Errors while parsing invalid JSON passed from PHP to AJAX - javascript

I'm trying to parse JSON sent by PHP.
JSON:
[{"id":"1","value":"1"},{"id":"4","value":"1"},{"id":"2","value":"1"},{"id":"3","value":"1"},{"id":"4","value":"1"}]
I'm trying to parse it to get the id and pass it to another JavaScript function and I'm continuously calling the PHP. When I tried $.ajax, $.get, $.getJSON and used JSON.parse and parseJSON, I get this error:
Uncaught SyntaxError: Unexpected token <
because the JSON looks like this:
id: id: id: html> 1id: 4id: 1id: 2id: 3id: 4id: id: id: >
I tried to fix it using JSON.stringify, which caused this error:
Cannot use 'in' operator to search for 'length' in
and now I'm stuck and have no idea how to fix this.
test.php:
<?php
$link = mysql_connect("localhost", "root", "password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("example");
$sql = "select * from data";
$x = mysql_query($sql);
$emparray = array();
while ($row = mysql_fetch_assoc($x)) {
$emparray[] = $row;
}
echo json_encode($emparray);
mysql_close($link);
?>
heatmap.html:
<script>
$(window).ready(function(){
$.ajax({
url:'test.php',
data:"{'id':'1', 'value':'1'}",
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function (data){setInterval(function(){
/* if I use parseJSON(data), I get "Unexpedted token <"
error */
$.each(data, function (id, value){ // error occures here
liveHeatMap(id); //Never called
});
}, 10000)}});
});
</script>
I think the problem is that the JSON is invalid. I have tried so many things and looked at many other similar problems but I still cannot fix it.

Remove the contentType and dataType properties in your AJAX request, and use an object (rather than a string) for your data. In your success function, remove the setInterval and manually parse the JSON string returned using JSON.parse(data). This ensures you have the most control over the data to prevent jQuery from causing problems (and also makes it clearer). jQuery may be interfering with the data in the process and you want the complete raw data.
It looks like you're receiving HTML. Common causes:
Your AJAX URL is pointing to the incorrect place (and it may not seem obvious -- try ./test.php or using an absolute path).
Your PHP is not killed after echoing the JSON. Replace mysql_close($link) with die() as when the script ends, all database connections are automatically closed anyway.
If you're still having issues, run these commands and comment their output:
console.log(data);
console.log(typeof data);

Related

Unexpected JSON behavior

I'm building a WordPress plugin. The PHP script sends the JSON, javascript receives it. Time to time, the js receives an empty JSON, even when I'm sure it should receive data. If I put an empty echo (echo ' ';), it fixes my problem and the data received correctly.
The receiver:
jQuery.ajax({
url: url + "get_bookings.php",
method: "POST",
data: {
week: t,
year: e
}
}).done(function(w) {
w = JSON.parse(w);
fetchTableData(w)
})
The sender:
echo ' ';
.
. // Code here.
echo json_encode( $query );
I couldn't find why this happens. Sometimes it works fine without the empty echo.
Edit: thanks for the answers, the exit did not help.
I checked the network panel, and it was requesting get_bookings.php twice. I put a slash at the end of the URL, and works fine.
url: url + "get_bookings.php/",
First, remove this line:
echo ' ';
Id suggest debugging the PHP script first by testing the resulting value for $query:
print_r($query);
If the value intermittently results as an empty string, then make sure to test for this and return an empty JSON object instead when necessary.
if (empty($query)) {
$query = (Object)[];
}
echo json_encode($query);
Please remove the second parameter true in json_encode and also issue is header already sent error.
You don't need header for json encode in ajax return. just add json_encode and that's it.

Trouble with inserting JS variable into MySQL table with PHP with AJAX

I am a pretty much a beginner to all of these technologies, I have been stuck all day on what I thought would be a fairly simple process. Basically, I'm trying to pass a parameter in a JS function through to my PHP code using AJAX, and then inserting the parameter into my database.
The JS function in my .html file.
function pushData(paramData) {
$.ajax({
url: "databaseStuff.php",
type: "post",
data: paramData
});
}
I wish to insert into my SQL table whatever I have put into the Parameters. For example the below code should create 3 new database entries. I have these hooked up to buttons in my actual project.
pushData('It is Wednesday');
pushData('My Dudes');
pushData('AHHHHHHH!');
databaseStuff.php
<?php
$mysqli = new mysqli("localhost", "root", "default", "testDB");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$paramData = $_POST['paramData'];
$sql = "INSERT INTO testDBtable (Name, Text) VALUES ('Joe', '$paramData')";
?>
My PHP is successfully connecting to the MySQL DB since I am getting the proper 'localhost via TCP/IP' message, however, I am getting stuck on:
"Notice: Undefined index: paramData in C:\wamp64\www\databaseStuff.php on line 23
Help is appreciated! I am not concerned with SQL injection vulnerability as this code will never leave localhost.
Try writing your Ajax data parameters like this
data: {
'paramdata':paramdata
}
Also, you never actually queried your data.
mysqli_query($mysqli, $sql);
But with the error that you're getting, it's likely because of the ajax data parameters.
If you just want to correct your code, replace the AJAX query with this:
$.ajax({
url: "databaseStuff.php",
type: "post",
data: {'paramData': paramData}
});
However, you should not concatenate user input with sql query directly because of SQL injections, I suggest you to use parametrized queries. Here is the PHP manual page with explanation and examples

Errors when attempting an ajax POST call to PHP to return SQL query variable to jquery

Im trying to trying to return a PHP variable which is made of a SQL query to the same database using jquery.
At the moment my method does not work but i cant figure out why. Currently getting the following messages on the PHP response along with the error alert configured in the js function:
Warning: Illegal offset type line 55
{"average":null}
Im very new to PHP and server side programming, so an explanation of where i am going wrong would be really good. I am sure it is just a really simple misunderstanding i have with how i am going about this.. its baffling me so far though!
javascript function to make ajax call to PHP page
so here i have defined an array and added 2 values to it to post to the PHP page.
once recieved i want PHP to change the value to one it will get by doing an SQL query
var javascriptvalue = []
javascriptvalue["id"] = "the id";
javascriptvalue["name"] = "the name";
function averageRecall() {
$.ajax({
type : 'POST',
url : 'recall.php',
data: JSON.stringify(javascriptvalue),
dataType : 'json',
success : function (result) {
console.log(result); // see too what we get in the request
console.log(result.average);
},
error : function () {
alert("error");
}
PHP:
Here PHP should run a query against the DB and return a single value into the variable $avg which will be passed to an array, coded to JSON and then echoed back into my JS callback function.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$avg = $conn->query("SELECT AVG(`Answer`) AS AvgAnswer
FROM (
SELECT `multi1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi5` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio5` AS Answer
FROM `zc_Answers`
) AS s1");
if (!$avg) {
echo 'Could not run query: ' . mysql_error();
exit;
}
header('Content-Type: application/json');
$avg2 = array('average' => $_POST[$avg]
);
echo json_encode($avg2);
$conn->close();
?>
First , try adding this to your php file because it doesn't return a JSON response :
header('Content-Type: application/json');
$avg = array(
'average' => $avgcalculation // you can try sending just a number to see if the script works excluding your query
);
echo json_encode($avg);
then , in your success function of javascript you have :
dataType : 'json',//So we need to do the header() step in php
success : function (result) {
console.log(result['average'])// ???????
},
You try to get an item of a javascript array by string index ... which is not possible.
1) You write dataType:json <<< So, the result variable is a object ! So you can access average value with :
success:function(result){
console.log(result); // see too what we get in the request
console.log(result.average); // thats all
}
UPDATE : in order to help you ._.
your php script is failing too because you are retrieving POST values that doesn't exist because you are not sending them !
Please read the documentation of $.ajax() here.
Try first with a simple script in php to see if your javascript works. Comment everything just let 2 lines.
header('Content-Type: application/json');
$avg = array(
'average' => $_POST["javascriptvalue"]
);
echo json_encode($avg);
then in your javascript file add the data tag (because you need to retrieve data in your server !)
data:{
javascriptvalue:"I'm sending this to php so it can be retrieved in my php script"
},
Finally your success javascript function should be executed without problem with :
success:function(data){
console.log(data);//an object with average property (data.average)
}
It should work anyway this is not dificult, read the documentation
"data: avg" in the Ajax call is the data you want to send to the PHP (your page form values) that's why "avg" needs to be defined in the javascript before making the ajax call, that's why you get "avg is undefined".
You need to create the variable and somehow fill it with the form values.
For the PHP if it is on a server you need to work a little bit more like Carlos explained.
I give you some example code from a project I'm working on:
JS CLIENT SIDE
//jsonvar is an array
jsonvar["id"] = "the id";
jsonvar["name"] = "the name";
$.ajax({
url: url_webservice,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(jsonvar), //turn jsonvar into json to send to the php server
})
.done(function(result) {
console.log("Show the result from the PHP in the console", result);
// Do all you want with the result
})
.fail(function(err) {
console.log(err.responseText);
// Do all you want in case of error
});
});
PHP SERVER SIDE
header('Content-Type: text/html; charset=utf-8');
//Get the data from the POST
$input_data = json_decode(file_get_contents("php://input"), FILE_USE_INCLUDE_PATH);
if(is_null($input_data))
{
trigger_error('Error empty input data in server.php', E_USER_WARNING);
}
//Do what you want with input data, sorry not familiar with mysql code.
echo json_encode($result); //Back to the client

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Why does jsonp return "Unexpected Token :" when using $.ajax() when my json is properly formated?

I'm using the below code to grab json from a remote address and use it's information in my project as a javascript object.
$.ajax({
type: "POST",
dataType: "JSONP",
url: "http://www.edupal.co/deals/?email=wed#umbc.edu",
jsonCallback: 'parseResponse',
success: function( data ){
console.log($.parseJSON(data));
},
error: function( xhr, str, e ){
console.log( "There was an error with the request", str, e );
},
complete: function(){
console.log("The request has completed.... finally.");
}
});
The problem is that although the request is being made just fine (I can see it in my networks tab in dev tools), it is telling me in my javascript console that there is an "Unexpected Token : "
Here is the JSON that is returning:
{"0":"1","id":"1","1":"20% Off UMBC Hoodies","title":"20% Off UMBC Hoodies","2":"umbc","school":"umbc","3":"UMBC Bookstore","location":"UMBC Bookstore","4":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","picture":"http:\/\/bookstore.umbc.edu\/StoreImages\/9-862269-1.jpg","5":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","description":"Limit 1 per person. Must present EduPal app with deal to cashier to be awarded discount.","6":"http:\/\/www.globatum.com","link":"http:\/\/www.globatum.com","7":"7\/30\/2014,08:45","start":"7\/30\/2014,08:45","8":"7\/30\/2014,09:45","end":"7\/30\/2014,09:45","9":"active","status":"active","10":"0","clicks":"0","11":"2014-07-30 20:18:30","posted":"2014-07-30 20:18:30"}
So i'm confused at what the problem could be. Can anyone help? I put it all in jsfiddle if anyone wants to test it. http://jsfiddle.net/#&togetherjs=T0ztQQbitP
Here is the PHP that generates the JSON
<?php
include('../dbconnect.php');
header('Content-Type: application/json');
$email = $_GET['email'];
$email = substr($email, 0, strpos($email, ".edu"));
$email = strstr($email, '#');
$school = str_replace('#', '', $email);
$sql = "SELECT * FROM `ads` WHERE `school` = '$school' ORDER BY `posted` DESC";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count > 0){
$deals = array();
$deals = mysql_fetch_array($result);
echo json_encode($deals) ;
}
else{
echo 'No records';
}
?>
It is not properly formatted.
JSONP must be a JavaScript program consisting of a single function call (to a function specified in the query string (usually via a callback parameter) which passes one argument (usually an object or array literal).
Your quoted response consists of a JavaScript object literal. Since the property names are identifiers instead of strings, it isn't even JSON. Since you are missing , between key:value pairs, it isn't even valid JavaScript.
The actual response I get (it looks like you are copy/pasting from the Chrome visualisation of the JSON instead of the source code) when I hit that URL is JSON — but not JSONP. So you shouldn't tell jQuery to process it as JSONP.
Since the URL doesn't appear to give permission via CORS, there doesn't appear to be any way to hit it directly with client side JavaScript unless you are hosting your HTML on www.edual.co so you'll need to use some server side code to relay the data to your JS.
JSON requires double-quotes around keys and commas for all but the last item.
...
clicks: "0"
...
should be...
...
"clicks": "0",
...
Note: even integer "keys" need to have double-quotes. So 0: "..." should be "0":"..."
Check out JSONLint in the future to double-check your JSON.
Also, JSON is not JSONP (source). You specify dataType: "JSONP", but you may just want dataType: "json". If so, as Barmar mentioned, you don't need to call $.parseJSON at all since data will already be a JSON object.

Categories

Resources