Jquery Ajax Problem - javascript

Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?

In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.

To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.

$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});

Related

Taking data out of the Ajax Jsonp

I want to taking data out of the Ajax Jsonp.
Why doesn't work this app?
Please Help.
var res;
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
}
});
$("div").html(res);
https://jsfiddle.net/q6vfgemp/
The data is retrieved correctly but since the request is async you cannot set the html outside of the success callback, put it inside the success callback and it will work.
Also it's a good practice to console.log the data when you're not sure where the problem is to make sure it is retrieved successfully.
Edit: Here is why the async: false option is not working, check the accepted answer for the details.
In JSONP you should add a callback parameter to the request.
The response would be a script calling your callback with the requested data.
So, you should call a URL like this:
http://domain.ext/?callback=xxx
And you should have a function with name "xxx":
function xxx(data) {
// Here you can manage the received data
}
Also, the requested resource should support JSONP, if it doesn't you will not receive anything in your callback.
Since the request is asynchronous, your code sets the "div" before the result is actually retrieved. In order to make sure you retrieve the result, and then set the div, do this:
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
$("div").html(res);
}
});

Getting json on cross domain with jsonp using jquery

I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc

jquery ajax : what is the actual request sent?

What is the actual url sent to the server when I use the jquery ajax? And how do I access that value? For example, consider the following code:
<script>
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: {name:'Smith',age:10},
success: function(data) {
...
}
beforeSend: function(){
console.log(url);
// what do I put here to see what is being sent
// I am expecting to see "response.php?name=Smith&age=10"
}
...
So essentially what variable holds "response.php?name=Smith&age=10".
Thanks.
No variable holds
response.php?name=Smith&age=10
because you aren't sending the data as a query string. This would happen if you issued a GET request, but doesn't with a POST request.
You're sending the data in the request body of an HTTP post. The data is the data that you assigned to the data parameter. You don't need to round-trip it through jQuery's ajax methods. You've got it already. It's:
{name:'Smith',age:10}
does jQuery's interpretation of your data really matter?
The settings object is fully populated when beforeSend is called:
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
console.log(settings.data);
}
$.ajax({ type: "POST", ... }) will log
response.php
name=Smith&age=10
and type: "GET"
response.php?name=Smith&age=10
undefined

async ajax inside another ajax

I have an ajax call inside ajax. Problem is I have to wait second ajax finish because until that time browser freezes. Why is this happening if I set it to async true? I dont want to wait for any response from this second inner ajax and I dont need any response from it. It is just an email notification to some users based and needs parameters from first ajax.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html',
success: function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
},
Thanks all, now I found out the problem is not maybe in those ajaxs. User wants to move to another webpage through load when click on menu icon.
$('.main_body').find('.container').load(url);
This dont works until those ajax finish. So not complete browser freezes only I cannot navigate to next page.
Common, Ajax is indeed async but You should remember that a success handler is called only when the ajax call is complete whether sync or async So this inner ajax call can be called only when the first is complete. There is no way you can access inner ajax call without first being completed. All you can do is make an ajax call via callback on the success handler of the outer ajax.
This is not an exact answer to your problem but only a help/checklist :
The most common causes of the UI freezing on making an ajax call when the call is async:true are as follows:
A lot of Dom manipulation taking place on response of the call.
A lot of data is being sent by the server and processing it requires time.
If a session is being maintained and it is not closed before multiple ajax callbacks (this happens to avoid race conditions).
Something on the server side goes wrong/extremely slow on the ajax call and the client side is stuck.
Network speed is too slow.
EDIT: Based on the response from asker , to help others if they face similar issue.
Is there a redirection involved which is locking up with ajax response.
It is highly unlikely that the UI freezes despite all the check points mentioned above taken care of.
In any case the solution might be one of the following approaches :
Try making a call to the second ajax after a timeout of like 5000 ms.
Try promises : how does jquery's promise method really work?
(worst way)Try using an iframe to make the requests.
try to use promise.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html'
}).promise().then(function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
})

AJAX .responseText want to assign to global variable

For CORS AJAX request, the best and cross browser supported example is the following one as I know...
http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/
The above one working as properly but callback return only local variable not global. Can somebody give me the idea how to make global variable return from AJAX callback.
In jQuery code, if I would like to return global variable result I can do as follow:
jQuery.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: url,
success: function(data){
result = data;
},
error: function(xhr){
alert("Request cannot complete");
},
async: false
}).responseText;
But above jQuery.ajax() POST example is not fully support by IE.

Categories

Resources