json call allways returns an error - php

I want to perform a simple json call to a php file, but somehow it allways returns an error.
This is my html (the dataString is filled with form values):
$.ajax({
type: "POST",
url: "reghandle.php",
data: dataString,
dataType: "json",
success: function(result){
$("#modaltitle").html("Welcome");
$("#errorDetails").html(result.responseText);
$('#myModal').modal('show');
},
error: function(result){
$("#modaltitle").html("Error:");
$("#errorDetails").html(result.responseText);
$('#myModal').modal('show');
}
});
And my php file (I use $num_rows to produce an error or an succes):
if ($num_rows>0){
echo "error and blablabla";
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
return json_encode(array("error" => "bad table name"));
}else{
echo "ok";
header('Content-Type: application/json; charset=UTF-8');
return json_encode(array("success" => "blablabla"));
}
If I let my php file produce an error, the modal screen popsup with:
Title: Error
Errordetails: error and blablabla
(this is all correct)
And if I let my php file produce a success, the modal screen popsup with:
Title: Error (this should be a Welcome message)
Errordetails: ok
So obiously something goes wrong when returning a success from within my php file, I haven't got a clue what it is though.

because echo "error and blablabla"; and echo "ok"; is not json!
remove these .

echo "ok"; breaks it on two counts:
You have to output your HTTP headers before you output any content.
Outputting some free text before the JSON in a JSON document invalidates the JSON
You are returning the JSON (it isn't clear if you are returning it anywhere useful) instead of echoing it.

You are telling Jquery that only JSON responses from the server should be treated as successful, but your not sending a JSON response.
So, a few things to note here:
You shouldn't output (echo) anything before you set any headers, because the headers have already been sent and so cant be modified.
If you do set your headers to say the doc is json, then you should output some json on the page somewhere! (although it still has to be after the headers).
Your json_encode statement won't do anything as it only returns. It doesnt output the encoded json data onto the page anywhere.
In short, if you remove the current echo lines, then replace your returns with echos, then it should work.

Related

SyntaxError: JSON.parse?

So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results).
The application lets me pick a client and it pulls out that client's orders
JS file :
function getOrders(clientId) {
$.ajax(
{
type: 'POST',
url: "AjaxRequests.php",
data : {
action: 'showOrders',
clientId: clientId
},
dataType : 'json',
success: function(results){
alert(results);
},
error: function(request, status, error){
console.log(clientId);
console.log(request.responseText);
console.log('error : ' + error);
console.log('status' + status);
},
}
)
};
AjaxRequests.php file
<?php
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';
if (isset($_POST['action'])) {
if ($_POST['action'] == 'showOrders') {
$clientId = $_POST['clientId'];
$gc = new GestionClients();
$results = $gc->getCmdsByClient($clientId);
echo json_encode($results);
}
}
?>
and this is the results i get in the console after i pick a client (first client in this example with an ID = 1 in the DB) from the selection list:
1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror
I tried putting that JSON result on an online JSON parser and it looks just fine.
Thank you for your time.
As I so often advise, this problem could have been avoided, or at least quickly identified, by breaking the problem down: you were trying to debug the JS, but that wasn't the part that was broken.
In this case, you have two key pieces:
A PHP script that, when requested with the right parameters, outputs something. You can open this in your browser, and see it for yourself.
Some JS code which requests that PHP script, and parses its content as JSON. You can test this with a PHP script that just echoes {"hello": "world"}, or even a text file uploaded to your server.
Once you know that the JS code works if the JSON is valid, you can basically ignore #2, and look for problems in #1.
If you open the PHP script you wrote in a browser, it will show:
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now, we know that the JS is going to try to parse this as JSON, so we can do a quick test in our browser's console:
JSON.parse('Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
We get a syntax error! Well, of course we do: that "Connection successfull!" wasn't supposed to be part of the JSON.
So we dig into the PHP code, work out where that's coming from, and stop it happening. Now we run the PHP again, and it looks like this:
[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now we can do our JS test again:
JSON.parse('[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
Now the error's gone away, and it gives us an array. While we're here, we can look at the structure of the array in the console and make sure it looks right.
Only now do we go back and run the original AJAX call, and see if it's all working. If it's not, we look for other steps we can break out, and repeat the process.

Sending html to Javascript from PHP via JSON obejct

I'm sending some data from php through ajax to jquery.
If $content="ABC"; everything is OK. I get alert with ABC.
If $content="<div>ABC</div>"; then Houston has a problem. Nothing happens at all.
Here is PHP code
$json = json_encode(array("content" => $content));
echo $json;
And this is Jquery
$('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
success: function(responseimage){
result = jQuery.parseJSON(responseimage);
alert(result.content);
Any ideas ?
UPDATE!
I've removed jQuery.parseJSON
so that line has only this code
result = responseimage;
And now I get the result in alert.
The result is the following
{"content":".<div>ABC<\/div>."}</div>
So we can see that JSON is not created well. I;ve tried utf8_encode and trim , but they do nothing to the result. result is strange.
PHP (and JSON) code seems fine, provided that the variable $content actually has any content. Else the PHP script will fail and there's your problem.
Did you define the dataType as "json" in the AJAX request?
$.ajax({
url: 'json.php',
dataType: 'json',
success:function(data){
console.log(data);
}
});
I think you just need to utf8_encode your response before doing json_encode.
Just change this :
$content = utf8_encode("<div>ABC</div>");
You are delivering invalid json somehow - please put your raw response in JSONLint, it will tell you what is wrong.

JSON error(s) with php backend

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);
?>

Why is this ajax post giving me an error? Does an ajax post require "true" or "false" to be returned?

$.ajax({
url:"http://www.xxxxxxxxxxxxxx.com/cc/validate",
type:"POST",
dataType:"json",
data: JSON.encode($parts),
complete: function(){
},
success: function(n)
{
console.log(n);
console.log(n.object);
console.log("ajax complete");
},
error: function(){
console.log("error");
}
});
This gets an array defined above the ajax post call and posts an encoded json array to a php file. The problem is determining why the post will only let me return "true" or "false". If i try to return any string, i get the error in the ajax. I want to be able to return a string created in the php and not only "true" or "false".
are you on a local host? well if so you might have to change your mime headers (application/json) ... your javascript is expecting json but your php is echoing html.
header('Content-type: application/json');
if you want to be able to return something else then json you have to delete or change the content type in your ajax call. the content type is for giving jquery a hint of what to expect from the server. if you tell it will receive json data you need to give it json or you'll have a parse error.
your code is alright
just make sure your php file return an echo json_encode($arrayOFdata)
dataType:"json",
means the data recived from php will be parsed as a json object
it doesn't mean you will send a json object

Jquery AJAX PHP data return

I'm using the ajax function in Jquery to return some values from a PHP script with the json_encode function. The returned data seems to be full of slashes, quotes and \r\n. I understand that there must be something going wrong with stripslashes or magic_quotes (which is turned on) but can't seem to manage to get a clean output
Make sure on your ajax call from jQuery, you tell it to expect a json response. It sounds like you're returning plaintext and trying to parse it manually.
$.ajax({
url: "myscript.php",
dataType: "json",
success: function(data){
console.log( data ); //this line only works with chrome (stock) or FireFox (with FireBug plugin)
}
});
That code will echo in your console (if you don't have chrome or FF with FireBug, go get one of them :P) the json encoded output. Remember when you output from PHP, all you should be doing is this:
header('Content-type: application/json');
echo json_encode( $myAssociativeArrayOfData );
exit; //make sure nothing else happens to output something
You don't need to use any special formatting or slashes. Just make sure the json code gets output as json code with the proper headers and jQuery's ajax function should convert it for you. The result will be the data variable in the success function being your json object (php array). So if you pass in an array like this: array('foo'=>'bar') in PHP, then in your success function in jquery, you could type: alert( data.foo ); and get a dialog box that says "bar".

Categories