Using the following code i am trying to send JSON data via javascript to a PHP script
Watching "isRunning" while stepping through the code returns true, ie suggests AJAX isn't running, however once the code progresses to the next portion of AJAX code "isRunning" changes to false;
I have tried to trap the error on the second portion - which returns "Unexpected error"
Does anyone have an suggestions as to what i am doing wrong, or how I can trap a more informative error response ?
var isRunning = true;
$.ajax({
url: url,
success: function(resp) {
isRunning = false;
}
});
jsonString = JSON.stringify(row);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
console.log('The answer from the PHP file: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
Thank you
Thanks to everyone or their suggestions, I think the issue lies with the JSON.stringify conversion, also i noticed i didn't include the PHP side, which i have kept to a minimum basically
$data = json_decode($_POST['json']);
echo "Data:-".$data."<BR>";
Is it possible that the problem lies on the PHP side ?
As discussed many times before ajax is asynchronous which means it runs while you are requesting the isRunning variable. If you want to know if this call succeed use a network console like most modern browsers have. This will show you if the call will be made and the server response.
For the second part, the code looks to be correct. However if you run the code from your browser you only see the client side. I suggest you use the network console here as well. A small error in the url may already get your code to output Unexpected error. Either way, you need more information like server response, error codes etc..
Have you tried logging jqXHR.responseText with the unexpected error too? Or put a breakpoint on that line and examine the variables in the debugger.
If that doesn't help you could try debugging the php side and seeing how the code executes there and what goes wrong.
Also remember that ajax is asyncronous, so your isRunning could change halfway down the page, or when it's all done.
edit:
If you don't have a debugger for php it would definitely save you a ton of headaches in the long run to get one setup.
I'd recommend netbeans, since it has a robust toolset for many languages (including both javascript and php). You'd also need to configure xdebug on your server to allow remote debugging.
To handle the errors, use the error setting as you're doing, but PHP can return the JSON data too, so you can handle more errors from PHP.
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
if(data.errorCode) {
console.log('The answer from the PHP file: Error #' + data.errorCode + ' - ' + data.errorException);
} else {
console.log('The answer from the PHP file: ' + data.responseText);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
And in your PHP file, you can handle the errors, returning this if the things worked fine:
$response = array(
"responseText" => "AJAX is working OK.",
"errorCode" => 0,
"errorException" => ""
);
This if you have to return an error, like MySQL error or something like that:
$response = array(
"responseText" => "",
"errorCode" => 1,
"errorException" => "Your error message here."
);
And finally sends the JSON data back to the AJAX:
echo json_encode($response);
Related
I am sending the ajax request to the tomcat server and getting response as ,
function getAgentName(){
$.ajax({
type: "POST",
url: "agentName.html",
success: function(response){
// we have the response
if(response != null && response !="" && response !="null"){
alert( "response :"+$.trim(response)); // line 10
}
},
error: function(e){
alert('Error: ' + e);
},
complete:function(){
getAgentName();
}
});
}
I got the error in response success alert in the line 10 as '$' is null or not an object .
Edit : I have already added the Jquery 1.9.1.js.
Don't know how to solve this. Hope our stack users will help me .
I guess the link to your JQuery library might be wrong. Check if you included the right one.
Here is the latest hosted by jQuery: http://code.jquery.com/jquery-latest.min.js
There's a quite a chance that there's error in response. But just to give it a proper shot, instead of using
$.trim(response)
use
response.trim()
If you're still getting issue, then it's a response related issue, else you've already solved your problem.
I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.
I dont get why i get so many different errors.
I'm using Google Places API for a test, and using simply an ajax query call with callback, i receive back the json but in CHrome browser i get
"Uncaught SyntaxError: Unexpected token :"
why the hell is that?
I supposed Google does it right, and their json must be correct...so where could be the problem?
this is my code
$.ajax({
dataType: "json",
url: "https://maps.googleapis.com/maps/api/place/search/json?location=40.47,-73.58&radius=5000&sensor=false&key=MYOWN&name&callback=?",
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
}
});
You get this error, if a server returns plain JSON. As this is a cross-site request, jQuery has to use the JSONP-technique where the server-response is interpreted as script. This is the only way to do cross-site-requests in the browser.
The problem is that the server has to support JSONP and surround the JSON answer with a callback generated by jQuery. The response must look like that:
jQuery17101705844928510487_1324249734338({"data":"whatever"});
Server-Example with PHP:
<?php
header("Content-Type:text/javascript"); // avoid browser warnings
$request = new HttpRequest("http://programmingisart.com/json-data-source.php", HttpRequest::METH_GET);
$request->send();
$json_data = $request->getResponseBody();
// wrap the data as with the callback
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "alert";
echo $callback."(".$json_data.");";
Client-Example with jQuery:
<div id="json-result"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "jsonp-wrapper.php",
success: function(data) {
$("#json-result").html(JSON.stringify(data));
},
error: function() {
alert("error");
}
});
});
</script>
You can replace the PHP-code with any other server-platform and do the required steps.
HTTP-Request to a JSON source
Wrap the JSON as with a callback-function
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
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
And also:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
I've also tried adding the $.ajaxError but that didn't work either:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
Here's my extensive answer to a similar question.
Here's the code:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
Detecting JSONP problems
If you don't want to download a dependency, you can detect the error state yourself. It's easy.
You will only be able to detect JSONP errors by using some sort of timeout. If there's no valid response in a certain time, then assume an error. The error could be basically anything, though.
Here's a simple way to go about checking for errors. Just use a success flag:
var success = false;
$.getJSON(url, function(json) {
success = true;
// ... whatever else your callback needs to do ...
});
// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
As thedawnrider mentioned in comments, you could also use clearTimeout instead:
var errorTimeout = setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
$.getJSON(url, function(json) {
clearTimeout(errorTimeout);
// ... whatever else your callback needs to do ...
});
Why? Read on...
Here's how JSONP works in a nutshell:
JSONP doesn't use XMLHttpRequest like regular AJAX requests. Instead, it injects a <script> tag into the page, where the "src" attribute is the URL of the request. The content of the response is wrapped in a Javascript function which is then executed when downloaded.
For example.
JSONP request: https://api.site.com/endpoint?this=that&callback=myFunc
Javascript will inject this script tag into the DOM:
<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>
What happens when a <script> tag is added to the DOM? Obviously, it gets executed.
So suppose the response to this query yielded a JSON result like:
{"answer":42}
To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:
<script>{"answer":42}</script>
Well, nothing. It's just an object. It doesn't get stored, saved, and nothing happens.
This is why JSONP requests wrap their results in a function. The server, which must support JSONP serialization, sees the callback parameter you specified, and returns this instead:
myFunc({"answer":42})
Then this gets executed instead:
<script>myFunc({"answer":42})</script>
... which is much more useful. Somewhere in your code is, in this case, a global function called myFunc:
myFunc(data)
{
alert("The answer to life, the universe, and everything is: " + data.answer);
}
That's it. That's the "magic" of JSONP. Then to build in a timeout check is very simple, like shown above. Make the request and immediately after, start a timeout. After X seconds, if your flag still hasn't been set, then the request timed out.
I know this question is a little old but I didn't see an answer that gives a simple solution to the problem so I figured I would share my 'simple' solution.
$.getJSON("example.json", function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
We can simply use the .fail() callback to check to see if an error occurred.
Hope this helps :)
If you collaborate with the provider, you could send another query string parameter being the function to callback when there's an error.
?callback=?&error=?
This is called JSONPE but it's not at all a defacto standard.
The provider then passes information to the error function to help you diagnose.
Doesn't help with comm errors though - jQuery would have to be updated to also callback the error function on timeout, as in Adam Bellaire's answer.
Seems like this is working now:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
I use this to catch an JSON error
try {
$.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
alert("wow");
alert("Error : "+ err);
}
Edit: Alternatively you can get the error message also. This will let you know what the error is exactly. Try following syntax in catch block
alert("Error : " + err);
Mayby this works?
.complete(function(response, status) {
if (response.status == "404")
alert("404 Error");
else{
//Do something
}
if(status == "error")
alert("Error");
else{
//Do something
}
});
I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded
you ca explicitly handle any error number by adding this attribute in the ajax request:
statusCode: {
404: function() {
alert("page not found");
}
}
so, your code should be like this:
jQuery.ajax({
type: "GET",
statusCode: {
404: function() {
alert("page not found");
}
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
hope this helps you :)
I also posted this answer in stackoverflow - Error handling in getJSON calls
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.