Im using MVC on server side and calling a function via jQuery.Ajax sending json type.
the function results with exception.
i want to invoke/trigger the error result function of the Ajax, what should i send back with the return JSON function?
for the example, let's say the return JSON is triggered from the catch section.
MVC Function
public JsonResult Func()
{
try
{
var a = 0;
return Json(a, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
FxException.CatchAndDump(ex);
return Json(" ", JsonRequestBehavior.AllowGet);
}
}
JavasScript call
$.ajax({
url: '../Func',
type: 'GET',
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
alert('s');
},
error: function (data) {
alert('e');
}
});
Quoting from this answer:
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:
HTTP 404/500 or any other HTTP error message has been received
data of incorrect type was received (i.e. you have expected JSON, you have received something else).
In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.
function handleError(xhr, status, error){
//Handle failure here
}
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success: function(data) {
if (whatever) {
handleError(xhr, status, ''); // manually trigger callback
}
//Handle server response here
},
error: handleError
});
error callback is invoked when HTTP response code is not 200 (success) as well as when response content is not comply to expected contentType which is json in your case.
So you have to either send HTTP header with some failure response code (e.g. 404) or output non-json response content. In the latter case you can simply output empty string:
return "";
If you want to trigger an error in AJAX, but still know "why" it was triggered so you can customize the error message, see this post:
https://stackoverflow.com/a/55201895/3622569
Related
I code this ajax request but I don't know why the code in the success method doesn't work
Even though in the networks in chrome browser appear state: 200ok
this is ajax code:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success:function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
}
});
});
the problem is that alert or console Not to mention the others code
success:function(data,state)
{
console.log(data);
console.log(state);
alert('ajax success');
}
From the ajax events docs:
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
Since your server responded with 200 OK that means we can route out problems with the server and are left with errors with the data.
From the ajax docs (only the relevant parts):
dataType
The type of data that you're expecting back from the server.
The available types (and the result passed as the first argument to your success callback) are:
"json": Evaluates the response as JSON and returns a JavaScript object.
...
The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
So most likely the data returned by the server is being rejected by ajax in which case a parse error should be thrown.
This would be an example of how to implement an error handler:
$("#noti_filter").click(function(){
//first add item into cart
var item_id = 'test';
$.ajax({
method:"POST",
//contentType:"application/json",
url:"../html/notifies.php",
data:{product_id:item_id},
dataType: "json",
success: function(data,state) {
console.log(data);
console.log(state);
alert('ajax success');
},
error: function(err) {
console.log(err.responseText); // <-- printing error message to console
}
});
});
You defined the dataType as json. The dataType is the type of data that you're expecting back from the server. Does your server responds json?
I assume the result of your 200-ok-server-request is probably not in json format, so the parsing fails and your success-callback is not called. You can catch the error with error callback function.
After that you know the exact reason.
I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.
I am making a cross-domain AJAX call, and I am not sure if I am doing something wrong or the providers of the API call is incorrectly returning the JSON. Whenever I get the response from the API call, it is a string instead of a JSON object. Here is my AJAX call.
$.ajax({
async: false,
dataType: 'jsonp',
url: 'http://cross-domain/getSummaryStat.action',
data: { minDailyDate: start_param, maxDailyDate: end_param },
success: function(response) {
map = {
gamefuse: response["ROM-GF-Live"],
facebook: response["ROM-FB-Live"],
kongregate: response["ROM-Kongregate-Live"],
yahoo: response["ROM-Yahoo-Live"]
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
When the response comes back, here is response.result
"[{"dayRetention1":"0.01453800063053","visit":"601","installs":"203"},{"dayRetention1":"0.122484891199019","visit":"33863","installs":"10949"]"
NOTE: I set dataType to jsonp because it is a cross-domain AJAX call, and I was getting an error without it.
First, It looks like the returned string isn't even in correct JSON form. It's missing a close bracket at the end.
If this doesn't fix it then the issue here is probably on the server side. Since JSONP is JSON with padding, your return function shouldn't be:
function_name("the string that I return");
Instead you should have:
function_name({
"name":"Bob Loblaw",
"age":40
});
I have a simple web application.
I've created the server REST API so it will return a response with HTTP code and a JSON (or XML) object with more details: application code (specific to scenario, message that describe what happened etc.).
So, for example if a client send a Register request and the password is too short, the response HTTP code will be 400 (Bad Request), and the response data will be: {appCode : 1020 , message : "Password is too short"}.
In jQuery I'm using the "ajax" function to create a POST request. When the server returns something different from HTTP code 200 (OK), jQuery defines it as "error".
The error handler can get 3 parameters: jqXHR, textStatus, errorThrown.
Ho can I get the JSON object that sent by the server in error case?
Edit:
1) Here is my JS code:
function register (userName, password) {
var postData = {};
postData["userName"] = userName;
postData["password"] = password;
$.ajax ({
dataType: "json",
type: "POST",
url: "<server>/rest/register",
data: postData,
success: function(data) {
showResultSucceed(data);
hideWaitingDone();
},
error: function (jqXHR, textStatus, errorThrown) {
showResultFailed(jqXHR.responseText);
hideWaitingFail();
}
})
}
2) When looking at Firebug console, it seems like the response is empty.
When invoking the same request by using REST testing tool, I get a response with JSON object it it.
What am I doing wrong?
Here's an example of how you get JSON data on error:
$.ajax({
url: '/path/to/script.php',
data: {'my':'data'},
type: 'POST'
}).fail(function($xhr) {
var data = $xhr.responseJSON;
console.log(data);
});
From the docs:
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
Otherwise, if responseJSON is not available, you can try $.parseJSON($xhr.responseText).
directly from the docs
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader()
so use the jqXRH argument and get the responseText property off it.
In the link above, look for the section entitled
The jqXHR Object
I also faced same problem when i was using multipart/form-data. At first I thought multipart/form-data created this mess, but later i found the proper solution.
1) JS code before:
var jersey_url = "http://localhost:8098/final/rest/addItem/upload";
var ans = $.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jersey_url,
data: formData,
dataType: "json",
processData: false,
contentType: false
success : funtion(data){
var temp = JSON.parse(data);
console.log("SUCCESS : ", temp.message);
}
error : funtion($xhr,textStatus,errorThrown){
console.log("ERROR : ", errorThrown);
console.log("ERROR : ", $xhr);
console.log("ERROR : ", textStatus);
}
});
Here when error occurred, it showed me this in console :-
Error :
Error : { abort : f(e), always : f(), .... , responseJSON :"{"message":"failed"}" }
Error : error
Thus i came to know that we have to use $xhr.responseJSON to get the string message which we sent from rest api.
2) modified/working error funtion:
error : funtion($xhr,textStatus,errorThrown){
var string= $xhr.responseJSON;
var json_object= JSON.parse(string);
console.log("ERROR : ", json_object.message);
}
Thus will output "Error : failed" on console.
After spending so much time on this problem, I found the problem.
The page is under the URL: www.mydomain.com/register
The REST api is under the URL: server.mydomain.com/rest
Seems like this kind of POST is not so simple.
I'm going to search more information to understand this issue better (if you have more information please share it with me).
When putting the REST API under www.mydomain.com/rest - everything is working fine.
I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.
You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem
I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.
The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json