passing json object with ajax to php - php

I have set up a basic api and I know its working because requests that come with postman pass normally ,what I am having trouble with is passing the JSON object through AJAX to the php file.
The AJAX part
function add_book(){
if(validate()){
var jsonData = {};
jsonData.Price = document.getElementsByName("Price")[0].value;
jsonData.Title = document.getElementsByName("Title")[0].value;
jsonData.Author = document.getElementsByName("Author")[0].value;
jsonData.Genre = document.getElementsByName("select_dropdown")[0].value;
alert(JSON.stringify(jsonData));
var request = new XMLHttpRequest();
var url = "/books.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
}
}
request.send(jsonData);
}
}
For example this is the alert I get from stringifying the object
{"Price":"23","Title":"asdas","Author":"dasda","Genre":"Science fiction"}I can basically copy/paste this string to postman and it works as intended.
Now to the php part
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj->Price) && !empty($json_obj->Genre) && !empty($json_obj->Author) && !empty($json_obj->Title)){
The if always returns false ,while it should not ,again postman requests pass for true.
========================================================================
EDIT :
I managed to find the source of the problem . I made a function to check if the json is valid , turns out its not , there is no problem in the php part as it turns out . Here is the function in case someone needs it / wonders :
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
=========================================================================Edit 2:
The problem was on the request.send(jsonData); part . Fixed it with request.send(JSON.stringify(jsonData));
Thanks for your time !

This is the problem
$json str = file_get_contents('php://input');
The post parameters should be accessed by $_POST.
Instead try this
$json_str = $_REQUEST['jsonData']`;
and also do a var_dump for $json_str

Does this help?
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj['Price']) && !empty($json_obj['Genre']) && !empty($json_obj['Author']) && !empty($json_obj['Title'])){

I think the problem is the file_get_contents(). Maybe you try to echo it.
And for the if you could write:
if (!(empty($json_obj->Price) && empty($json_obj->Genre) && empty($json_obj->Author) && empty($json_obj->Title)))

Related

PHP not getting JSON values sent from retrofit

I'm sending values user and id as JSON values to server using POST request.
On server I'm getting values using:
$data = file_get_contents('php://input');
$json = json_decode($data, true);
if (array_key_exists('user', $json) && array_key_exists('id', $json)) {
...
echo "received";
}
else {
...
echo "not received";
}
But it always ends in "not received".
I tried to throw new Exception to see values for $data and for $json, and here is what I got:
Uncaught Exception: $data:"{\"user\":\"usr\",\"id\":\"0\"}"
Uncaught Exception: $json:{"user":"usr","id":"0"}
It should work, but it's not working for some strange reason.
If I replace $data = file_get_contents('php://input'); with $data = "{\"user\":\"usr\",\"id\":\"0\"}";, then it works.
But if I replace $json = json_decode($data, true); with $json = "{'user':'usr','id':'0'}";, then it's not working.
I also tried to run this code in PhpStorm and it works normally. I tried replacing both $data and $json with their actual values and it works all the time, like it should work.
Does anyone have any idea why it doesn't work on the server?
EDIT:
Kotlin part:
#Headers("Content-type:application/json")
#POST("user.php")
suspend fun getUsers(#Body body: String): List<User>
val jsonObject = JSONObject()
jsonObject.put("user", user)
jsonObject.put("id", "" + id)
val users = network.getUsers(jsonObject.toString())

Saving data across multiple lines JSON

Currently I have PHP and JS save my data in a JSON.
Below is the code for it:
PHP:
<?php
$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];
$item = $_REQUEST["item"];
// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
echo $data["passwords"][$key]['timesToUse'] - 1;
if ($password['password'] == $q) {
$data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
$data["passwords"][$key]['winningItem'] = $item;
}
}
$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);
?>
JS:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();
The issue that I am having is that initially my JSON file looks like this:
{"password":"IS360H","timesToUse":1,"winningItem":""},
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""},
{"password":"99NOTX","timesToUse":1,"winningItem":""},
{"password":"X2Z8BO","timesToUse":1,"winningItem":""},
{"password":"R9G4Q0","timesToUse":1,"winningItem":""},
{"password":"CG9RGT","timesToUse":1,"winningItem":""},
As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:
{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},
What do I need to do to make my JSON file preserve the line breaks?
Thank you!
There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Read more about json_encode

json_decode() not working

I am using ajax to send data with JSON and it keeps returning null. Here is the string I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
It is sent via post. Here is the code I send it with:
function slash(strr){
var re = /([^a-zA-Z0-9])/g;
var str = strr;
var subst = '\$1';
var st = encodeURIComponent(str.replace(re,subst));
console.log("st");
return st;
}
function create() {
var info = {};
var code=editor.getValue();
info.username=username;
info.code=slash(code);
var name=document.getElementById('projectName').value;
name2=name;
info.name=slash(name2);
info=JSON.stringify(info);
console.log(info);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "create_project.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("info="+info);
}
When it gets received in the php file it is processed like this:
$info = $_POST['info'];
echo "<pre>".$info."</pre>";
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";
However for some reason the json_decode() doest work. Again here is the JSON I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
the first echo works correctly but the second one doesn't. How do I fix this?
json_decode() must be emitting an error which you are not checking. Functions like json_decode() and json_encode() do not display errors, you must use json_last_error and since PHP 5.5 there is also json_last_error_msg().
<?php
$str = '{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above outputs:
string(189) "{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}"
class stdClass#1 (3) {
public $username =>
string(8) "HittmanA"
public $code =>
string(136) "%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F"
public $name =>
string(10) "Untitled-1"
}
int(0)
string(8) "No error"
If we try to decode invalid JSON:
<?php
$str = 'foobar{';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above prints:
string(7) "foobar{"
NULL
int(4)
string(16) "boolean expected"
There must be an error in the JSON when you try to decode it. Check for errors usings the json_* error message functions. The error message will tell you what's wrong and it will be straight to fix once you know what the error is.
hello mister if you echo in php is equal to return or print in some functional programming.
if your using ajax, ajax is one way communication.
$info = $_POST['info'];
//this code will be return
echo "<pre>".$info."</pre>";
//this also will not be triggered cause you already return the above code
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";
Perhaps setting the xhttp content-type as json like
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data); ?>
As stated in this answer.
Looking at the object it looks like you have a ' inside your code parameter. I think that's invalid for encoding.
Using json_decode like this:
$info = json_decode($info);
Will return a PHP variable.
If you add the associative parameter as true (false by default) like this:
$info = json_decode($info, true);
Then it will return an associative array
http://php.net/manual/en/function.json-decode.php
I was struggling with this on my Windows 10 machine, PHP version 5.5.9 only to find that the php_json.dll file was not in the ext folder of my installation and obviously no extension to uncomment in php.ini file. I found the dll at http://originaldll.com/file/php_json.dll/31989.html. After copying it to my ext folder I added extension=php_json.dll to my php.ini file and restarted my apache server and it started working fine.

How to parse JSON in PHP

I'm trying to parse JSON sent by POST to my webservice.
I'm using Advanced Rest Client tool for Google Chrome to test restapi.
How can I read this request and response to it?
I'm sending key called "format" and "json" as value for this key. I'm adding JSON like
"{"id":"235325"}"
Part of my PHP API code:
if( strcasecmp($format,'json') == 0 )
{
//how to read that id = 235325?
}
Try the json_decode() function. It is the standard function to parse json in php.
If want to work with array:
$json = '{"id":"235325"}';
$array = json_decode($json, true);
foreach($array as $element){
if($element == 0){
}
}
With object:
$json = '{"id":"235325"}';
$object = json_decode($json);
if($object->id == 0){
}

passing a javascript variable to PHP with xmlhttprequest

Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
Thanks
Instead of
print_r($test);
use the echo
echo $test;
As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.
And your send function in ajax should be like this:
hr.send("value="+value);
In the send function, the parameter that passed must be a string like this:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
More tutorial is here.
I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.
The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long.
The code is:-
function getGame(str){
//Sends data to the php process "save Game".
var test = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send("data="+ test);
}
This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.
<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
fwrite($fp, $outputString);
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
This works for me and I hope it is useful to other newbies.

Categories