Passing javascript object to php file using ajax post method - php

Iam desperately trying to pass a json object using ajax post method to a php file, decode it and pass something back.
Php's json_last_error displays 4, which means Syntax error.
this.send = function()
{
var json = {"name" : "Darth Vader"};
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","php/config.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+json);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
};
};
};
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data["name"];
}
?>

You have to encode it to json if you want to send it as json.
xmlhttp.send("data="+encodeURIComponent(JSON.stringify(json)));
currently what you have will send something like data=[Object object].
The variable json is a JavaScript object which is not json. JSON is a data-interchange format which is basicly a subset of javascript. see http://json.org
var object = {"name" : "Darth Vader"};// a JavaScript object
var json = '{"name" : "Darth Vader"}';// json holds a json string

Related

Sending json using native javascript

I want to use native javascript to send a json to php file. Why my $_POST from get-translation.php is empty?
var xmlhttp;
json_data = JSON.stringify(a_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","get-translation.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(json_data); // json_data is simple json
$_POST only works for the default content type application/x-www-form-urlencoded.
For any other type of data - including JSON - you need to parse the raw input stream.
file_get_contents('php://input') will return the raw request body. Since this is JSON, you need to use json_decode to parse the json data into an associative array.
$jsonData = json_decode(file_get_contents('php://input'));
You need to make the JSON data a string:
json_data = JSON.stringify(json_data);

Get data from a JSON API into JS or jquery variable

I am trying to get some data from this api:
https://www.bitstamp.net/api/ticker/
into a jquery variable (to eventually display on a web page). It returns a JSON dictionary (more information here https://www.bitstamp.net/api/).
I tried for hours on end doing it all client side but realised that I cant because the api doesn't support cross-origin requests nor JSONP. So I then moved onto serverside code:
I have a php file 'test.php' with the following code:
<?php
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
Then inside my html page I have the following code:
<script>
var last = JSON.parse(test.php)["last"]
document.getElementById('apidata').innerHTML=last;
</script>
<span id="apidata"></span>
But I don't know why it's not working! Can anyone please shed some light on this?
I thought jquery may be simpler but if anyone knows how to get this done with JS I'd like to hear that too. I also suspect that my php file is wrong.
EDIT: Here's a link to my php file http://www.buyabitcoin.co.uk/beta/test/test.php
and my html file http://www.buyabitcoin.co.uk/beta/test/test.html
username: 'test' password: 'test123'
EDIT: I have also tried
$.getJSON('test.php', function(response) {$("#apidata").html(response.value); });
in the html but to no avail. Can anyoneplease confirm if my php is outputting a JSON rather than a string?
Many thanks in advance
Modify your php file like so:
<?php
header('Content-type: application/json');
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
The header() tells the requesting entity what sort of data it provides.
The url you request (https://www.bitstamp.net/api/ticker/) provides this json string:
{
"high": "161.00",
"last": "154.00",
"bid": "153.51",
"volume": "20295.34112055",
"low": "135.10",
"ask": "154.00"
}
Your html page has this JQuery:
$.getJSON('test.php', function(response) {
// access the response here
// e.g. get the volume
var volume = parseInt(response.volume);
// the numbers are returned as strings (numbers in quotes), thats why parseInt should be used
});
You can use jQuery ajax function to get JSON from the php page
like,
$.ajax({
dataType: "json",
url: 'test.php',
data: data,
success: function(data){
var last = data.last
$('#apidata').innerHTML=last;
}
});
Read more about jQuery.ajax http://api.jquery.com/jQuery.ajax/
You do not need to have jQuery just to download a JSON string and replace a div's content!
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
r = JSON.parse(xmlhttp.responseText);
document.getElementById("apidata").innerHTML=r;
}
}
xmlhttp.open("GET","/beta/test/test.php",true);
xmlhttp.send();
}
loadXMLDoc();
I managed to do what I want with the following code. This allows me to 'extract' a value from the JSON (in this example, the value for 'last') to use as a JS variable in a separate html file:
In my php file:
<?php
$ticker = file_get_contents('https://www.bitstamp.net/api/ticker/');
$obj = json_decode($ticker,true); // Split the JSON into arrays.
echo json_encode(array("myVariable" => $obj['last']));
?>
In my html file:
$.getJSON('test.php', function(data) {
var myVar = data.myVariable });
I hope this helps someone.

How to pass JSON via ajax to PHP?

I'm trying to pass a json string to php via ajax and php is not decoding it properly. a vardump in php after the decode always returns null. Can anyone tell me what I'm doing wrong. Big thanks!!!
var addObj= {"facility":"Baptist Medical Center",
"osb":"Jacksonville",
"office":"North Branch"};
var JSONstr = JSON.stringify(addObj);
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var rt = xmlhttp.responseText;
alert(rt);
}
}
xmlhttp.open("GET","jsontest.php?addObj="+JSONstr,true);
xmlhttp.send();
//php code in jsontest.php
<?php
var_dump(json_decode($_GET['addObj'], true));
?>
//php returns null
Try urldecodeing the parameter first:
var_dump(json_decode(urldecode($_GET['addObj']), true));

Sending Javascript Object to PHP via Ajax

I'm learning Ajax by failure and have hit a wall:
I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.
I have a function that is called when the user clicks the 'save' button. The function is as follows:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
My question is:
What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?
furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?
Thanks in advance.
If your array has more then 1 dimension or is an associative array you should use JSON.
Json turns a complete array structure into a string.
This string can easily send to your php application and turned back into a php array.
More information on json: http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
In php you can decode the string with json_decode:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&' to the query string each time.
furthermore, should I try using JSON?
You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.
And if so, how could I send a JSON object via ajax?
There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).
I found this question useful for Javascript enthusiasts.
Sending a javascript Object, be it js array or js object, you must stringify the setup before putting it to the server for decode & processing.
Stringifying a js object:
Based on your function:
case of Javascript Array object
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
case of Javascript Object object
let my_obj = {
name: "Daniel",
age: 23,
location: "Nigeria"
}
my_obj = JSON.stringify(my_obj);
Ones on point you can push this to the server, as per use case, u're working with AJAX GET method in sending your stringified object to the server.
Here is the full code:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById('message').innerHTML = this.responseText;
// if your returned response is in json, please, do ensure to parse the response before displaying
// like this JSON.parse(this.responseText)
}
}
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
var url = "create_amenities.php?my_json=" + my_array;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here are what i noticed out of your codes:
You don't need to call xmlhttp inside of xmlhttp object again, all you need is the this
I included the my_json parameter that holds the array object you are sending to the server.
Now, here in the server, you will need to catch the object and convert it to php readable object.
$my_json = $_GET['my_json'];
$my_json = json_decode($my_json);
Now, you can do whatever you wish it, because it has now become a full php array.
Example to pick the first array option:
$first = $my_json[0];
echo json_encode($first) // hahaha, you echoed it for AJAX to display
// i used to json_encode() to convert from php object to a js readable object
First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.
The best approach to your actual problem would be to submit your array as cgi parameters.
If the checkboxes are in a form, you need to do very little - simply submit the form,
<form><input type=checkbox ...><input type=checkbox ...>
$.post("test.php", $("#testform").serialize());
See http://api.jquery.com/jQuery.post/ for more details on how to do that.
Your list will turn up as an array in PHP.
Or to augment your own example with something very simple, do this:
url = url + '?checkboxes=' + checkboxes.join(',');
Now just split it inside PHP and you've got it back!

Decoding a JSON Array From Ajax Request

I finally succeeded in using Ajax to get SOMETHING sent from one page to another! What I'm trying to do is pass an array from a PHP file to a Javascript file, and the Javascript file is receiving this in this.responseText:
<html>
<head>
<script type="text/javascript">
var jsonArray = ["chickens","horses","cows","werewolves","zombies","vampires","phantoms","U.S. Congressmen","performance artists","pieces of fencepost","barnhouses","robots","cyborgs"]
</script>
</head>
</html>
I tried running eval() and alerting the result, but no result appears. How do I successfully extract the array from this.responseText?
Edit Here is my function thus far:
/*
* Function: selectVictim
* Called from function laserOn()
*
* Selects a random victim from a list of victims
*
* #return String: victim
*/
function selectVictim()
{
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();
request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function ()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null )
{
var vicArray = eval('('+this.responseText+')');
var numVic = Math.floor(Math.random() * (vicArray - 1));
alert(vicArray);
}
else alert("Ajax error: No data received");
}
else alert("Ajax Error: " + this.statusText);
}
}
request.send(params);
}
Second Edit The file containing the array (in PHP) is as follows:
<html>
<head>
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
<script type="text/javascript">
var jsonArray = <?php echo json_encode($victims); ?>
</script>
</head>
</html>
If your php page is returning all the text that you reported (with <html> etc...) then your output is not a JSON object, but an html page. Your response should contain only your serialized JSON object (and the proper http response headers)...
Once you have 'cleaned' your output you can use JSON2 library to parse your object:
http://www.json.org/js.html
var myObject = JSON.parse(myJSONtext);
That does not look like a proper JSON response from the server, because it contains HTML code and then a chunk of javascript. The response should contain only javascript code containing data, like
var data = ["chickens","horses","cows","werewolves","zombies"]";
You can then eval() the string and it will work.
As said above, eval() might be unsafe, so, if using jQuery, you can use the $.parseJSON function which is safe.
To return the JSON correctly, don't output HTML at all in the page, just do something like
<?php
$victims = ...; // fill array
echo json_encode($victims);
?>
You can use the library on json.org or use eval("(" + this.responseText + ")");
Generally you want to use a library to parse the JSON string instead of eval because eval is generally unsafe.

Categories