JSONP json callback method not called : parsererror - ajax

I have the following ajax function using jsonp:
function PopulateDivisions1()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions?callback=?',
dataType: "jsonp",
//jsonp: false,
jsonpCallback: "myJsonMethod",
success: function(data) {
alert('yes');
$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
},
error: function(xhrequest, ErrorText, thrownError) {
alert("Original: " + thrownError + " : " + ErrorText);
}
});
}
I am getting the following error:
myJsonMethod was not called : parsererror
If I look at Fiddler, I am getting the following data back, I added the callback name to the front, as I saw that suggested, if I take it out it still doesn't work.
"myJsonMethod([{\"Id\":1,\"Description\":\"Executive\",\"Name\":\"Executive \"},{\"Id\":2,\"Description\":\"ASD\",\"Name\":\"Administrative Services Division \"},{\"Id\":3,\"Description\":\"COM\",\"Name\":\"Communications \"},{\"Id\":4,\"Description\":\"CP\",\"Name\":\"Contracts and Procurement \"},{\"Id\":5,\"Description\":\"PMD\",\"Name\":\"Program Management Division \"},{\"Id\":6,\"Description\":\"RED\",\"Name\":\"Research and Evaluation Division \"},{\"Id\":7,\"Description\":\"IT\",\"Name\":\"Information Technology \"}])"
Here is the method in my controller:
public string GetAllDivisions(string callback)
{
var divisions = _DivisionModel.GetAllDivisions();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(divisions);
string result = callback + "(" + json + ");";
return result;
}
I'm not getting to my success call, what am I missing or doing wrong?

You dont have to specify a success callback because the jsonp callback will happen automatically as the server side code will return javascript in case of jsonp.
Refer the below answer for working example.
Using jquery jsonp returns error callback function was not called

Related

Ajax call always triggers fail handler even though success is returned by the server

The following JavaScript always triggers the fail handler even though the return value is success from the server side:
$.ajax(payload)
.done(function(data, statusText, jqxhr) {
document.getElementById('myModal').innerHTML = "<p>Record Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.fail(function(jqxhr, statusText, errorThrown) {
document.getElementById('myModal').innerHTML = "<p>Record Not Saved ... </p>";
modal.style.display = "block";
refresh_html_page(document.getElementById("sheetname").value);
})
.always(function () {
// Re-enable the inputs
$inputs.prop("disabled", false);
});
Returned JSON string:
[{"result":"success","row":11}]
Any thoughts?
Good news. I was able to crack it. The solution was as follows:
Set up a call back function in the payload
Have a dummy action in the newly created call back function
Prefixed the call back function name in the server side while creating the jasonp response
Client side:
function handleJSONPResponse(data, status, request) {
console.log('response', data);
}
// Fire off the request to /form.php
var payload = {
crossDomain: true,
url: "https://script.google.com/macros/s/XXXXXXXXXXXXXXXXX/exec",
method: "POST",
dataType: "jsonp",
data: serializedData,
jsonpCallback: 'handleJSONPResponse'
};
Server Side (e is the payload sent from client):
return ContentService
.createTextOutput(e.parameters.callback + '(' + JSON.stringify({"result":"success", "row": nextRow})+ ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
It was wonderful solving the problem. Thank you very much for your kind inputs and encouragement. Much appreciated.

Return bool value from Ajax

I am calling the below function from my .aspx page and all I want to check whether this function returned true or false. I tried many things but I get undefined as result.
I am calling function using below code
if (IsIncetiveAllowed())
{
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
function IsIncetiveAllowed() {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
return true;
else
return false;
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
Please Help!
If you pass a callback to the IsIncetiveAllowed function, you can make it execute your code with the result of the ajax call after it has been made.
IsIncetiveAllowed(function(is_allowed) {
if (is_allowed) {
sCondition = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']";
xmlNode = $(XMLCombos).xpath(sCondition)[0];
XMLCombos.firstChild.removeChild(xmlNode);
}
else {
// Not allowed
}
});
function IsIncetiveAllowed(callback) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "pp060.aspx/CheckIncentiveAllowed",
data: "{'typeOfApplication': '" + m_TypeOfMortgage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d)
callback(true);
else
callback(false);
},
error: function (response) {
MessageBox.Show("An error occurred checking IsIncetiveAllowed method.", null, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
});
}
First off, you never want to use synchronous Ajax. Synchronous Ajax blocks the browser, the user interface freezes and the user cannot scroll, click or do or anything while synchronous requests load. Don't use them.
Second, it's useful to break up your operation into separate parts. What you have here is
A part can post JSON to the server
This is the most re-usable part, it works the same for all JSON you want to post to any URL.
A part that knows how to talk to to a specific endpoint on the server
This is the second most reusable part, it can send any data to a specific endpoint.
A part that uses this endpoint
This is the least reusable part, it can send specific data to a specific endpoint.
It makes sense to have a separate function for each part. jQuery supports this easily, because all Ajax methods return promises, and promises can be given from function to function.
Part 1, as a jQuery extension for maximum re-usability:
$.fn.postJSON = function(url, data) {
return $.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data)
});
};
Part 2, as a stand-alone function. Note that I am matching the remote API endpoint name. You can write more functions like this to wrap other API endpoints.
function checkIncentiveAllowed(typeOfApp) {
return $.postJSON("pp060.aspx/CheckIncentiveAllowed", {
typeOfApplication: typeOfApp
}).fail(function (err) {
MessageBox.Show("An error occurred in checkIncentiveAllowed method.",
null, MessageBoxButtons.OK, MessageBoxIcon.Error);
console.log(err);
});
}
Part 3, to be used inside an event handler for example:
checkIncentiveAllowed(m_TypeOfMortgage).done(function (response) {
var path = ".//LISTENTRY[VALUEID='" + m_sIncentiveReleaseId + "']",
xmlNode = $(XMLCombos).xpath(path)[0];
if (response.d && xmlNode) {
xmlNode.parentNode.removeChild(xmlNode);
} else {
// not allowed
}
});
Well this is happening because the ajax call is asynchronous. You can put your code present in if block to the ajax callback function to implement your logic

How To Use Object Returned By VB.NET Web Service

I have a Javascript function that passes a string into a VB.NET Web Method. Here is the Javascript
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + e);
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial
Here is the VB.NET web Method. The Web Method simply takes the string and sends it back to the Javascript:
<WebMethod( )> _
Public Function testWebService(str As String) As String
Return str
End Function
When the Web Method returns successfully my AJAX block returns the following message:
"It worked: [object Object]"
So my question is, how do I use the returned object? The object should be a string containing the words "hello world" but how do I access the string value?
ASP.Net WebMethods wrap their return values in a JSON object with a d property. (You can see this in the response body in the browser's developer tools)
You need to write e.d to get the actual value.
if you do:
$(e).text()
You'll get your text;
So change this to be:
function jQuerySerial() {
//I SET A VARIABLE TO THE STRING I IS PASSED INTO MY WEB METHOD
var str = "{ 'str': 'hello world'}";
//THEN I PASS IT INTO MY VB.NET WEB METHOD
$.ajax({
type: "POST",
url: "test_WebService.asmx/testWebService",
data: str,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (e) {
alert("It worked: " + $(e).text());
},
error: function (e) {
alert("There was an error retrieving records: " + e);
}
});
}//END jQuerySerial

JSON returned AJAX post jQuery undefined

I am using jQuery to get a list of Names as JSON string -
`
$.ajax({ type: 'POST', url: "../Names.aspx", dataType: 'json', contentType: "application/json; charset=utf-8", data: "NAME=ALL_PROFILES", success: function (data, textStatus, jqXHR)` {
var html = '';
var obj = jQuery.parseJSON(data);
$.each(obj, function (key, val) {
html += '<option value="' + val + '">' + val + '</option>';
alert("Success" + val);
})
$('#selName').append(html);
$('#selName').selectmenu('refresh');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error ' + jqXHR.val + errorThrown.val + textStatus.val);
}
});
The back end is an asp.net page, and when I debug I get the string as "{"Name":["Maria","John","Raj","Rosh","Tony","Name","test3","test4","test5","test6"]}", which I put in JSONLint and validated. It returns an undefined error in the AJAX request above. If I try with a single string "Name":"John", it works perfectly. The function for adding option is not correct for an array of JSON strings(I will work on it once it enter the success block), but I don't understand why it returns an undefined error when it is returning a valid JSON string. Any help would be appreciated.
If your aspx page returns valid JSON and you are using dataType: 'json', you should not use jQuery.parseJSON() on the returned data, since jQuery already parses the returned JSON string into an object.
If you use "Name":"John" it is not valid JSON, so JQuery enters the error callback.
Put an extra paranthesis around the result and it works.It is strange since JSONLint is not validating it now

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources