.ajax JSONP parsererror - ajax

I'm trying to use an ajax call to bring back data from a web api. I wrote 2 similar functions and neither work. I can see the data come back through Fiddler, but it won't go to the success call, for both of the functions below. What am I doing wrong? The data comes back in both functions in Fiddler, it just doesn't go to success.
Here is attempt 1:
function PopulateDivisions()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert(data);
$("#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);
}
});
}
Error: jQuery19102671239298189216_1382022403977 was not called : parser error
Here is the data Fiddler is showing comes back:
[{"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 attempt #2:
function PopulateDivisions2()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisionsJsonP',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function(data) {
//data = JSON.parse(data):
alert(data);
$("#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("PopulateDivisions2: " + thrownError + " : " + ErrorText);
}
});
}
Error: myJsonMethod was not called : parsererror
Here is the data Fiddler shows is coming back:
"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 \"}]);"

contentType: 'application/json; charset=utf-8' Tells your server that you are sending JSON data, but you don't have any data you are sending. Try leaving that setting out.
If you were to brows to your url in the browser do you get json back?
I'm not sure if this would matter, but I would remove the error setting because it says in the jQuery Ajax documentation that This handler is not called for cross-domain script and cross-domain JSONP requests.
I would try to run this with the least amount of configuration like this:
$.ajax({
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions',
dataType: 'jsonp',
success: function(data) { console.log(data); }
});
See if this works and then build on top of it. Without jsfiddle it's hard to debug what's going on.
Here is a link that should be a good resource for you: Basic example of using .ajax() with JSONP?

function PopulateDivisions2(){
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisionsJsonP?callback=?',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
jsonpCallback: "myJsonMethod" });
function myJsonMethod(data) {
//data = JSON.parse(data):
alert(data);$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
}}
Can you try the above code? I have removed the success callback and included callback in query string.

Related

Is there anything I'm missing in ajax

Here is the code i've used it's always going to error but working call back but cant able to read any data always showing undefined
$.ajax({
type: "GET",
url: "http://localhost:59817/api/patients?callback=?",
dataType: "jsonp",
jsonpCallback: function (data, textStatus, jqXHR) {
debugger;
console.log(data);
},success: function (){},error: function (){}
}
)
here is A sample of Jquery Ajax, Try it
$.ajax({
url: "Url/" + value,
type: "Get",//Or Post,Put
data: {dataname: value}
}).done(function(response){
alert("Response is: " + response);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Cross-origin ajax not working

I am having a problem while using cross-origin ajax.
I know it's a common question but did not get any solution for it yet.
$.ajax({
type: "GET",
url: url,
data: {id:id},
dataType: "jsonp",
crossDomain: true,
contentType: "application/jsonp; charset=utf-8",
async: false,
success: fnsuccesscallbackk,
error: function(xhr, error){
alert(error);
},
jsonpCallback: fnsuccesscallback
});
function fnsuccesscallback(data){
alert(data)
}
…but getting undefined response in callback function.
Is there anything wrong what I am doing.
After a lots of RND finally i got the solution of this.
Ajax function:
$.ajax({
type:"GET",
url:'https://www.url.com/welcome/test_js',
data:{name:'xyz'},
crossDomain:true,
dataType: "jsonp",
jsonp: 'fnsuccesscallback',
success: function(data) {
alert(data.name)
}
});
In the Php function:
function test_js() {
echo $_GET['fnsuccesscallback'] . "(" . json_encode($_GET) . ")";
}

How to use ajax with autocomplete in jquery

I have the following jquery with ajax call? My webservice returns dataset.
Here is the code:
$(document).ready(function(){
$('#ctl00_ContentMain_ddlRegions').change(function(){
region = $(this).val();
alert(region);
});
});
$('input[type="text"]').autocomplete({
$.ajax({
async: true,
type: "GET",
url: "~/EmailActivation/EmailActivation.asmx/GetIsoFromRegion",
data: "{'option':'" + region + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(data,status){
alert("success");
}
});
minLength: 4 });
});
Right now there is an error in my code so, I cannot even display alert to show region. Error is generated from autocomplete section.
When I remove autocomplete section, script works.
What do I need to change and how can I make my autocomplete work with the data coming from webservice?
Thank you

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

$.ajax is not working

In my web page there is a textbox to get the scanned barcode value. Once we scan the barcode it has to get details from the database. I am creating the change event for the textbox.
Problem: $.ajax is not working.
Code:
var target = $('#txtBarcode'), val = target.val();
target.change(monitor());
function monitor() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
}
You are trying to pass 'monitor' to the change method but you're actually calling it. It should look like this (no parens)
var target = $('#txtBarcode'), val = target.val();
target.change(monitor);
function monitor() {
You can always declare it inline too:
var target = $('#txtBarcode'), val = target.val();
target.change(
function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
});
Add an error handler.
Make sure your relative URL is right.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
// ...
}
});
EDIT: Dan is right about your change handler.
You can copy some answers posted here, and at least one of will likely to work, but you won't get the intimate knowledge of why. Here's an additional way:
Since you use asp.net, put the break point in the first line of HomePage.aspx/SearchProduct. This ensure that the request goes to the right URL on the server.
Step all the way through this method to make sure there's no exception that gets thrown.
Use FireFox and install Firebug (even if you target IE and have no intention to make it run on FF). You can inspect the http response.
Add an error handler in addition to the success handler.

Resources