Javascript executes before getting result from a ajax call - php

I have the following code which displays session data.The problem am facing is even if the session has value and the ajax get that data the alert that I have put below the function call getValFromSession(qes) always shows null data.I think this is due to the asynchronous execution of ajax with in the javascript.So I put some extra code as shown in the function
getValFromSession(qid).How can I overcome this asynchronous issue?
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
function getValFromSession(qid)
{
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false
}).responseText;
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}

Try this:
var qes=$('#qsid_'+q).val();
var res=getValFromSession(qes);
function getValFromSession(qid)
{
$.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
cache: false,
async: false,
success: function(data) {
alert(data); // alert here in successHandler
$('#select_'+).val(parseInt(data));
}
})
}
/*controller*/
function getValFromSession()
{
echo $_SESSION['time'][$_REQUEST['qid']];
}
Hope this helps.

$.ajax provides you with a success, error and complete callback handlers. Populate your response text in those handlers because the way you have implemented is synchronous and would execute immediately instead of after the request completes.
Docs

You can put your code into a function and call that function on success event of AJAX as below
---
---
return $.ajax({
url : site_url_js+"controller/getValFromSession",
type : "POST",
data : "qid="+qid,
false,
async: false,
success: finalfunction
---
---
function finalfunction(res)
{
alert(res);//always shows null value
$('#select_'+).val(parseInt(res));
}

Related

WordPress post request in my plugin

I am trying to make a post request in my plugin, but I am not sure if it is reaching the desired function or not. I try to echo, return value but nothing seems to work. Here is my jquery
$.post({
url: "http://localhost/tutorials/wordpress/wp-admin/admin-post.php",
type: "POST",
cache: false,
data: {
action: "add_order"
// parameters:parameters,
//orderAddress : orderAddress,
//order : order
},
success: function(response) {
console.log(response);
secondStep.hide();
pricing.hide();
$('.thirdStep').show();
}
});
My function on the WordPress server end is this
function prefix_admin_add_order() {
echo 2; // or return 2;
}
Just trying to return anything from the function and trying to console log it in the response. But it doesn't work. Any pointers?
Your Php file must be as a page template and you must address it like this :
http://yourdomain.com/ajax
and in your jquery you must put this url

How can I set a jquery var to be another jquery ajax functions callback

Sorry for my terms incase they are incorrect, but I have a php function that I am going to interop with ajax so I can use a php function to get a value for a jquery variable.
So now I am just at the point where I have received the ajax callback and would like to set the jquery variable to the response value I got back. Here is my code as an example:
$(document).ready(function() {
$('body').videoBG({
position:"fixed",
zIndex:0,
mp4:'', //This is where I want to use the ajax response value
opacity:1,
});
})
jQuery.ajax({
type : "POST",
url : "index.php",
data : {
request : "getvideo_Action"
},
success : function(response) {
alert(response);
//Do my response stuff
}
});
So basically what I want to do is set the 'Mp4' var(or is it property?) with the value that I get from the response. Can anyone help me out with this? Thanks.
You can put the entire thing inside the success function, like this:
jQuery.ajax({
type: "POST",
url: "index.php",
data: {
request: "getvideo_Action"
},
success: function (response) {
$('body').videoBG({
position: "fixed",
zIndex: 0,
mp4: response,
opacity: 1
});
}
});

Returning the fetched data from a ajax call to another function

So I have this javascript function, it sends an ajax requests to fetch a value from a php variable.
The function looks like so:
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
return cartlimit;
},
error: function(output){
}
});
}
When I call this function from another function like this:
var cartlimit = get_cart_limit();
my variable "cartlimit" is undefined.
So the ajax call is working, but why can't I return the value to another function?
To early for me, my brain isn't working properly! :)
Cheers!
If you change the scope of the cartlimit variable and disable Asynchronous request, get_cart_limit() should return the correct value
function get_cart_limit() {
var cartlimit;
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
async: false,
success: function(output) {
cartlimit = output;
},
error: function(output){
}
});
return cartlimit;
}
The variable cart_limit is only set once the AJAX request successfully terminates.
Why?
The AJAX call is asynchronous, i.e. get_cart_limit() ends before the actual answer comes back from the server
The anonymous function that you specified as success: function(output) { /*...*/ } is called when the answer comes back from the server.
If you call another function that tries to access cart_limit before the success function has been executed, you will get an undefined value.
Even if you execute a return statement in the success function, it is a different function from get_cart_limit() and it gets executed at a different time, so you will not obtain the desired effect of assigning the return value to whatever variable.
One to solve this problem is to have the function that needs cart_limit be called by the anonymous success function.
function get_cart_limit() {
$.ajax({
url: '/w2w/ajax/',
data: {
_action: 'get_cart_limit'
},
type: 'post',
timeout: 10000,
success: function(output) {
var cartlimit = output;
alert(cartlimit); // this gives me the correct value.
function_that_needs_cart_limit();
},
error: function(output){
}
});
}
Declare this cartlimit with a global scope. Decalre this before the function starts
var cartlimit;
function get_cart_limit() {
$.ajax({
...................
Here your cartlimit will be declared only after the ajax function get success .
But execution of another scripts may take before this success. So it will get undefined
Your can pass your output data to the specified function like this
var cartlimit = get_cart_limit(output);

How to set ajax returned value as a variable

I have the following ajax call which executes successfully:
function fnFormatDetails ( oTable, nTr )
{
var aData = oTable.fnGetData( nTr );
var memberid = 'memberid='+ aData[6];
$.ajax({
type: "POST",
url: "shout.php",
data: memberid,
success: function(html) {
//$("#shout").html(html);
var sOut = html.returned_val;
}
});
return sOut;
}
If I remove the commented out line ($("shout").html(html) and use a div on my page, the results display fine. However, there is a second function which would use the HTML results from sOut and display accordingly in the proper position.
The PHP file in shout.php simply 'echos' HTML to the page (which is then returned and displayed accordingly.
I am unfortunately unable to set the variable sOut currently based on the results of my ajax call. What am I missing?
If you'd like your function to return what returns from the AJAX call, you need to make the call synchronously. Also, this is assuming the result of "shout.php" is plaintext. If it's JSON or otherwise, you need to set the dataType property in your call to $.ajax.
function fnFormatDetails ( oTable, nTr ) {
var aData = oTable.fnGetData( nTr );
var memberid = 'memberid='+ aData[6];
var result;
$.ajax({
type: "POST",
url: "shout.php",
data: memberid,
async: false,
success: function(data) {
result = data;
}
});
return result;
}
First of all you are defining sOut within a success callback method and therefore it would not be available to fnFormatDetails.
Secondly by default $.ajax works in async mode, therefore whenever "return sOut" is called, the success callback would have not executed !
I would suggest you to call some method from the success which would do the process based on the html.returned_val, or you can pass async:false in $.ajax to make that call synchronized.
thank you #Matt Huggins
async: false
this small code change, fixed the issue i was having since morning. :)

jQuery Ajax success variable

I have the next function. My PHP script returns an array with element error with value 'ERR':
var updatePaymentType = function(plan_pt_id, pt_id){
var error = null;
var data = new Object()
data["function"] = "update";
data["payment_type_id"] = pt_id;
data["plan_payment_type_id"] = plan_pt_id;
data["data"] = $("#saveform").serializeArray();
$.ajax({
type: "POST",
url: "<?=ROOT_PATH?>/commission/plan/edit/id/<?=$this->editId?>",
data: data,
dataType: "json",
success : function (data)
{
error = data['error'];
alert(error); // All works. Output ERR
}
});
alert(error); // Not work. Output null
return error;
};
My function should returns an error. But it returns null.
Thank you very much.
AJAX requests are asynchronous, meaning the value isn't set until after you already returned (the success handler runs later, when the server responds with data).
To return the error type you have to make it synchronous with async: false like this:
$.ajax({
async: false,
type: "POST",
...
But this locks up the browser, it's better to call whatever uses the value from your success callback, like this:
success : function (data)
{
var error = data['error'];
functionThatTakesError(error);
}

Categories