JSON error(s) with php backend - php

I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!

This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.

It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.

Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.

As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>

Related

AJAX call triggers success callback even if server script exists with error

Even though the below PHP code exits with an error, the success callback in the AJAX code is still being triggered. Why is that?
JavaScript code :
$.ajax({
type: "POST",
url: xxxx,
data: {info:data},
success: function(result){
//code here
},
error:function(msg)
{
alert('add data error,please add again');
}
});
php code:
if(is_wrong) //data is error
{
exit("the data is not right,please add again");
}
There are various ways to handle error or success, when communicating between the client and server.
1. with HTTP status code
One of the $.ajax() callbacks (success and error) will be called, depending on the HTTP status code returned by the server. The "normal" success code is 200 OK. When you send output with a PHP script, if everything goes well, your generated content will be sent with code 200.
This is the case when you call exit() here. From the point of view of your client-side JavaScript code, since it received status code 200 OK, it will call the success callback. If you want the error callback to execute, you have to send custom headers in your PHP code, before sending any other output.
You can achieve this with the header function. For example, the following code can be used to generate a "404 Not Found" status:
header("HTTP/1.0 404 Not Found");
Here you would need to find another HTTP code that corresponds to your code better. I don't think this approach is the best solution, because HTTP status codes are meant to be server status codes, i.e. not meant for reflecting application error codes.
2. with your own conventions
The other way would be to handle the application error codes would be to handle everything from the success() handler. You don't set error codes from your PHP, but establish a convention to tell when you have an application error or a normal case. You would still keep the error() callback, so that you can handle various HTTP errors (i.e. if your connection to the server is broken).
For example, if you send your data from the server to the client as JSON, you might send from your php:
if(is_right) //data is ok
{
$response = array(
'data' => $someData, // any data you might want to send back to the client
);
}
if(is_wrong) //data is error
{
$response = array(
'error' => "the data is not right,please add again"
);
}
// Called in both cases
exit(json_encode($response));
In your client-side code, you would have:
...,
success: function(result) {
if(data.error !== undefined) {
// do something if your server sent an error
console.log(data.error);
}
else {
var data = result.data;
// do something with the data
}
},
...

Wordpress plugin development - AJAX JSON data is sending correctly but PHP response is always 0, why?

I must be missing something simple here. Firebug shows data being sent exactly as it should in NET tab (NET tab-> Post -> Parameters). PHP function will not even echo simple text.
The PHP:
add_action('wp_ajax_nopriv_process_json', 'process_json_received');
add_action('wp_ajax_process_json', 'process_json_received');
function process_json_received(){
echo "ANYTHING...";
exit;
}
The JS/Jquery (sending correctly)
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
$.ajax({ url: 'http://localhost:12345/site_name/wp-admin/admin-ajax.php',
data: {data: data},
type: 'post',
dataType: 'json',
success: function (response) {
alert("Got this from the server: " + response);
console.log( response );
$('body').append(response); // <-- Append the ajax response to the page body
},
complete: function(XMLHttpRequest, text_status) {
},
error: function (response) {
alert("Error getting php file");
}
});
Again, it doesn't matter what is in the PHP function, the response is always 0. It could be an "enqueue_scripts" thing but ajax request is sending exactly as it should. NET tab in Firebug shows perfect json data so the problem has to be with the PHP function (or correct access to it). Maybe Wordpress is somehow blocking it??? Has to be something simple - I'm hoping a fresh set of eyes will help. Thanks in advance...
Because ANYTHING... isn't correct json format. Try echo json_encode(array('msg' => 'test')); This causes that JQuery have a parsing error (not error from receive)
Change the line in javascript from
var data = JSON.stringify({ action: 'process_json', value_name: 'value' });//generic sample
to
var data = { action: 'process_json', value_name: 'value' };
Wordpress expect POST Data so it can read $_POST['action], you should never Stringify it, but use core javascript object only.
Read more about it : http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
EDIT:
Also change data: {data: data}, to data: data,
:) I miss that last time.
OK, I got it using the following code:
In main PHP plugin file:
echo "<script src='URL PATH TO/ajax_file.js' type='text/javascript'></script>";
add_action( 'wp_ajax_foobar', 'foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'foobar_handler' );
function foobar_handler() {
// Handle request then generate response
echo "ANYTHING..."; // do stuff here
die(); // avoids extra 0 at the end of the response
}
In ajax_file.js: (referred to above in script tag)
jQuery(document).ready(function($) {
$('#id_to_submit_button').click( function() {
var data = {
action : 'foobar',
Whatever : '1234',
}
;
// ajaxurl only needed for front - facing public pages, comment out for back end pages
var ajaxurl = 'http://SITE_URL/wp-admin/admin-ajax.php';
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
}
);
}
);
}
);
As soon as I included the script in this way it worked, it would not when placed in a PHP function as many sources suggest. I tried soooo many other ways that should have worked. I went step by step on the Wordpress codex pages (many times) and several other tutorials. Enqueueing scripts, registering scripts, following all recommended practices. I still don't understand why this way works for me and all the other "correct" ways didn't. Could be something in my local server environment. Big thanks to those who answered and tried to help. God knows I have gotten the quick answer on StackOverflow enough times, I hope this saves someone the long hours I spent testing and troubleshooting...

Send back response string to use in jQuery's ajax function

I have a function for making a post request.
$('#save').click( function() {
...
$.ajax({
type: 'POST',
url: 'logic/save.php',
data: { 'json': JSON.stringify( post ) },
dataType: 'jsonp',
success: function( data ) {
console.log('success!')
}
});
}
The request handler is written in php, as you can see, and performs operations with mysql. Because of my poor knowledge of php and requests, I do not see any success! output in the console. Php code runs fine, and the mysql queries runs with no errors.
What I want is to be able to write something in php code at the end so that my code in js could receive it as a positive response (like 200, OK) and the success! line in the console will then (I believe) appears.
What code should I add to the php file?
UPDATE: since many of people requested the php code, here's the link to it. Thank you for fast replies, guys.
First, you should switch from jsonp to json, as you have no need for jsonp in this case. The following instructions assume you have made that change.
The bug is in your PHP code when you respond back to the client. You do so with this line:
print_r( "New item inserted.\n" );
However, jQuery is expecting you to be returning JSON back from your endpoint (and, truthfully, it should, because sending back plaintext to an ajax client is almost never the right way). We can make this work with jQuery by changing the line above to something like this:
print json_encode( array('success' => true, 'message' => "New item inserted." ) );
You should find yourself in the success callback in your client. This code would work for your success handler:
{ // ...,
success: function(response) {
if (response.success) {
alert(response.message);
}
}
}
You'll probably want to use something other than an alert, though. But that's up to you.

Php script returns json, but I am getting parseerror

i know that there was similar questions, but i would like to get some clarification here.
With following Ajax setup:
$.ajaxSetup({
cache: true,
dataType: 'json',
error: function(xhr, status, error){
console.log(status);
},
timeout: 60000, //Timeout of 60s
type: 'POST',
url: 'test.php'
}); //Close $.ajaxSetup()
$('#openTest').bind('click', function(){
$.ajax({
data: {val: "Hello", val2: "Hello2"},
success: function(response){
console.log('complete');
console.log(response);
}
});
When 'test.php' is:
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
return json_encode($return);
?>
I am getting parseerror. But when I replace 'return' with an 'echo', it works fine.
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
echo json_encode($return);
?>
I will be retrieving much more complex data via this $.ajax calls, and I was expecting 'return' to works, 'echo' doesn't seems to me like good solution.
So, what are you suggesting? Is there something wrong with the Ajax setup, or call, so 'return' doesn't work, and is 'echo' a good solution?
Thanks.
return returns data to the caller of the function and since you are not in a function you cannot use return.
echo prints the data. So echo is the way to go.
when you do a return in php, it is not printed. When you do an echo, it gets printed.
Nothing is wrong with php or Ajax, it is just the context which is wrong.
Sinply put, use return when u need to catch the returned data and maybe process it. Best case for using return is in functions.
Use echo when you need to print something directly.
Here in this case using an echo and exit is what i recommend.
Return is used in functions to get the data back and use it in some fashion in your PHP. Echo is used for ajax calls because your PHP code will output the data to whatever is calling it (the browser, your ajax call, etc).
You also probably want to have header('Content-Type: application/json'); in your PHP file to make things all right and proper.
No, there is no problem with your ajax setup, it's because the return is used with PHP objects or variables and it can't return a value to other language like javascript. when you are using echo it sends the values to HTTP response so your ajax response can handle it.
The best way to do complex data is to send them in arrays like:
$arr = array();
$arr['res'] = 'something';
$arr['res2'] = 'somethingelse';
echo json_encode($arr);
and then you can handle it as object.parameter in your jquery code as I have specified it before in this example.
Always make echo or print or parsing php as html file in ajax call and then get the data, this will save you a lot of efforts.
the ajax is just reading the file, there is no way to make calls in two different languages PHP and JS.
The JS just returned the filed from the server, if it was php then it will interpreted and go to the Ajax call as html or else possible.

JQuery ajax error

Ok, so my Ajax call looks like this:
var poststring = "id_Client=" + id_client + "&id_File=" + id_file;
alert(poststring);
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Everything works fine until the $.ajax(). If I use alert(poststring) the output looks like this:
id_Client=7&id_File=32
Using firebug, I found out that the url "addclpermission.php" is actually requested, but then 'aborted'. The path is correct though, if I copy the url out of firebug and call it directly, no error is displayed.
The alert in the 'error' option returns "Error: error"
The file addclpermission.php:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = $_POST['id_File'];
$id_Client = $_POST['id_Client'];
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
I'm pretty sure this code once worked and that I haven't changed that much.
Any ideas?
Thanks!
Edit: I don't think that the error is in the php script, I have multiple ajax calls to several php scripts, but all of them fail the same way.
Edit 2: Now it works! Well, at least half of it. The request is still aborted, but the data gets inserted in the database. But as I said, this isn't the only ajax call and the others still aren't working, and this one is aborted. So I'd really like to know what caused this error and how I can fix it for good. Thanks!
Does the data get inserted to mysql despite the error? If so, can you put echo on your addclpermission.php file to return 'success' and/or 'fail' for mysql_query()? How about stripping this php file to just echo "hello"???
First, I would try just requesting addclpermission.php in the browser and see what happens.
Then, if that works, what if you just make addclpermission.php contain some text, no PHP content at all. Then for each stage that works, gradually add content (so first the include, for example).
I think the error could be in dbonnect.php or addclpermission.php. Save this in addclpermission.php (make a backup of your current file) and browse to it directly:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = 1;
$id_Client = 1;
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
Please let us know if it works or if you get an error.
When I do jQuery Ajax, I set the data as a Javascript object that jQuery then serializes. Do you have better luck if you provide data: property as an object like this:
data: {
id_Client: id_client,
id_File: id_file
}
I am pretty sure your problem is that you are not returning an expected dataType to the .ajax call, if you explicity set the datatype (json or text for example):
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
dataType: "json",
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Then just echo out the expected datatype, just so the server responds, then ajax will know the request was successful.
<?php
// if your dataType is json
echo json_encode(true);
// if your dataType is text
echo ' ';
// exit so the server can return the request
exit;
problem is a --> require_once
require_once("../allgemein/includes/dbconnect.php");
remove this line in a php and write all code here
but I don't know why ?

Categories