Get Value of Ajax changed field - javascript

I am making an ajax call, it looks like this:
$.ajax({
url: "index.php?id=70&type=999",
type: 'post',
data: form + '&sort=' + val,
success: function(response)
{
$(".listing").load(location.href + " .listing");
$(".count").load(location.href + " .count");
},
complete: function (response) {
alert( $(".count").val());
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
}
});
So, as you can see 2 classes "listing" and "count" are changing, this works fine. After i am trying to alert the NEW value of the "count" class, but it is always giving me the actual one. And just after the alert, the value changes. But doesn't complete: mean that the call is made after the success: function? Why the alert is being made first and gives me the old value before the ajax call?

Try changing you're code like this:
$.ajax({
url: "index.php?id=70&type=999",
type: 'post',
data: form + '&sort=' + val,
success: function(response)
{
$(".listing").load(location.href + " .listing");
$(".count").load(location.href + " .count", function(){
alert( $(".count").val());
});
},
complete: function (data) {
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
}
});

alert value inside success:
$.ajax({
url: "index.php?id=70&type=999",
type: 'post',
data: form + '&sort=' + val,
success: function(response)
{
$(".listing").load(location.href + " .listing");
$(".count").load(location.href + " .count", function(){
alert( $(".count").val());
});
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
}
});

The issue is because the complete fires after the first AJAX request completes, not after the second/third AJAX request which you create by calling load(). If you want to know the .count value you need to put a callback in the load() method:
$.ajax({
url: "index.php?id=70&type=999",
type: 'post',
data: form + '&sort=' + val,
success: function(response) {
$(".listing").load(location.href + " .listing");
$(".count").load(location.href + " .count", function() {
// get the value here, after load() completes
console.log($(".count").val());
});
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
}
});
Also note that you could improve the code by calling the URL in both load() calls just once and then extracting the required information from the response, something like this:
$.ajax({
url: "index.php?id=70&type=999",
type: 'post',
data: form + '&sort=' + val,
success: function(response) {
$.ajax({
url: location.href,
success: function(html) {
$(".listing").html($(html).find('.listing'));
$(".count").html($(html).find('.count'));
}
});
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
}
});

Related

Setting up Ajax Promise

I have a function to add a record to database that uses Ajax with C# web service. Prior to updating DB I call another function to validate input that also uses Ajax. So, I need the validate function to finish before continuing with the one adding the record.
I know due to asynchronous nature of ajax I have to use promise/deferred but just can't get my head wrapped around it to set it up properly.
Updated
function validate() {
var deferred = $.Deferred();
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
}).done(function (result) {debugger
if (!result || result.d === "") {
isValid = false;
}
else {
var duplicate = JSON.parse(result.d);
switch (duplicate) {
case DuplicateData.Name:
isValid = false;
break;
case DuplicateData.ID:
isValid = false;
break;
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
deferred.resolve(isValid);
return deferred.promise();
//return isValid;
}
$(document).on("click", "#btnAdd", function (event) {debugger
$.when(validate())
.then(function(isValid) {
if (isValid) {
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
}).done(function (result) {
addNewRecord();
)}.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
})
});
function addNewRecord(){
// add record to DB
}
As you are only dealing with a boolean result, there is no reason to return a value, you can just resolve or reject the deferred.
function validate() {
var $defer = $.Deferred(function() {
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
})
.done(function (result) {
// If there's no result
if (!result || !result.d) {
$defer.reject();
}
else {
// This call shouldn't be necessary, as dataType: "json" will call it for you
// Unless you double-encoded it.
var duplicate = JSON.parse(result.d);
// Not sure about this part, what's DuplicatedData and what does result.d contain?
switch (duplicate) {
case DuplicateData.Name:
case DuplicateData.ID:
$defer.reject();
}
}
// Everything checks out, resolve the promise
$defer.resolve();
})
.fail(function (jqXHR, textStatus, errorThrown) {
// If there was a network or server error
// alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
$defer.reject();
});
});
return $defer;
}
$('form').on("click", "#btnAdd", function (event) {
validate()
.done(function() {
// If the validation passes
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
})
.done(function (result) {
// Creation successful
addNewRecord();
}).fail(function (jqXHR, textStatus, errorThrown) {
// Creation failed
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
})
.fail(function(reason) {
// Called in case of a validation error
console.log("Validation error");
});
});

jQuery select the appended element in an ajax call dose not work

In the code, .moneychoose is the div in moneychoose.jsp. $(".moneychoose") can not be selected in the ajax call.
$("input[name='money']").on("click", function() {
if ($("#money").find(".moneychoose")) {
$(".moneychoose").remove();
}
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
});
But if i add console.log($(".moneychoose")) after "append external html",
$(".moneychoose") in ajax call can be selected. why? however, the $(".moneychoose") after "append external html" still can not be selected.
$("input[name='money']").on("click", function() {
if ($("#money").find(".moneychoose")) {
$(".moneychoose").remove();
}
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
console.log($(".moneychoose"));
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
});
Your confusion is because console.log is not synchronous.
Your error is because you have a race condition between two AJAX requests.
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
And
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
In order to ensure that .moneychoose is available in the success callback of $.ajax, you will either need to use a Promise that resolves once both requests have succeeded, or you will need to wait to execute one of the requests until the other has finished.

jquery pass 2 ajax result outside ajax

I have a simple working ajax with result.
jQuery.ajax({
type: "POST",
url: my_url_query
success:function(response){
}
}).done(function(response) {
//Assuming the response for currChild1 is 12
res1 = response;
window.$vars = { currChild1: res1 };
window.$vars = { currChild2: res2 }; //----> How will I do this
$.getScript( "assets/js/main/request_add_staff.js");
});
Is it posible to create another ajax to pass another vars to the getscript
Anyway I think This is what im looking..
async:false
kinda long code.
but if you have an idea to shorten this... that will do.
jQuery.ajax({
type: "POST",
url: "index.php/form_dashboard/get/Senior/"+ dataid,
success:function(response){
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
},
async:false
}).done(function(response) {
res_Senior = response;
});
//Result for Junior
jQuery.ajax({
type: "POST",
url: "index.php/form_dashboard/get/Junior/"+ dataid,
success:function(response1){
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
},
async:false
}).done(function(response1) {
res_Junior = response1;
});
window.$vars = { currChild: res_Senior, currChildJunior: res_Junior };
$.getScript( "assets/js/main/request_add_staff.js");

Can I call ajax function inside another ajax function? [duplicate]

Is it possible to make an ajax request inside another ajax request?
because I need some data from first ajax request to make the next ajax request.
First I'm using Google Maps API to get LAT & LNG, after that I use that LAT & LNG to request Instagram API (search based location).
Once again, is this possible, and if so how?
$('input#search').click(function(e) {
e.preventDefault();
var source = $('select[name=state] option:selected').text()+' '+$('select[name=city] option:selected').text()+' '+$('select[name=area] option:selected').text();
var source = source.replace(/ /g, '+');
if(working == false) {
working = true;
$(this).replaceWith('<span id="big_loading"></span>');
$.ajax({
type:'POST',
url:'/killtime_local/ajax/location/maps.json',
dataType:'json',
cache: false,
data:'via=ajax&address='+source,
success:function(results) {
// this is where i get the latlng
}
});
} else {
alert('please, be patient!');
}
});
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
Call second ajax from 'complete'
Here is the example
var dt='';
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
dt=data;
/*Do something*/
},
complete:function(){
$.ajax({
var a=dt; // This line shows error.
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
/*do some thing in second function*/
},
});
}
});
This is just an example. You may like to customize it as per your requirement.
$.ajax({
url: 'ajax/test1.html',
success: function(data1) {
alert('Request 1 was performed.');
$.ajax({
type: 'POST',
url: url,
data: data1, //pass data1 to second request
success: successHandler, // handler if second request succeeds
dataType: dataType
});
}
});
For more details : see this
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});

Repeat jQuery ajax request

I make an ajax request to the server. And sometimes I receive 502 error. So, if that happened error() method is called.
How can I repeat request if receive an error? The code should looks like this:
$.ajax({
url: 'http://server/test.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
//some actions here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
// here I want to repeat the request like "this.repeat()"
},
});
you can do it like this,
function ajaxCall(){
$.ajax({
url: 'http://server/test.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
//some actions here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall(); // recursion call to method.
},
});
}
Put your code in function and call this function again. like:
function ajaxFunction()
{
....
error:function(){ajaxFunction();}
}
With calling limit, as suggested by Hadas:
function ajaxCall(count) {
count = typeof count == 'undefined' ? 0 : count;
limit = 5;
if(count === limit) return;
// no need to specify cache and type:
// type has 'GET' as default value
// cache has default value of false if the dataType is jsonp
$.ajax({
url: 'http://server/test.php',
dataType: 'jsonp',
timeout: 32000,
async: false
}).done(function(data) {
// some actions here
}).fail(function(jqXHR, textStatus, errorThrown) {
count += 1;
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
// 500, 1000, 1500, 2000 etc
setTimeout(function() {
ajaxCall(count);
}, 500*count);
});
};

Categories

Resources