Error - Passing an array from PhP to jQuery using JSON - php

I apologise, since I know this has been asked before, more than once.
I've been struggling with this little bugger for quite a few hours now, and I cannot seem to find my mistake.
The problem is simple - I have a PhP array which I want to pass over, from the server side to the client side, using jQuery AJAX with the data in JSON format.
The code for my Client-side Ajax call is
$.ajax({
url: 'php/test/pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
And the code for my server-side pass_array.php script is
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name"=>"Johnny")); //Build JSON object from the array
As you can see, this is pretty basic, but it's not working. On the client side, the AJAX response is never received.
When I check the browser console log, I get
Error: SyntaxError: Unexpected token parsererror [object Object]
What the devil am I doing wrong?
All my files are in UTF-8 encoding. This also works if I remove the dataType: 'json' and the heading() on the PhP side. In that case, I get the following string:
{"Name":"Johnny"}
UPDATE
Commenting out the header() code in the PhP side makes the console show the following error:
Uncaught SyntaxError: Unexpected token o
How can there by syntax errors? I create a PhP array and encode it using json_encode.
UPDATE #2
Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
It looks like including that db_io.php file added a Byte Order Mark character (\ufeff) to the JSON string.
The complete string being sent to the Client side was
\ufeff{"Name":"Johnny"}
It seems this db_io.php file was encoded with BOM. Changing its encoding (using notepad++) fixed that.
Amazing how a simple include instruction can mess up an AJAX call.

Try checking out if your ajax function is being triggered and if any request is even being sent to your php code. For example maybe there is some syntax in your ajax script or you have not provided the url of your php file.

Make sure your PHP script starts with <?php
Update 1:
I made two files on my localhost - index.html
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: 'pass_array.php',
method: 'POST',
data: {test1: 'abc', test2: 'cde'}, //Random input data
dataType: 'json',
success: function(response_data)
{
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
</script>
</body>
</html>
pass_array.php
<?php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array("Name" => "Johnny"));
The result of the AJAX call in the console is:
Object {Name: "Johnny"}
Make sure the url is correctly accessing the right php file.
You can check any "XHR" requests (AJAX) in Chrome's inspector under the "Network" tab.

Fixed it.
On my PhP file I had (only one more!) line
include '../core/db_io.php';
I commented that line out and it worked fine.
This file contains methods to query my databases. Since I did not call any methods or objects from this file, I left it uncommented - thinking it made no difference.
I still don't understand tho - I'm not using that file in any way - other than include it. Why should it interfere?
Thanks for the ideas. Peace!

Error: SyntaxError: Unexpected token
U have problems with 'token' variable. Mb u use CMS or Framework?
Try
console.log(arguments);
And also, u can try send
header('Content-type: application/json');

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.

Remote serve not sending response to ajax post

I am using WAMP 3.0.8 PHP 7.0.10 Apache 2.4.23 and trying to build my first JSON API.
The ajax call does send the data to the server. I can see it stored in the text file.
My AJAX looks like this.
$(document).ready(function(){
$('#order').click(function(){
var send = {"name":"Jo Moe", "age":39, "city":"Meridian"};
var prescription = JSON.stringify(send);
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'https://apa.superserver.com/receive.php',
data: {"scripts": prescription},
success: function(data){
console.log(data);
alert(data);
$('#success').html('<p>Finished</p>');
}
});
});
});
Server side looks like this:
if(isset($_POST["scripts"]) && !empty($_POST["scripts"])){
$sent = filter_input(INPUT_POST, "scripts", FILTER_SANITIZE_SPECIAL_CHARS);
$scripts = html_entity_decode($sent);
file_put_contents("jsonScript.txt", $scripts);
$finish = "Message Received!";
echo json_encode($finish);
}
Now this all worked when it was on the same server. When I separated the receive.php and put it on the remote server. It no longer shows the response.
Thanks!
UPDATE:
Get json ajax php form to work remotely
The link above fixed my issue and gave me more information in the console to figure out what was happening. (I should not have been given a -1) The problem with searching the index here that if you don't use the exact terms in the post it is nearly impossible to find. (my two cents)
Adding the error function and changing from "data" to "response" made the difference along with the xhr. I can see everything.
This my return to the console:
Object {readyState: 4, responseText: "↵↵hello!"Message Received!"", status: 200, statusText: "OK"}
ajax.php:56 parsererror
ajax.php:57 SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at parseJSON (jquery-1.6.4.min.js:2)
at b$ (jquery-1.6.4.min.js:2)
at w (jquery-1.6.4.min.js:4)
at XMLHttpRequest.d (jquery-1.6.4.min.js:4)
As you can see the response text is what the server is sending back.
I did have to modify my httpd.conf to turn on the mod_headers.c and added an .htaccess .
UPDATE 2:
Figured out what was causing the parse error. I had a print "hello!" line in my server side file that I had there for other troubleshooting. Once I removed it and had only the posted server side code. Everything is peachy now. Onward!!
If I understand correctly You want to make ajax request to another domain. It's blocked because of Same origin policy. To achieve your goal You can implement JSONP

JQuery can't parse properly formed JSON data sent from PHP

I'm trying to use JQuery to send AJAX data from a web browser to a PHP script in a web server and then getting a response back from the server. The request is received and processed correctly by the PHP script, but there seems to be something in the server's response that JQuery can't parse. Using Firefox, I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
And using Chromium I get something like this:
SyntaxError: Unexpected token in JSON at position 0
I'm not sure if that's a blank space or some other character, as Chromium won't let me copy the alert text.
Anyway, here's the PHP script that resides in the server, processes the AJAX request and generates the response. I previously used json_encode() to return dynamically generated data, but right now I'm using a static string just to try to make it work:
<?php
echo '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
?>
And here's my JQuery AJAX code:
$.ajax({
url: 'www.siteurl.com/server_script.php',
method: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
dataFilter: function ( recieved_data, data_type ) {
//I added this function just to check the JSON data before it gets parsed by JQuery
alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
var filtered_data = recieved_data;
return (filtered_data);
},
success: function (json) {
alert('SUCCESS --- json: ' + json);
response($.map(json, function () {
return json;
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error - ' + textStatus + ': ' + errorThrown + ' * Server Response:_' + XMLHttpRequest.responseText + '_')
}
});
So the PHP script gets JQuery's message without a problem, returns a static string of (as far as I can tell) properly formed JSON that gets back to the browser without a problem (that alert command in the dataFilter function shows the same string that PHP sends back) but JQuery can't parse it.
The funny thing is: If I insert that very same static string directly in the dataFilter function instead of passing it from the PHP script, JQuery parses it properly and everything else works without a hitch!
dataFilter: function ( recieved_data, data_type ) {
alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
/*var filtered_data = recieved_data;*/
//instead of using the data I got from PHP, I use a string literal value
var filtered_data = '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
return (filtered_data);
},
This works, but it obviously doesn't suit my needs, as I need to use the JSON data that gets sent back from the server. Right now, I'm using the very same JSON string, only JQuery can't parse when it gets it from PHP, even when it seems to be receive it complete and properly encoded, as far as I can tell.
I'm at a loss to figure out what may be happening with the data that I get from PHP. When displayed with the alert command in the dataFilter() function, it looks perfectly ok! What am I missing here? Any help will be greatly appreciated. Thanks in advance!
Thanks to user JAAulde, I found the cause of my problems. The server side PHP script returned properly formatted JSON data, and checking it with the browser's network inspector and in the JQuery script after reception, I couldn't see any extraneous characters that could stop the parser from processing it.
The cause of my problems was a little configuration file I included in the PHP script, that some text editor had codified as UTF8 with BOM (byte order mark), the mere inclusion of which, apparently produces some kind of undisplayable output that gets added to the beginning of the data and messes JSON parsing in the client script. Be careful with the BOM in your UTF-8 encoded files when you need to send data for another script to process, kids!
Many thanks to users Nitin and charlietfl for their helpful and reasonable answers, too!

jQuery Mobile -> Load content from external server

I am working on a seemingly basic mobile app (first). But I want to enable the application to request information from our 'head' server. To make sure it has the latest information.
I'm currently running a jQuery script like this.
$.ajax({
url: 'http://www.domain.com/list.php',
dataType: 'json',
crossDomain: true,
success: function(data) {
// Remove all content first
$(contentId +' li').remove();
// Load Data
$.each(data.items, function(index, list){
$(contentId).append('<li><a href="details.html?id=' + list.homeId + '" >' + list.name + '</a></li>\n');
});
// Reload View
$(contentId).listview('refresh');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: '+ jqXHR + textStatus + errorThrown);
}
});
And actually on that LIST.PHP file, it does return a JSON string. But what I did for security was by adding this as a header
header("Access-Control-Allow-Origin: *");
Or I could change * to a domain/url to add better security. But if I don't add that header() code in their, my javascript breaks and won't run properly.
I guess what i'm truly wondering is, am I doing this properly? or is there a better way to do this? I have tried JSONP, but I can't seem to get that to work for cross domain.
Is my solution sound? or total crap? Any thoughts or direction would be greatly appreciated!
I think you should look into JSONP. It's not that hard. On the client side, jQuery already handles it out of the box, just append a ?callback=? to the URL. On the server, instead of just responding with JSON, e.g.:
{
"foo": "bar"
}
Look for the query parameter callback, and if it exists, wrap your JSON output in a function call with the name being the value of the callback parameter, so, for callback=foo:
foo({
"foo": "bar"
})
When responding with JSONP, send Content-Type: text/javascript. This should work without setting Access-Control-Allow-Origin or anything like that.

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