i have a javascript function to call ajax to write some stuff to database. So far it has worked on chrome and firefox without any problem. However, Safari randomly fails without much clue. (This is tested within localhost)
This is the error :
write failed : {"readyState":0,"status":0,"statusText":"error"}
This is my ajax function :
function writeToDB() {
var data = {
setting: 'some data'
} ;
$.ajax({
type: "POST",
url: 'Admin/write_to_db',
data: {
data:
btoa(unescape(encodeURIComponent(JSON.stringify(data))))
},
success: function(response) {
consoe.log('success');
console.log('response : ' + JSON.stringify(response));
},
error: function(response) {
console.log('write failed : ' +
JSON.stringify(response));
},
complete: function(response) {
console.log('completed');
},
});
}
I simplified the actual function for ease of reading. I have tried many similar responses given for a similar problem but nothing worked. Pls help me with this. Thank You.
Managed to fix the problem.
The above function writeToDB is triggered by a button click. So all that i had to do is add
event.preventDefault()
to the function. That worked!
I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from
I am not a JSON specialist and therefore I need help to solve a little problem.
When submitting a form, before the form closes, it returns 'Unexpected end of input'.
I have searched the Internet and this forum, I found nothing solving the problem. I hope you'll be able to help me sort it out.
So, to make it easier for you, what's going on?
The user requests a listing. He fills the form with a message and a price. The item_id is transmitted directly (and working as I get it working so far).
The form data are sent via JSON to a remote server (VPS) which un-json the data. However, in addition to the 'unexpected end of input', I got on my remote server 'Server response: 400 (Bad Request)'
I am almost sure it is due to this code and not the remote server one.
I have identified thanks to debug that the error is at the line :
JSON.parse(data);
$('#requestListingSubmit').click(function (evt) {
evt.preventDefault();
rL_form.hide();
rL_load.show();
rL_controls.hide();
rL_alert.empty();
var item_id = $(this).data('item-id');
var route = '/request';
$.ajax(
{
type: 'POST',
url: coreURL + route,
data:
{
'item_id': item_id,
'message': $('#message').val(),
'price': $('#price').val(),
},
success: function (data)
{
try
{
JSON.parse(data);
window.location = coreURL+'/account/listings?new';
}
catch(e)
{
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert(
{
type: 'danger',
message: 'Error: '+e.message
});
}
},
error: function (jqXHR, status, httperror) {
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert({
type: 'danger',
message: (jqXHR.responseJSON.message || httperror)
});
}
});
});
Thank you very much guys!
I'm using the Ajax.Request in prototype.js(1.6) like this:
new Ajax.Request(URL, {method: "get",
onSuccess: cbFn,
onCreate: function(req) {
$("fetchBtn").value = "Fetching..."
},
onFailure: function(req){
console.log(req)
alert("nima")
},
parameters: {"id": pmid}});
however there is a bug in cbFn, and when cbFn is called by Ajax.Request, it just stops in the statement which has bugs. However, it just stops silently that I can not see the error information in Firebug. I also tried onFailure, but it seems that it is not even called when onSuccess is failed.
Does anyone have ideas about how to check the debug information of cbFn function? Thanks!
I saw you have been use jquery in your java script. In that case, you can using the jquery ajax GET/POST to solve your problem with effiency.
Some thing like that:
jqxhr = $.get("example.php", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
jquery do better in multiple browser for you
I'm using ASP.Net MVC, but this applies to any framework.
I'm making an Ajax call to my server, which most of the time returns plain old HTML, however if there is an error, I'd like it to return a JSON object with a status message (and a few other things). There doesn't appear to be a way for the dataType option in the jQuery call to handle this well. By default it seems to parse everything as html, leading to a <div> being populated with "{ status: 'error', message: 'something bad happened'}".
[Edit] Ignoring the dataType object and letting jQuery figure out doesn't work either. It views the type of the result as a string and treats it as HTML.
One solution I came up with is to attempt to parse the result object as JSON. If that works we know it's a JSON object. If it throws an exception, it's HTML:
$.ajax({
data: {},
success: function(data, textStatus) {
try {
var errorObj = JSON.parse(data);
handleError(errorObj);
} catch(ex) {
$('#results').html(data);
}
},
dataType: 'html', // sometimes it is 'json' :-/
url: '/home/AjaxTest',
type: 'POST'
});
However, using an Exception in that way strikes me as pretty bad design (and unintuitive to say the least). Is there a better way? I thought of wrapping the entire response in a JSON object, but in this circumstance, I don't think that's an option.
Here's the solution that I got from Steve Willcock:
// ASP.NET MVC Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AjaxTest(int magic) {
try {
var someVal = GetValue();
return PartialView("DataPage", someVal);
} catch (Exception ex) {
this.HttpContext.Response.StatusCode = 500;
return Json(new { status = "Error", message = ex.Message });
}
}
// jQuery call:
$.ajax({
data: {},
success: function(data, textStatus) {
$('#results').html(data);
},
error: function() {
var errorObj = JSON.parse(XMLHttpRequest.responseText);
handleError(errorObj);
},
dataType: 'html',
url: '/home/AjaxTest',
type: 'POST'
});
For your JSON errors you could return a 500 status code from the server rather than a 200. Then the jquery client code can use the error: handler on the $.ajax function for error handling. On a 500 response you can parse the JSON error object from the responseText, on a 200 response you can just bung your HTML in a div as normal.
While Steve's idea is a good one, I'm adding this in for completeness.
It appears that if you specify a dataType of json but return HTML, jQuery handles it fine.
I tested this theory with the following code:
if($_GET['type'] == 'json') {
header('Content-type: application/json');
print '{"test":"hi"}';
exit;
} else {
header('Content-type: text/html');
print '<html><body><b>Test</b></body></html>';
exit;
}
The $_GET['type'] is just so I can control what to return while testing. In your situation you'd return one or the other depending on whether things went right or wrong. Past that, with this jQuery code:
$.ajax({
url: 'php.php?type=html', // return HTML in this test
dataType: 'json',
success: function(d) {
console.log(typeof d); // 'xml'
}
});
Even though we specified JSON as the dataType, jQuery (1.3.2) figures out that its not that.
$.ajax({
url: 'php.php?type=json',
dataType: 'json',
success: function(d) {
console.log(typeof d); // 'object'
}
});
So you could take advantage of this (as far as I know) undocumented behavior to do what you want.
But why not return only JSON regardless of the status (success or error) on the POST and the use a GET to display the results? It seems like a better approach if you ask me.
Or you could always return a JSON response, and have one parameter as the HTML content.
Something like:
{
"success" : true,
"errormessage" : "",
"html" : "<div>blah</div>",
}
I think you'd only have to escape double quotes in the html value, and the json parser would undo that for you.
I ran into this exact same issue with MVC/Ajax/JQuery and wanting to use multiple dataTypes (JSON and HTML). I have a AJAX request to uses an HTML dataType to return the data, but I attempt convert the data that comes back from the ajax request to a JSON object. I have a function like this that I call from my success callback:
_tryParseJson: function (data) {
var jsonObject;
try {
jsonObject = jQuery.parseJSON(data);
}
catch (err) {
}
return jsonObject;
}
I then assume that if the jsonObject and errorMessage property exist, that an error occured, otherwise an error did not occur.
I accomplished this by using the ajax success and error callbacks only. This way I can have mixed strings and json objects responses from the server.
Below I'm prepared to accept json, but if I get a status of "parsererror" (meaning jquery couldn't parse the incoming code as json since that's what I was expecting), but it got a request status of "OK" (200), then I handle the response as a string. Any thing other than a "parsererror" and "OK", I handle as an error.
$.ajax({
dataType: 'json',
url: '/ajax/test',
success: function (resp) {
// your response json object, see if status was set to error
if (resp.status == 'error') {
// log the detail error for the dev, and show the user a fail
console.log(resp);
$('#results').html('error occurred');
}
// you could handle other cases here
// or use a switch statement on the status value
},
error: function(request, status, error) {
// if json parse error and a 200 response, we expect this is our string
if(status == "parsererror" && request.statusText == "OK") {
$('#results').html(request.responseText);
} else {
// again an error, but now more detailed and not a parser error
// and we'll log for dev and show the user a fail
console.log(status + ": " + error.message);
$('#results').html('error occurred');
}
}
});