jquery pass 2 ajax result outside ajax - javascript

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");

Related

Jquery / JSON handle XHR Response

I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.
What I would like to do is basically say if successful do X, else do Y.
I have try using an if / else statement within the function, but it doesn't seem to work.
Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
EDIT: Working Code:
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
add this line to your return jQuery.ajax({}) function:
error: function(xhr, ajaxOptions, thrownError){
window.alert(thrownError);
}
hope this helps~

how to dynamically generate JSon object?

I was trying to send/receive JSon between client and server.
I generated JSon (I thought) by a function
self.gen_data=function()
{ //create request data
var input_array =self.input_value();
myJson={
request_type:1, //send request for problem 1
data_list:{}
};
for(var k=0;k<input_array.length;k++)
{
myJson.data_list[k]=input_array[k]; //a number in array
}
console.log(myJson);
return myJson;
}
can't read it on server
$.ajax({
type: "POST",
url: self.serverURI,
data: JSON.stringify(self.gen_data()),
dataType: 'json',
success: function (result)
{
//console.log(result);
alert(JSON.stringify(result));
//alert(result.a);
},
error: function (xhr, ajaxOptions, thrownError)
{
console.log(xhr);
}
});
on server
var data=req.body;
console.log("request_type: ",req.body.request_type);
console.log("data_list size: ",data.data_list.length);
/*
for(var i=0;i<data.data_list.length;i++)
{
console.log(data.data_list[k]);
}
*/
but it displayed as:
data_list size: undefined
try to read array elements caused error.
JSON.stringify() returns a JSON string, but it seems you want the JSON object.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Try without JSON.stringify:
$.ajax({
type: "POST",
url: self.serverURI,
data: self.gen_data(),
dataType: 'json',
success: function (result)
{
//console.log(result);
alert(JSON.stringify(result));
//alert(result.a);
},
error: function (xhr, ajaxOptions, thrownError)
{
console.log(xhr);
}
});

Getting error trying to submit data using JQuery ajax

When I try to run the following JQuery ajax, I get an error saying that a parameter is missing and it will not send the data. I can't find any syntax errors. What am I doing wrong?
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: fd,
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
Why not use jQuery native form encoder?
$.ajax({
...
data: $('#illustrationTypeForm').serializeArray(),
...
});
Try This
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: $('#illustrationTypeForm').serializeArray(),
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
To make ajax request using jQuery a type 'POST' you can do this by following code :
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Get Value of Ajax changed field

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);
}
});

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');
}
});

Categories

Resources