continue jQuery after mysql data has loaded - php

I am using jquery and php along with WordPress to access data from a mysql database.
I managed to retrieve that data but would like jquery to wait until all the data has been retrieved.
Below is the pertinent code segment.
Both alert commands display nothing because the data has not finished loading.
How can I re-code this?
jQuery(document).ready(function ($) {
load_qs('foo');
alert($(".all-qa-free").val());
//////////////////////////////////////////////////////////////////////////
function load_qs(data) {
var data = {
action: 'load_question_set',
async: false,
cache: false,
qset_id: data
};
$.post(the_ajax_script.ajaxurl, data, function (response) {
var mydb_data = $.parseJSON(response);
$("#all-qa").val(mydb_data.qa);
alert($(".all-qa-free").val());
return;
});
}
});

Ajax calls are asynchronous, while the JS executes synchronously. jQuery/JavaScript initiates the ajax calls and immediately goes to the next line for executing. It doesn't wait for the response to come from the server.
Solution:
Do all the processing, which you want to do on server response in the callback function itself. In your case, in the below function:
function(response) {
var mydb_data = $.parseJSON(response);
$("#all-qa").val(mydb_data.qa);
alert ($(".all-qa-free").val());
return;
}
Otherwise you will keep facing this issue. Try putting alert in the callback function. It'll definitely work.
One more thing, you are putting value in id "#all-qa" and fetching data from ".all-qa-free", please check if you are doing this right.
--
HappyCoding

You should set async: true in your ajax call.
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.
If you set async: true then that statement will begin it's execution and next statement will be called regardless of whether the async statement has completed yet.

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

How to set a state between sending a request and receiving the data with AJAX

i'm trying to get so information from a php function that i call in ajax so i want to do a state between the sending data and receiving them
$.ajax({
//Some code
})
// putting a state between the two
.done(function( json ) {
//Some code
});
Thanks
The #Daan answer is not correct at all because AJAX is asynchronous by default, then you are not sure if .ajaxStop will execute after the ajax call ends. #GuyT comment I think is a good point.
I have two variants:
The first one: execute the startWait() just before the ajax is called and stopWait() inside the .done() and .fail() statements. Look:
startWait();
$.ajax({
//setup the ajax call
})
.done(function(res){
//do some code
stopWait();
})
.fail(function(res){
//do some code
stopWait()
});
The second one is execute startWait() and stopWait() inside the .done():
$.ajax({
//setup the ajax call
})
.done(function(res){
startWait();
//do some code
stopWait();
});
If you ask me, I prefer the first one, because I make sure to show a loader (or run code) while the ajax is run and I stop it when all is finished even if it falls.
For your question, the first one is the better choice too.
As you said in the comments you want some sort of waiting time use ajaxStart and ajaxStop.
$( document ).ajaxStart(function() {
//ajax start create a loader or something
});
$.ajax({
}).done(function(data) {
});
$( document ).ajaxStop(function() {
//stop the loader
});

How can make sure code after my ajax request only runs if the request was a success?

I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}

Problems with multiple PHP functions in the same file

I want to make an AJAX call to a php file called functions.php, where I have mutliple related functions (all making database changes to accounts, ie. add, edit, delete). I've been struggling with this, because the AJAX call seems to work fine, but the response that comes back from the server is empty (content-lenght: 0). I went back to square one and just used AJAX to send data to a php file that only contained the php code to handle that one call (ie. no functions), and it works fine. As soon as I wrap that simple statement into a function, it fails again. So something I'm doing causing the php not to send a respone when I'm wrapping it in a function.
Do you have to call a specific php function somehow from your ajax script, or somewhere in your form element? How does the php file know which function you're requesting in your ajax call if there are multiple functions? Or does it just sort it out by matching the $_POST element with the data being sent over, regardless of which function that $_POST element is in?
I suspect that my PHP code is to blame:
function delete_account(){
require(ROOT_PATH . "/inc/database.php");
$deleteAccount = $_POST['accountName'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
return;
}
Also, when I press the submit button and my ajax call is fired off, it immediately returns the success message in the browser, and as I'm watching the Network tab on my google dev tools window, the success message is displayed seemingly before the php file is even loaded. I've tried setting async: false.
Adding AJAX code:
function deleteAccount(){
event.preventDefault();
var accountName = $('.account_name').filter(":selected").attr("name");
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {accountName:accountName},
async: false,
success: function(response){
$('#results').html(response + " has been deleted.");
}
});
};
If you have multiple functions in your PHP file, then you can do something like:: pass in extra parameter in you jQuery ajax, like:
$.ajax({
url: "some_file.php?action=get_accounts"
}).done(function() {
$( this ).addClass( "done" );
});
and in your PHP file use switch to call appropriate function depending on value of action variable in your ajax, like:
//in PHP
.....
$action = $_GET['action'];
switch ($action) {
case "get_accounts":
//call the function
get_accounts();
break;
case "otherFunction":
....
break;
}

Where am i going wrong - ajax

I have the following link-
Grab Coupon
Where i have initialized $var3 like this
$var3 = "brand1,camp2";
The code for the function popitup2() is -
<script language="javascript" type="text/javascript">
function popitup2(id) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
success: function(){
alert( "Data Saved: " );
}
});
newwindow2=window.open('','name','height=225,width=350');
var tmp = newwindow2.document;
....some more code...
...at end...
return true;
}
</script>
Now when i click the link ex.com opens up without any alert i.e without running the php script through ajax and the javascript after that. If i remove the ajax call from the function popitup2() then the remaining javascript gets executed correctly.
Agree with previous answer that you are executing asynchronous Ajax request.
From documentation Async parameter may not work in 2 cases: Cross-domain requests or if dataType: "jsonp".
If you are doing crossdomain request, I can suggest only:
Grab Coupon
<script type="text/javascript">
function popitup2(id, link) {
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
context: link,
success: function(){
alert( "Data Saved: " );
window.location = $(this).attr("href");
}
....
return false;
});
With such approach we track clicking for sure.
There is another problem with such approaches, that tracking server should be fast otherwise, user will wait long time till navigate to resource.
What's happening here is that you're performing an asynchronous AJAX request, meaning that when you perform the request, the rest of your function continues to run. When the AJAX result comes back, it then fires the alert in your success function, but since you've clicked a link, you've navigated away from that page already.
Try adding an async: false to the ajax function's parameters to wait for the result to come back before continuing, like so:
$.ajax({
url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
async: false,
success: function() {
alert( "Data Saved: ");
}
});
You are passing two arguments to JS function. But function prototype (first line) accept only one. This lead into JS error.

Categories