Returning post data [duplicate] - php

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
$.post("../js.php", {state: state},
function(data) {
return data;
});
Here's my jquery code. Like you can see it sends a post request to js.php.
Here's the code for js.php.
{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";
$result = $mysqli->query($query);
$num_rows = $result->num_rows;
echo $num_rows ? $num_rows : 0;
Now, when I alert the "data" back in the js file then it displays fine. But when trying to return it or assign it to a variable it does not work. The console tells me that the variable that has been assigned the value of data is undefined.
Any thoughts?
Updated code:
var data = null;
$.post("../js.php", {state: state},
function(response) {
data = response;
});
console.log(data);
Still not working. :(

the function in the post is a callback function, you cannot return anything from it since there is no one to return it to.
You need to use the data retuened inside the callback, for example:
$.post("../js.php", {state: state},
function(data) {
$('.someClass').html(data);
});

The callback you pass to asynchronous methods such as $.post are executed some time in the future, once the async call has returned. The JavaScript execution has moved on and is now somewhere else, so there is nowhere for your callback to return to.
Imagine it like this:
//Some code... executed as you would expect
var data; //Currently undefined
$.post("../js.php", {state: state}, function(response) {
//Callback is executed later, once server responds
data = response; //No good, since we already executed the following code
return response; //Return to where? We have already executed the following code
});
/* More code... we carry on to this point straight away. We don't wait for
the callback to be executed. That happens asynchronously some time in
the future */
console.log(data); //Still undefined, callback hasn't been executed yet
If you need to work with the data returned by the async call, do so in the callback.

var data = null;
$(...).click(function(e) {
$.post("../js.php", {state: state},
function(response) {
data = response;
});
});
After that just access data variable. Keep in mind that its value will be null unless the post request is done.

The example you posted will do nothing EVERY TIME because AJAX calls like this are ASYNCHRONOUS (that's what the A in AJAX stands for).
If you want to be able to use the value of the output, add a hidden element to your page with a unique ID that contains the value. Then you can access that element through javascript.

Thats because, the ajax call is asynchronous. You should never return a value from a callback function. Do the job in the callback or trigger an event.

Related

jquery each json variable bug

I have a strange bug. When I try to run my code:
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
});
alert(firstJson);
The alert I get is: "undefined".
Why did I get this instead of getting 9?
What am I missing here?
(the each loop runs without issue and there are values in the JSON)
At the end, 9 changes to some other value.
Thanks
Async functions my friend. Your alert is being called before your .getJSON request has been finished. You'll need to use a callback function to get the correct alert.
Because when you call alert(firstJson) the asynchronous $.getJSON call has not yet completed, so firstJson has no value associated with it. If you move your alert into the $.each function or after the $.each, and at the end of $.getJSON, it will have a value.
The variable doesnt have a value when alert is called. You'll have to wait getJSON is over, using done().
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
}).done(function() {
alert(firstJson);
});
References:
done()
$.getJSON

Pass a variable from a get query in javascript

I am trying to pass the value of a parameter outside a $.get jQuery in javascript. I read that I should somehow do that in synchronous mode but I couldn't find a solution.
Here is my code:
var flag;
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
flag=data;
});
document.write(flag);
where I get undefined as a result.
Thanks!
write it inside the callback function
try this
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
//this is the callback function and runs when get gets completed
flag=data;
document.write(flag);
});

Get Session value based on ajax success

I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});​

Why does this Javascript function alert my value but not return the same value?

I am using the jquery plugin datatables and am trying to take advantage of the fnRender function to manipulate some data.
I have a php script that returns a JSON string from my $.post. Here is a sample response that I get from each post: {"description":"myvalue"}. I got this from the Google Chrome Developer Tools.
Here is my post function:
$.post("functions/getDescription.php", {gpn:oObj.aData[1]},
function(data) {
returnedVal = jQuery.parseJSON(data);
var test = returnedVal.description;
//alert(test);
return test;
});
Here is my php script:
$passedVal = mysql_real_escape_string(($_POST['gpn']));
$descriptionPrint = array('description' => "");
include 'db_include.php';
$getDescription = "SELECT part_number_description, description FROM unit_description
WHERE part_number_description = '$passedVal' ";
$result = mysql_query($getDescription,$db) or die(mysql_error($db));
while ($row = mysql_fetch_array($result)) {
extract($row);
$descriptionPrint = $description;
echo json_encode(array('description' => $descriptionPrint));
}
There is only one value returned from each query.
Every row alerts the right value but returns undefined.
If I replace javascript function with only a return value of a string or any generic value it works fine.
I feel like there has to be something silly I'm missing in all this. Any help is much appreciated and please let me know if you need more information (I know troubleshooting something running in a plugin like datatables can be frustrating). Thanks.
Because $.post does not return the return value of the anonymous callback function you pass to it as its third argument.
Since Ajax is asynchronous, $.post even returns before the callback function is executed.
If you want to do something when the data gets back from the server, then the callback function has to to it (or call another function to do it).
This is the same reason that the following wouldn't work:
var were_you_expecting_sunshine = $('button').click(function () {
return "sunshine";
});

Can't get data back from an Ajax get request

Been playing with this for too long now!
I'm using codeigniter.
I am trying to get some data back from an Ajax get request. Simply I want to check a MySQL DB to check if there is some data in there mathcing a given date. A simple true or false will be fine for the return.
Here is my request, followed by the PHP. The PHP does return the correct result into $data, but when it gets back to the Ajax request, the alert(data) is called and shows up as blank... nothing there.
Any ideas what I'm doing wrong?
Thanks
function get_appointment_data(request_date){
$.ajax({
url: 'http://localhost/doctor_today/booking/retrieve_cal_data',
type: 'GET',
data: request_date,
success: function(data){
alert(data);
}
});
}
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
return $data==null;
}
I am not familiar with codeigniter but you must output the result of the function. Instade of 'return' you must use 'echo' to return result to ajax request.
You have to echo the result, otherwise your ajax won't receive a result and the success handler won't execute. Here is what I'm going to use for this case, I'm using the simpler .post function for that task with one key difference - I specify 'json' at end of it which means I'll get a json object as a result from my .post (you can search Google for this). The next key is to use encode the result I wanna get in json format using PHP's json_encode function and echo its result. We don't really need to return a result via the normal 'return' statement. So...
The script:
var url = 'http://example.com/ajax_function';
var data = null;
$.post(url, data, function(data) {
if(data.ok)
alert('Everything is fine!');
else
alert('Ops!');
}, 'json');
The server side:
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
echo json_encode(array('OK' => $data==null));
}
If you call directly the PHP function it should output something like
{ "OK": "true" }
which later on will be translated to an javascript array
data[OK] = true;
which you can use as you wish.
Cheers,
Stan.
P.S. I haven't tested the code but it should pretty work.

Categories