Jquery jsonp response error - Callback was not called - javascript

I'm trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I get an error in response. I don't need to execute it, I just need it in my script. In any format (the response is json but js doesn't understand it).
I can't affect on that domain so it's impossible to change something on that side.
Here's my code:
$.ajax({
url: url + '?callback=?',
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
window.jsonpCallback = function(response) {
console.log('callback success');
};

There are a few issues with your $.ajax call.
$.ajax({
url: url + '?callback=?',
// this is not needed for JSONP. What this does, is force a local
// AJAX call to accessed as if it were cross domain
crossDomain: true,
// JSONP can only be GET
type: "POST",
data: {key: key},
// contentType is for the request body, it is incorrect here
contentType: "application/json; charset=utf-8;",
// This does not work with JSONP, nor should you be using it anyway.
// It will lock up the browser
async: false,
dataType: 'jsonp',
// This changes the parameter that jQuery will add to the URL
jsonp: 'callback',
// This overrides the callback value that jQuery will add to the URL
// useful to help with caching
// or if the URL has a hard-coded callback (you need to set jsonp: false)
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You should be calling your url like this:
$.ajax({
url: url,
data: {key: key},
dataType: 'jsonp',
success: function(response) {
console.log('callback success');
},
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
JSONP is not JSON. JSONP is actually just adding a script tag to your <head>. The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.
JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.
Please read the docs: http://api.jquery.com/jquery.ajax/

var url = "https://status.github.com/api/status.json?callback=apiStatus";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'apiStatus',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Try this code.
Also try calling this url directly in ur browser and see what it exactly returns, by this way You can understand better what actually happens :).

The jsonpCallback parameter is used for specifying the name of the function in the JSONP response, not the name of the function in your code. You can likely remove this; jQuery will handle this automatically on your behalf.
Instead, you're looking for the success parameter (to retrieve the response data). For example:
$.ajax({
url: url,
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
success: function(data){
console.log('callback success');
console.log(data);
}
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You can also likely remove the other JSONP-releated parameters, which were set to jQuery defaults. See jQuery.ajax for more information.

Related

Returns error when consuming this php response

Return error in the query
From the browser the answer is correct.
$.ajax({
type: "POST",
url: url,
async: true,
contentType: " charset=utf-8",
dataType: "XMLHttpRequest",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});
The message says "error".
I see three issues. First, dataType is a choice of xml, json, script, or html, unless you did something really fancy. jQuery can guess it based on received data though, so there is normally no need to set it. But if you want to be explicit (assuming your page returns json):
dataType: "json"
Second, contentType value looks like some truncated thing. I would just completely remove it, as you are not sending any data and just requesting a page.
Finally, when you are sending no data and just requesting a resource, the best is to use GET.
All in all:
$.ajax({
type: "GET",
url: url,
async: true,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});

jQuery synchronous call

For rendering a dialog, i have two jQuery ajax calls. One to load the buttons and another to load the body of the dialog. I first call the function that loads the buttons (asychronous ajax call)
$.ajax({
type: "POST",
//async: false,
url: action,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#dialogButtons').html(result);
},
error: function (req, status, error) {
alert(req + " " + error + " " + status);
}
Then i call another similar ajax call to load the body of the dialog in asychronous fashion.
The buttons doesn't always show up. So I made
$.ajaxSetup({ async: false });
$.ajax({
asyc: false,
url: action
})
$.ajaxSetup({ async: true });
as per other stack overflow experts. i am seeing mixed opinions on this approach.
Please help me with the standard way to achieve this.
Do the second AJAX call in the success function of the first.
$.ajax({
type: "POST",
url: action,
dataType: "html",
success: function(result) {
$('#dialogButtons').html(result).hide(); // Will show it after 2nd AJAX call
$.ajax({
type: "POST",
dataType: "html",
url: otheraction,
success: function(result) {
if (result) {
$("#dialog").html(result);
$("#dialogButtons").show();
}
}
});
},
error: function(req, status, error) {
alert(req + " " + error + " " + status);
}
});
You also shouldn't have contentType: "application/json". You're not sending any post data, and $.ajax doesn't send JSON; if you had post data, it would be URL-encoded.

jquery ajax post request fails

trying to send an ajax post request
function ajaxCall(request_data) {
alert(request_data['table'] + request_data['name'] + request_data['description']);
$.ajax({
type: "POST",
cache: false,
url: "../src/api.php/InsertTo",
data: request_data,
dataType: "json",
contentType: 'application/json',
success: function() {
alert('good');
/* $('form').hide();
$('h3').append("Object Successfully Inserted!");*/
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown + textStatus);
}
});
it throws error every time, 'request_data' is an object and url return just a simple string for now, please find the problem
You have to use JSON.stringify() method.
data: JSON.stringify(request_data)
Also, contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
Can you try with the below code after using JSON.stringify on the request_data. As per the docs
"The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified."
As you are using dataType: "json" and contentType: 'application/json;' you should convert the javascript value to a proper JSON string.
Please find more in the below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
function ajaxCall(request_data) {
alert(request_data['table'] + request_data['name'] + request_data['description']);
$.ajax({
type: "POST",
cache: false,
url: "../src/api.php/InsertTo",
data: JSON.stringify(request_data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert('good');
console.log(data); // print the returned object
/* $('form').hide();
$('h3').append("Object Successfully Inserted!");*/
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown + textStatus);
}
});

Reliably complete Ajax request on page unload

I have a html/javascript application. When user refreshes the page or close the page i need to make a ajax request and then close the application.
I am using page unload event for this purpose.
I am calling
window.onbeforeunload=beforeFunction;
beforeFunction will make the ajax request. But when i check in fiddler i dont see the ajax request. However if i debug the application and execute each line with f10 then i see the ajax request in fiddler.
thats how my ajax request is formed:
$.ajax({
url: url,
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
dataType: 'jsonp',
success: function(json){
alert("success: " + json);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
$(window).on('beforeunload' function() {
$.ajax({
url: url,
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
dataType: 'jsonp',
success: function(json){
alert("success: " + json);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
});
Try this....

Ajax request after success result of other reqjest (.NET + jQuery)

I need to get xml document from a server, then client signs it and sends back to server.
At server side I have web method which saves document:
[WebMethod]
public static void SaveSignedDocument(string SignedData)
{
SignedCms signedCms = new SignedCms();
....
}
Then, I get document from a server and after success receive it I make client to sign it and send back. Here is Javascript
// get xml to sign
$.ajax({
type: "POST",
url: "Default.aspx/GetXMLReceipt",
data: "{'ITN': " + ITN + " }",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
// xml file was got
var xmlString = xmlToString(xmlData);
// Sign data
var SignedData = SignData(xmlString);
// Send it to server
$.ajax({
url: 'Default.aspx/SaveSignedDocument',
data: "{ 'SignedData': '" + SignedData + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){
alert('Document was successfully sent!');
}
error: function (data, status, jqXHR) {
alert('Send signed data failed - ' + jqXHR);
}
});
},
error: function (data, status, jqXHR) {
alert('Get data failed - ' + jqXHR);
}
});
The problem is that none of the alert at second requests ever fire. If I change request to synchronous everything is ok but why it does not work like written above? The server receives nothing and if we look to network traffic I see that request was interrupted. Why?
Encode your data properly, do not use any string concatenations. Here's the correct way:
data: JSON.stringify({ ITN: ITN }),
and on your second AJAX request:
data: JSON.stringify({ SignedData: SignedData })
The JSON.stringify method will ensure that you are sending valid JSON to your server by properly encoding the argument.

Categories

Resources