let me start with some code:
function sendAjax(data, type)
{
$.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
$.when(sendAjax(someData, 'url')).then(function(data){
console.log(data); //undefined
});
$.when(sendAjax(someOtherData, 'url')).then(function(data){
console.log(data); //undefined
});
the issue i'm having is that data comes in as undefined
if i use success in the $.ajax the data comes in fine
The main idea here is that i should write the sendAjax() method once and use it through the application, but i don't think i set it up properly
ant ideas?
You need to return the promise return by $.ajax() from sendAjax
function sendAjax(data, type)
{
return $.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
Related
Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
I am trying to get data from a server depends on logged in user's name.
I succeed to get correct object, but I failed to get only certain part of it.
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
$("#docDepartment").val(data.responseText);
$("#docDepartment").prev().html(data.responseText);
console.log(data.responseText);
console.log(typeof data.responseText);
}
});
},
That empName gets each logged in users' empNameTrim value in my DB.
The type of data is object and responseText is string.
And its output looks like following:
I want to make the value of docDepartment equals to the value of department which will be SM in this case.
Thank you in advance.
EDIT: I followed Loïc Faure-Lacroix's tips, modified my code like following:
1st
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
var doc = JSON.parse(data.responseText);
$("#docDepartment").val(doc.department);
$("#docDepartment").prev().html(doc.department);
console.log(doc.department);
console.log(typeof doc.department);
}
});
},
2nd
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
complete : function(data) {
$("#docDepartment").val(data.responseJSON.department);
$("#docDepartment").prev().html(data.responseJSON.department);
console.log(data.responseJSON.department);
console.log(typeof data.responseJSON.department);
}
});
},
3rd
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
})
.done(function (data) {
$("#docDepartment").val(data.department);
$("#docDepartment").prev().html(data.department);
console.log(data.department);
console.log(typeof data.department);
})
},
All of them works fine. Choose whatever you like.
If jQuery isn't parsing to JSON, use JSON.parse to do it on the responseText... That said, according to the documentation here, if you go to the data types section, you should read the following:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
So you should be using this:
$("#docDepartment").val(data.responseJSON.department)
But to make your code cleaner, It might be better to use the following form:
getDepartmentByEmp : function (){
var empName = $.trim($(".temp-test").html());
console.log(empName);
var request = $.ajax({
contentType : "application/json",
dataType : 'json',
type : "GET",
url : "<c:url value='/app/general/add/getDepartment/'/>" + empName,
})
request.done(function (data) {
$("#docDepartment").val(data.department);
$("#docDepartment").prev().html(data);
console.log(data);
console.log(typeof data);
})
request.fail(function () {
...
})
},
The main difference is that the done callback should be called with the final data. While the complete one is called with a jqXHR object. It will get called only on success while complete is always called even on errors.
If I understand your question correctly, you need to parse the JSON object. I believe jQuery makes your response JSON automagically. So, the following should work for you.
$("#docDepartment").val(data.responseText.department);
This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 8 years ago.
my web app as the following structure in ajax requests:
$.ajax({
type : "GET",
url: '...',
dataType: "xml",
success: function(xml) {
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "....",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
$.ajax({
type : "GET",
url : "...",
dataType : "xml",
success : function(xml) {
},
error : function(xhr) {
alert(xhr.responseText);
}
});
}
});
I need all the resquests that are beeing made here to finish before i do something else. Because i need them to load content into a div. and then append that to a html element in my code.
And i dont want to use (document).ajaxStop because that will ruin my code later on.
How can i achieve this?
You can use differed($.Deferred) Objects to make your code look more clean,
Every $.ajax request returns you a differed object, and use them with $.when and .done() combination like the following
$.when(req1, req2, req3).done(function (resp1, resp2, resp3) {
//This will be executed on the success of all three requests
})
In your case you can do as follows
var req1 = $.ajax({type:"GET", url: "..."});
req1.done(function (resp1) {
// This will execute after the first request is done
var req2 = $.ajax({type:"GET", url: "..."}),
req3 = $.ajax({type:"GET", url: "..."}),
req4 = $.ajax({type:"GET", url: "..."});
$.when(req2, req3, req4).done(function (resp2, resp3, resp4) {
// when other three request are done
});
// If there are arbitrary number of requests, please consider the following
var requestsArray = [],
numberOfRequests = 10;
for (var i=0; i<numberOfRequests; i++) {
var request = $.ajax({type:"GET", url: "..."});
requestsArray.push(request);
};
$.when.apply(null, requestsArray).done(function () {
// You can collect the responses in the same order from `arguments`
var responses = arguments;
});
});
Deferred objects provide a very nice way to handle callbacks,
To know more on Deferred objects check this out http://api.jquery.com/category/deferred-object/
jQuery's $.ajax returns a promise ($.Deferred) by default. So you don't have to use callbacks and you can use these promises instead. Then using the $.when function you can create a new promise which will wait for these 3 promises to finish and the do all actions you need.
Look at the example in the bottom of the linked page to see how it works.
Edit: If the documentation is right then it should look like this:
$.ajax({
type : "GET",
url: '...',
dataType: "xml"
})
.then(function (xml) {
return $.when(
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "....",
dataType : "xml"
}),
$.ajax({
type : "GET",
url : "...",
dataType : "xml"
})
);
})
.then(function (res1, res2, res3) {
var xml1 = res1[0], xml2 = res2[0], xml3 = res3[0];
});
But I didn't test it so I don't know if it's really right.
I think you can use Jquery Deffer, like that.
Serial call
$.ajax('http://echo.jsontest.com/id/1')
.then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/2')
}).then(function(result){
console.log(JSON.stringify(result));
return $.ajax('http://echo.jsontest.com/id/3')
}).then(function(result){
console.log(JSON.stringify(result));
});
Paralel call
$.when(
$.ajax('http://echo.jsontest.com/id/1'),
$.ajax('http://echo.jsontest.com/id/2'),
$.ajax('http://echo.jsontest.com/id/3')
).then(function(result1, result2, result3){
console.log(JSON.stringify(result1[0]));
console.log(JSON.stringify(result2[0]));
console.log(JSON.stringify(result3[0]));
})
I'm trying to post a form data using JQuery to a remote servlet.
I can see that the server receives the data and also returns status code 200 and a response string of "{result: 'success'}"
But the ajax call doesn't return with the done or fail functions (if I add an always function than I can see that it is being called)
Here's a code snippet of the client side:
`
var dataParams = 'email='+email+'&password='+password;
var url = 'http://127.0.0.1:8888/signup';
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json",
done: function() {
console.log("done!");
hideSignUp();
showThankYou(); },
fail: function() {
console.log("fail!");
}
});
`
Seems like I'm missing out on something, but can't seem to find what.
Note that I'm using JQuery 1.8.3 so success is deprecated.
Any thoughts?
Try:
var url = "http://127.0.0.1:8888/signup";
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function() {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
Try chaining your callbacks, rather than setting them as object fields:
$.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function (xhrResponse) {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function (xhrResponse, textStatus) {
console.log(textStatus);
}).always( function () {
console.log("I'm done with this.");
});
By chaining your callbacks, you guarantee execution of at least one (complete).
I am making a simple ajax request using jquery . Below is my ajax function .
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
return data;
}
}
});
}
here is my function calls :
var items = {
"type" : 'POST',
"url" : ajaxGetUrl,
"data" : arrParam['data'],
"data_type" : 'html'
};
var msg = makeJqueryAjaxRequest(items);
Now don't know why my makeJqueryAjaxRequest function always returns the null value. If I alert the data in the success : I'm getting the data perfect . But when I try to return it gives me the null value
You can't return value from an Asynchronous callback function.
Because success is a async callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated