Jump to content

$.post Request using jQuery returns undefined


Temnis

Recommended Posts

Hey guys!

 

This might be a very simple and stupid question, but here we go :Bucktooth:

 

I have a php - function (getDropDownMenue($what, $id)). This functions works perfectly and returns a string, containing html - code. Now I am doing somthing on my Website and I need that string. To get it, I have a javascript Function (getDropDownMenue($what, $id)). It performs a POST Request using jQuery, asking the getDropDownMenue.php to return that string. The problem is, I only get "undefined" instead of the string.

 

What am I doing wrong?

 

functions.js - File

function getDropDownMenue($what, $id){	$.post("getDropDownMenue.php", { what : $what, id : $id }, function($echoData) {		return $echoData;	});	}

getDropDownMenue.php - File

<?phprequire_once('functions.php');// Übergabe der Variabeln$what	=	$_POST["what"];$id		=	$_POST["id"];// Funktionsaufruf$string = getDropDownMenue($what, $id);echo $string;?>

functions.php - File

function getDropDownMenue($what, $id){	$string = "Irgendwas ist in der Funktion getDropDownMenue(php) schief gegangen...";	if($what == "ROOMPIC_URL"){		// Select Drop Down Menü		$string = '<select id="' . $id . '" name="Grundrisse"><option value="" disabled selected>URL</option>';		// Finde alle Dateien in dem Verzeichniss		if ($handle = opendir('roomPics')) {			while (false !== ($file = readdir($handle))) {				if ($file != "." && $file != "..") {					$string = $string .  "<option value="" . $file . "">" . $file . "</option>";				}		    }		    closedir($handle);		}		$string = $string .  "</select>";	}else{		$string = "Der Funktion getDropDownMenue(php) ist die " . $what . " nicht bekannt!";	}	return $string;}
Link to comment
Share on other sites

function getDropDownMenue($what, $id){	$.post("getDropDownMenue.php", { what : $what, id : $id }, function($echoData) {		return $echoData;	});	}
That function does not return a value, that's why the return value is undefined. The return statement you have there returns from the callback function, not the getDropDownMenue function. Ajax requests are by default asynchronous, so the code does not wait for that request to finish before the getDropDownMenue function finishes. You could make the request synchronous, but that's going to make the browser wait and become unresponsive. It's best to use a callback function. The callback function that you send to the post method should do whatever you need to do with the response from the ajax request. If you want to show how you're using that function then I might be able to suggest something more specific.
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...