Ajax starts too late... Really inconvenient [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have this problem with AJAX. I run the code and the ajaxString is undefined when the code is printed even though the Ajax code is pretty much called before the return statement. When I try to retrieve AJAX after the HTML generation and printing, the AJAX is defined so it makes me think that the return is called before AJAX gets the chance to finish. Any way around this? Here is my current code:
var ajaxHTML;
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
setTimeout(function(){$("#menu_container").html(generateHTML(str))},500);
$("#container_demo").fadeIn(500);
}
}
function generateHTML(source){
if (source =='d') {
return makeSchoolComboBox() + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
ajaxHTML = data;
}
});
return ajaxHTML;
}

Since AJAX is asynchronous, you can't call it and then return straight after as the call is still taking place. You need to populate the menu container in the success callback, like this...
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
makeSchoolComboBox();
}
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
$("#menu_container").html(data + "Please Select a Level: " +
"<select id='selectedLevel'>" +
"<option value='level1'>l1</option>" +
"<option value='level2'>l2</option>" +
"<option value='level3'>l3</option>" +
"<option value='level4'>l4</option>" +
"</select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button>" +
"<button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>").fadeIn(500);
}
});
}

ajax query is asynchronous
function makeSchoolComboBox(next) {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: next
});
}
and run it as
makeSchoolComboBox(function(ajaxHTML){
//manipulations with here
})
Or you can pass async: false in your $.ajax, but all stops while ajax request processed in this case

If you need to keep the structure you're using (I'd make generateHTML and makeSchoolComboBox into a single function to keep it simple) then you can use promises.
Your code would then become:
function generateHTML(source){
if (source =='d') {
makeSchoolComboBox().then(function(data) {
return data + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
});
}
}
function makeSchoolComboBox() {
var d = new $.Deferred();
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function(data) {
return d.resolve(data);
}
});
}

Related

Jquery/JS function not applies

building html that use jquery to get data from web API.
In the beginning of my script I did a function that checks the value of dropdown (what is selected) and according to the selected it's fill the global variable.
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
}
after defining the function I calling it immediately to check it and fill the variable.
finally by Clicking on search it should check what selected from dropdown and according to that fill again the variable and start GET function with the modified URL
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Tried to debug it many ways but couldn't find why it's assigning that value.
Please assist as it should be so simple but I must missed something.
Here is the part of the code from the begining:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Don't:
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
Do:
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === "Canada") {
$seldom = '172.168.0.1';
}
See documentation of jQuery.val():
.val(value)
Description: Set the value of each element in the set of matched
elements.
value argument
Type: String or Number or Array
A string of text, a number, or an array of strings corresponding to the value of each matched element to
set as selected/checked.
So, calling $("#dropdomain").val('some value') writes a value to the $("#dropdomain") element. To read its value, call $("#dropdomain").val().
Try the code below:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === 'Canada') {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
This condition $("#dropdomain").val('Europa') is always writing and is being evaluated as true.
So, you need to compare the values:
var drop = $("#dropdomain").val();
if (drop === 'Europa') {
$seldom = '192.168.5.37';
} else if (drop === "Canada") {
$seldom = '172.16.0.1';
}

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

How to hide current page

I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}

Waiting for Ajax called DOM manipulation to finish

Sorry for the title but I had no idea how to call it.
I got some ajax call function that on success adds some HTML elements to the page:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
},
complete: complete()
});
};
Function does something on success where the most important is the .append and then this ajax function is called in some button .click function like this:
$(function() {
$("#product_list_add_btn").click(function(e){
ajax_submit_append(
form_data = {
product_name: $('.selectpicker option:selected').val(),
amount: $('#amount').val()},
"<?php echo site_url('admin_panel/new_order/add_product'); ?>",
'#add_product_result',
calculateSum
);
return false;
});
});
What I want to achieve is that calculateSum function (sums table columns) is called after .append is done via ajax.
For now, when I add calculateSum to ajax complete event it is still called before new row is added to the table with .append
Edit: I present You calculateSum, but I believe there is nothing faulty there.
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".countit").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#total_price').text(sum);
alert("test");
};
If I had to guess, I would say its something with click event?
How to fix this?
Try using jqXHR's done() method:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
}
}).done(complete);
};

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Categories