How can i parse php variable to my javascript function result? - javascript

I have a script, i have to parse javascript variable to PHP file, i've no problem with this function, in my console i can see that the username variable is sent, it's fine .
$.post("user_add-js.php", { username: username })
.done(function(data) {
alert("Data Loaded: " + data);
});
In my user_add-js.php file , i wrote the variable $data with a value but i can't return the value "test", the variable is empty . I guess i forgot to add something in my PHP code to parse the value from PHP to javascript .
<?php
$data = "test";
?>

you need to set the header
header('Content-type: application/json');
and also you have to encode the variable to json like this
echo json.encode($data);
once you get the result to javascript you should parse the json code
data = JSON.parse(data);
This solution helps you get you data from PHP in any format ( object, array, string ... )

Related

PHP - json_decode() of a JSON string is null

I'm calling this line in my browser:
example.com/save.php?params={"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]}
and here's my save.php code:
<?php
include 'Config.php';
$getJSON = $_GET['params'];
echo 'getJSON: '.$getJSON.'<br><br>';
$updateArr = json_decode($getJSON, true);
echo 'UPDATE_ARR: ' .$updateArr; //<-- it prints 'null'...
$jsonStr = file_get_contents("Users.json");
// Decode the JSON string into a PHP array.
$objects = json_decode($jsonStr, true);
array_push($objects, $updateArr);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($objects);
file_put_contents("Users.json", $jsonData);
// echo data
echo 'JSON DATA: ' .$jsonData;
?>
The problem is this code makes my User.json file 'null', it removes all objects in it, in fact, the echo 'UPDATE_ARR: ' .$updateArr; returns null.
I would need to decode my $getJSON string into a PHP array, as I do for my User.json file (the $jsonStr), but it doesn't work.
What am I doing wrong?
Thanks so much!
I have updated your code and tested at my side it's working now. Please try it.
<?php
include 'Config.php';
if(!empty($_GET['params'])){
$getJSON = $_GET['params'];
echo 'getJSON: '.$getJSON.'<br><br>';
$updateArr = json_decode($getJSON, true);
echo 'UPDATE_ARR: ';print_r($updateArr); //<-- it prints 'null'...
$jsonStr = file_get_contents("Users.json");
// Decode the JSON string into a PHP array.
$objects = json_decode($jsonStr, true);
array_push($objects, $updateArr);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($objects);
file_put_contents("Users.json", $jsonData);
// echo data
echo 'JSON DATA: ' .$jsonData;
}else{
echo 'Params is empty';
}
This is the outcome of users.json file after refreshing many times:
getJSON: {"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]}
UPDATE_ARR: Array ( [objID] => i8O0FRuGEr [username] => johndoe [password] => 123456 [email] => j#doe.com [followedBy] => Array ( [0] => john [1] => sarah ) ) JSON DATA: {"ID":"i8O0FRuGEr","user_name":"johndoe","pass":123456,"email_id":"j#doe.com","followed_By":["john","sarah"],"0":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"1":null,"2":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"3":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"4":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"5":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"6":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"7":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},"8":{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]}}
After using your users.json file:
[{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]},{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]}]
It seems $getJson is null.
check its value using var_dump function or print_r function.
var_dump($getJson); // see what is the output.
this is no JSON string, while you won't properly urlencode() the query-string.
die(urlencode('{"objID":"i8O0FRuGEr","username":"johndoe","password":123456,"email":"j#doe.com","followedBy":["john","sarah"]}'));
^ append the above PHP output as params=.
rather proper would be, to POST the JSON as the content.
PHP documentation states that json_decode() returns NULL if the string cannot be decoded. Most likely it is a syntax error originating from bad url encoding.
Why are you json encoding url parameters in the first place? URL encoding is the accepted way to pass params in urls.
EDIT:
print_r($updateArr);
Shows a correct json, thus the problem is elsewhere
There are several other issues with your code.
echo 'UPDATE_ARR: ' .$updateArr; throws Notice: Array to string conversion on line 6. Depending on your PHP version and configuration, your NULL could be printed because of bad typecasting in echo.
Warning: array_push() expects parameter 1 to be array, null given on line 12. Check if your users.json file exists and is correct.

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Writing a JSON object to an existing .json file

EDIT: My error checking shows that the php is being executed but when I check my .json file it's still the same as before.
I apologize in advance since this has been asked before but I've spent hours trying out different things and none have worked. Hopefully this might help someone in a similar situation. I'm trying to append a new entry to my existing json object from user input and write the updated json object back to the file. The last part is what's giving me trouble.
Here I'm using ajax to send my json object to a php file
$.getJSON("http://existing.json", function(data){
//append new entry to previous json array
data['posts'].push(objectt);
//confirming that new object is correct
console.dir(data);
//Sending json object to .php file so it can write to .json file
$.ajax({
type : "POST",
url : "json.php",
//data : data, this was changed to
data : {json:data}, //by the suggestion of suggested by madalin ivascu
dataType: 'json'
});
The above block of code executes and no errors are displayed in the console. Here is my json.php file. After the next block of code executes my .json file does not have the new entry.
$json = $_POST['json'];
if ($_POST['json'])
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo: "File was updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}
Change data : {json:data},
Return something from the php
$json = $_POST['json'];
if (json_decode($json) != null)
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo "File updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

Undefined Index in php: transfering variables from Ajax to php

Hello I tried to transfer variable from ajax to php, but php file keeps throwing me the following:
Undefined index: vals in /Applications/XAMPP/xamppfiles/htdocs/fang_sophie/project/sign in-out/bin/readall2.php
Ajax reads like this:
<script>
var var_data = "Hello World";
$.ajax({ url: 'bin/readall2.php',
data: {'vals' : var_data},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
</script>
Php reads like this:
<?php
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
?>
Why doesn't it work? Please help :)
One problem here is that you're trying to output JSON dataType:'json', where you don't have JSON to start with. Consult my footnotes also.
You need to use a text data type.
dataType:'text',
By the way, this won't echo anything at all (in the alert), since $hello is empty:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
You (may) want to echo the session array taken from the POST array, which is the logical thing to do:
echo($_SESSION['hello']);
Reference:
http://api.jquery.com/jquery.ajax/
Foonotes:
If by any chance you may be trying to access that (PHP) file directly, or your entire code is in the same file, then you need to use a conditional statement for it.
I.e.:
session_start();
if(!empty($_POST['vals'])){
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($_SESSION['hello']);
}
That, and/or use two separate files.
In regards to JSON; if you really want/need to use it, then set it back to dataType:'json', but use json_encode() for it and replacing echo($_SESSION['hello']); with and assigning the $hello variable to the session array:
$hello = $_SESSION['hello'];
echo(json_encode($hello));
<?php
//first start session
session_start();
//set header to json and UTF-8 encoding
header('Content-Type: application/json;charset=utf-8');
//check if $_POST['vals'] is set first using isset() to prevent notice
//undefined index
if(isset($_POST['vals'])){
echo "value of vals is: ".$_POST['vals'];
}else{
echo "vals not set";
}
?>
In your ajax request, the format of return is expect to be JSON. and you are returning a string.
You just need to add json_encode in your return line of php:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo(json_encode($hello));
The correct answer is you are reading the wrong variable:
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
It should be:
echo $_SESSION['hello'];
If you want the session data. For the undefined index, var_dump out your $_POST variable: var_dump($_POST);
If the $_POST variables do not match, or you get back an empty array, it was never transmitted to the server.
Original wrong answer:
When JQuery has "processData" flag set to false, it doesn't encode the data and requires the user reads it from the php://input stream.
Unencoded JSON is not sent into POST requests. For the quickest fix, try this:
parse_str(file_get_contents("php://input"), $vars);
// This will fill $vars with any data sent over to PHP.
var_dump($vars);
$vars should now be populated with the data you want. If $vars is empty, you are not transmitting the data.

Categories

Resources