How to get request url in a jQuery $.get/ajax request - javascript

I have the following code:
$.get('http://www.example.org', {a:1,b:2,c:3}, function(xml) {}, 'xml');
Is there a way to fetch the url used to make the request after the request has been made (in the callback or otherwise)?
I want the output:
http://www.example.org?a=1&b=2&c=3

I can't get it to work on $.get() because it has no complete event.
I suggest to use $.ajax() like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
craz demo

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
So you would use
$.ajax('http://www.example.org', {
dataType: 'xml',
data: {'a':1,'b':2,'c':3},
context: {
url: 'http://www.example.org'
}
}).done(function(xml) {alert(this.url});

Related

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

Storing ajax jquery into a variable and acessing it with the variable

Can I call jquery ajax from a variable like this ?
var save = $.ajax({
type: "POST",
dataType: 'json',
url: "functions/ajaxInsertCheck.php",
data: dataString,
cache: false,
success: function(response){
alert(response.a);
}
// call ajax jquery
save
How can I call that request like its a function? Can anyone help?
You need to use a function. Functions encapsulate behavior we will want to invoke in the future. You can pass functions arguments which indicate how you want the function to execute.
Functions are typically used when we want to have reusable bits in our code or for code clarity:
function save(){ // declare a function and call it save
return $.ajax({ // a return means we're letting people from the outside use it
type: "POST",
dataType: 'json',
url: "functions/ajaxInsertCheck.php",
data: dataString,
cache: false,
success: function(response){
alert(response.a);
}
});
}
Then you can call it from your own code:
save(); // call the save function performing this action.
Note that there are plenty of examples of functions already in your code like alert and $.ajax that were defined by you by the browser and jQuery respectively.
If you mean, can you defer execution of the call as you've written it, then no. The call is executed immediately.
Check out the documentation at http://api.jquery.com/jquery.ajax/ - particularly under the heading "The jqXHR Object". It's different depending on the version of JQuery, but you get back an object that implements the Promise interface.
But using javascript features, you can make a function:
function saveFunction() {
$.ajax({
type: "POST",
dataType: 'json',
url: "functions/ajaxInsertCheck.php",
data: dataString,
cache: false,
success: function(response){
alert(response.a);
}
});
}
saveFunction();

.ajax returning json object, but no success

I am using JQuery's .ajax method to call to a URL which returns a JSON encoded string. I can see the object returned from the GET in the debugger, but for some reason I'm not falling into the success function. Any ideas?
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
If you look at the documentation, it shows that the proper way to make a jsonp request requires a jsonCallback parameter.
Code:
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie&jsonCallback=?',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
Fiddle: http://jsfiddle.net/xrk4z6ur/2/
jQuery will by default use callback=? for a jsonp request. In this case, the API accepts jsonCallback. Adding jsonCallback=? to the url will let jQuery handle it properly.
If you are using jsonp you should specify a callback GET parameter like &callback?
On server side return the callback with your desired data as argument (json encoded)

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.

Jquery Ajax Problem

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

Categories

Resources