How to use JSON between PHP and javascript - javascript

I have made an application requesting data to a PHP and javascript receives the data and displays it.
At first I did it by getting the data separated by ',' and it works fine, but I want to do it with JSON and this is where I have the problem.
I receive the data and try to decode them but it gives me the following error:
Uncaught SyntaxError: Unexpected token <in JSON at position 0
     At JSON.parse (<anonymous>)
     At XMLHttpRequest.xmlhttp.onreadystatechange
In the received variable I have:
"<meta charset="utf-8"/>
↵ {"rastro":"entrada:inicio-inicio-comprobarPerfil-conectar-","mensaje":"si","usuario":"Invitado47","password":"","email":""} "
My code is:
PHP
$jsondata = array();
$jsondata["rastro"] = $rastro;
$jsondata["mensaje"] = $mensaje;
$jsondata["usuario"] = $usuario;
$jsondata["password"] = $password;
$jsondata["email"] = $email;
echo '' . json_encode($jsondata) . '';
javascript
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var contenidosRecibidos = JSON.parse(xmlhttp.responseText);
I have looked at google for many examples and it seems all very simple but there is no way it works.
Thank you for your help

I don't know if this is the best solution but this is what I use to use JSON in Javascript via PHP.
PHP:
<script>
var datavalue= <?php echo json_encode($answers) ?>;
</script>
The data is a JSON object. I also recommend to have a look at jQuery, which provides excellent ways to call PHP pages and have JSON as a result.

It looks like your PHP page is throwing some error/warning.
Try to print response like this.
echo json_encode($jsondata);
That might not be the cause for your proble. But I strongly suspect that your PHP page is throwing some warning.
And are you sure $password is not "Undefined" ?
Try
console.log(xmlhttp.responseText)
before parsing it. You'll get the warning/error.

Thank you. The problem was in the beginning of PHP, in the first line had:
<meta charset="utf-8"/>

Related

JSON.parse reads "{\"number\":\"7\"}

Hi I have troubles to generate JSON with json_encode() PHP function.
I have a .php file that is doing only following:
<?php
// include_once for a few files here
$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;
result is following:
{"number":"7"}
Then there is jQuery in another file, retrieving this by following code:
$(document).ready(function e() {
let file_path = 'myJson.php';
let json = $.getJSON(file_path);
console.log(json);
let json_obj = JSON.parse(json);
However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?
I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.
If your web server sends JSON, it's good practice to set the Content-Type accordingly:
header("Content-Type: application/json; charset=utf-8");
On the client, you need to do:
$(document).ready(function() {
$.getJSON('myJson.php', function(response) {
// the response is already parsed by jQuery
alert(response.number);
});
}
$.getJSON() is asynchronous, so you need to pass a handler function to process the response.

Unable to parse JSON (xmlhttp)

I've gone through literally all of the other questions on this topic but I can't seem to find a fix for this relatively easy problem:
console.log(xmlhtpp.responseText) results in:
[{"id":"1","name":"Filosofie","image":"yin-yang.png","background_color":"no"},{"id":"2","name":"Politiek","image":"politics.png","background_color":"no"},{"id":"3","name":"Geschiedenis","image":"history.png","background_color":"no"},{"id":"4","name":"Vocabulaire","image":"vocabulary.png","background_color":"no"},{"id":"5","name":"Wetenschap","image":"science.png","background_color":"no"}]
The problem occurs when I try to parse the string to an object like so:
JSON.parse(xmlhttp.responseText);
Which results in the following error:
Uncaught SyntaxError: Unexpected end of input
The string originates from a PHP file:
$results = $db->query("SELECT * FROM library ORDER BY id", true);
$categories = array();
while ($row = mysqli_fetch_assoc($results)) {
$categories[] = $row;
}
echo json_encode($categories);
I need to loop trough the object eventually but I can't get past the parsing, any advice would be very much appreciated.
The default Content-Type from XAMPP is text/html, so your browser is trying to parse it like this..
Set the content-type yourself..
header('Content-Type: text/javascript');
echo json_encode(["foo", "bar"]);

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

Array not passing with ajax.

This is the java script code for ajax call. In this case code variable get a c program code and pass it to the compiler.php page.
function insert(){
var code = document.getElementById("file_cont").value;
var arr = new Array(code,"c");
alert(arr[0]);
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//window.location.assign("login.php");
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST","server_controlers/compiler.php?q="+JSON.stringify(arr),true);
xmlhttp.send();
}
Ajax call work well but the case is in php file. I'm decode the jason array to $arr variable. But if i echo like this echo $arr[0] it is empty. But if i not include the code to the array in the java script like this var arr = new Array("aaaa","c"); its works fine. Can some tell me what is the wrong when i send the array with code variable. This is the php file.
<?php
if(isset($_REQUEST["q"])){
$arr = $_REQUEST["q"];
$arr2 = json_decode($arr);
echo $arr2[0];
/*$file = fopen("../temp_files/c/mmm.c","w");
fwrite($file,"$arr[0]");
fclose($file);
shell_exec('gcc -ommm ../temp_files/c/mmm.c');
system('mmm', $retval);*/
}else{
}
?>
server_controlers/compiler.php?q="+JSON.stringify(arr)
Your data is not being made URL safe. You say that it contains c code, this means it might include (for instance) the & character which would break the query string format and cause the JSON to be invalid when extracted from it.
You need to run the data through encodeURIComponent before putting it into your URL.
server_controlers/compiler.php?q=" + encodeURIComponent(JSON.stringify(arr))
I think the problem in ur request type POST/GET. U shuffled 2 request types in 1. Also how i can see u try to send get request? but in parameters u use type POST.
All information what u need about GET request u can find here.
Also u can try change ur php code too. If u need to use POST
<?php
if($_POST){
print($_POST);
}
?>
After u can do all u need with data array.

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Categories