Json of jquery form plugin cannot be acquired - jquery-plugins

I will upload the file by using jquery form plugin, and question on the phenomenon of process of $.ajaxForm becoming timeout when the response data is json.
Processing by the servers end is done without trouble, and the response data is returned in the shape along as long as it sees with firebug the json form.
However, I think that $.ajaxForm cannot acquire data. Hereafter, it is a part of processed code.
code
$('#upload').ajaxForm({
cache: false,
dataType: 'json',
type: 'POST',
error: function(xhr ,status ,error ) {
alert('error occured. Status:' + status
+ ' --Status Text:' + error
+ ' --Error Result:' + xhr.statusText);
},
timeout: 1000,
dataType:'json',
data:{ 'path':'path' , 'type':'type' },
complete: function(){
alert('complete');
},
success:function(data){
alert('success');
},
});
response
(firebug)
header
Connection close
Content-Length 155
Content-Type application/json; charset=utf-8
Status 200
data
json
{"type":"json","message":"complete process"}
<i>(A browser)</i>
①download json data
②alert('error occured. Status:timeout --Status Text:timeout --Error Result:n/a')
③alert('complete')
</pre>
When dataType was html, success was able to be processed.
Moreover, when it is $.ajax, json becomes success.
Are there a settlement plan?It asks suitably.

try setting up the contentType like
$('#upload').ajaxForm({
cache: false,
dataType: 'json',
contentType:"application/json; charset=utf-8",
type: 'POST',
error: function(xhr ,status ,error ) {
alert('error occured. Status:' + status
+ ' --Status Text:' + error
+ ' --Error Result:' + xhr.statusText);
},
timeout: 1000,
data:{ 'path':'path' , 'type':'type' },
complete: function(){
alert('complete');
},
success:function(data){
alert('success');
},
});

Related

ajax - GET request keeps using same old cookie on each session

Here is my two ajax requests:
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded ",
url: "https://example.com/j_spring_security_check",
data: { j_username: "mmm#mmmm.com", j_password: "mmmm" },
error: function (request, status, error) {
alert("POST LOG IN REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
$.ajax({
type: "GET",
dataType: "json",
xhrFields: {
withCredentials: true
},
url: "https://mmm.com/rest/xxx/",
success: function(output, status, xhr) {
var flight = output;
alert(flight[0].flight.toAirport.name);
//return flight;
},
error: function (request, status, error) {
alert("GET ALL FLIGHTS REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
When I run the code and use firebug - the second request keeps using the same old cookie in every new session. What I want to happen is that the second request will use the cookie from my first POST(login) request. I have tried several variations of withCredentials: true/false and crossDomain: true/false on both requests.
When i clear the cookies, the get request will create it's own cookie. Then I refresh the page to let the script run again. The POST request will create a new cookie(as it should), but the get request will re-use the cookie it made before.

.ajax JSONP parsererror

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.

My Ajax POST is coming up as an error even though I am returning 200

I am making an AJAX post to a Jersey Resource. I build an image and return it. The issue is, no matter what status I return, Ajax thinks it is an error. I can actually use the error message (via error.responseTest) and it works fine. But it is ugly. What do I return to make it a success? I have returned OK(200), Accepted(202) and Created(201). All of them give me an error message but in my Console Network tab, I get a success (green with the proper status).
I am returning it like this:
return Response.status(Response.Status.ACCEPTED).entity(image).header('Content-Type',"image/png").build();
My JS code:
$.ajax( Monocle.config.Sightline.jobUrl + "/sightline", {
type: "POST",
processData: false,
data: JSON.stringify({
Lat1: Monocle.Sightline.BBOX(feature,2),
Long1: Monocle.Sightline.BBOX(feature,1),
Lat2: Monocle.Sightline.BBOX(feature,4),
Long2: Monocle.Sightline.BBOX(feature,3),
OrgLat:observerCoords[0].lat,
OrgLong:observerCoords[0].lon,
ObHeight: feature.attributes.observerHeight,
TargHeight: feature.attributes.targetHeight,
OuterRadius: feature.attributes.outerRadius,
LVA: feature.attributes.lowerVertAngle,
UVA: feature.attributes.upperVertAngle,
sAzimuth: feature.attributes.startAzimuth,
eAzimuth: feature.attributes.endAzimuth,
outputType: "MAX"
}),
contentType: "application/json",
dataType: "json",
success: function( results ){
var graphic = new OpenLayers.Layer.Image(
Monocle.currentWidget.name + " Destination " + featurenum,
"data:image/png;base64," + results,
new OpenLayers.Bounds(Monocle.Sightline.BBOX(feature,1), Monocle.Sightline.BBOX(feature,2), Monocle.Sightline.BBOX(feature,3),Monocle.Sightline.BBOX(feature,4)),
new OpenLayers.Size(580, 288),
{ isBaseLayer: false,
opacity: 0.3,
displayOutsideMaxExtent: true
});
feature.legionObject = graphic;
graphic.relatedlayer = Monocle.currentWidget.name + " Destination " + featurenum;
Monocle.Map.map.addLayer(graphic);
},
error: function(errMsg) {
// TODO: really handle any errors
}
});
Setting dataType: "json", means that your response is to be json which it isn't that would cause the error so just remove it.
Also is your image data has to be base64 encoded to make a data uri.

Handling AJAX Origin errors, caused by the Chrome Extension

Is there way to handle AJAX Origin errors from Chrome's extensions ?
Denying load of
chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json.
Resources must be listed in the web_accessible_resources manifest key
in order to be loaded by pages outside the extension.
I tried this:
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'json',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
but got nothing in variables. error status is "0", error message is empty.
You can try using the jsonp format. This often gets around cross-origin errors.
$.ajax({
url: 'chrome-extension://kldbdjcbjohfhddpicldkbifbkcdanid/data.json',
datatype: 'jsonp',
success: function(xhr) {
alert('ok');
},
erro r: function(xhr, status, err) {
alert('status: ' + xhr.status + ' - ' + err);
}
});
Sounds like you are attempting to load this resource from a content script, based on the error.
You have to explicitly add either the individual extension resources, or patterns that match your extension resources, in the manifest via web_accessible_resources. Your error message states this is the solution.
Once you've done this, you can construct the URL using chrome.extension.getURL(resourcePath).
Here's an excerpt from my manifest:
"web_accessible_resources" : [
"*.html"
]
And here's the code I'm using to request my HTML template file:
var url = chrome.extension.getURL("template.html");
$.get(url,function(data, textStatus, jqXHR){
console.log("Got the template!");
console.log(data);
},"html");

How do I know if a JSON string has loaded?

Forgive me, I am a complete JSON newbie here. I'm trying to load a file of json information from an external file, and I'm not sure how I can tell if the information has loaded or not. Here's what I have so far:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(string) {
data = $.parseJSON(string);
console.log(data);
alert(data);
document.write(data);
},
url: 'http://www.site.com/mystuff.php'
});
});
I've tried putting all kinds of stuff to see if the info has loaded, as you can see, and nothing has. How do I know if I've even gotten anything? I would really appreciate any help!
As already pointed out, two things:
You don't need to parse the string when setting the datatype as JSON
Check if the request returned successfully at all
Which could look like this:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(json) {
console.log(data);
},
error : function(xhr, text) {
console.log('An error occurred', xhr, text);
},
url: 'http://www.site.com/mystuff.php'
});
});
When setting the datatype to JSON you also have to make sure that mystuff.php sets the Content-Type header to application/json:
<?php
header('Content-Type: application/json');
?>
No need to parse to json again.. you can directly use the object
Also add the error Function to keep a check if you are getting any error..
$(document).ready(function(){
$.ajax({
dataType: 'json',
beforeSend : function() {
console.log('Before Ajax Request Starts !!');
},
success: function(data) {
console.log(data);
alert(data);
document.write(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Error occurred: " + errorThrown);
},
beforeSend : function() {
console.log('Ajax Request Complete !!');
},
url: 'http://www.site.com/mystuff.php'
});
});
This makes sure you have feedback at every step..

Resources