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));
Related
Hi I am new to this forum and hoping someone could help I have set a dropdown menu with option value dynamically pulling in from a mysql database. these values when selected use xml to return the ids and content according to whats been selected. In the url there is a variable which im having trouble getting PHP to create a session variable from it. Can this be done? Thanks
Thanks, this is the code where the url is set
function showUser(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("state").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("state").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send(null);
}
The php call '$id = $_GET['q'];
$_SESSION['q'] = $id;'
Do you mean this?
http://www.domain.com/?action=delete
$action = $_GET['action'];
$_SESSION['action'] = $action;
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
How do I send a javascript value to a PHP page, then reference that value IN the PHP page?
Assuming I have some sort of javascript AJAX solution such as this:
var id=5;
obj.onreadystatechange=showContent;
obj.open("GET","test.php",true);
obj.send(id);
I want to work with this particular id in the test.php. How can I do this?
In the javascript (I'm making a function so you can assign it to some other event)
//jQuery has to be included, and so if it's not,
//I'm going to load it for you from the CDN,
//but you should load this by default in your page using a script tag, like this:
//<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><\/script>')
function sendValueGet(passedValue){
jQuery.get('test.php', { value: passedValue });
}
function sendValuePost(passedValue){
jQuery.post('test.php', { value: passedValue });
}
And then in your PHP:
<?php
if( $_REQUEST["value"] )
{
$value = $_REQUEST['value'];
echo "Received ". $value;
}
?>
Notice that I use "value" in the javascript "object" { value: ... } and in the PHP "REQUEST" variable $_REQUEST["value"]
If you want to give that a different reference name, then you need to change it in both places.
Using GET or POST is your preference.
Change your code to this:
obj.open("GET","test.php?id=" + id,true);
obj.send();
Then in test.php use $_GET['id']
//GET
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("GET","test.php?q="+id,true);
xmlhttp.send();
in test.php
$id=$_GET['q']
//POST
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send("x=id");
in test.php
$id=$_POST['x']
Hi i am trying to send Json via Ajax to PHP using Javascript. The data is sent correctly by index.html when I view it on firebug. It shows Json type with the correct data.
However, it seems that I am unable to read the JSON on php. I am unable to access it using $_POST.
I tried using $_POST['name'] and there is not response.
When i try using $_POST, the response is array.
Can you please help me?
Here is my javascript code.
<html>
<head>
<script type="text/javascript">
//Create Http request depending on browser
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){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;}
}
// Function to create
var url = "control.php";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var data=JSON.stringify({"name":"John", "time":"2pm"});
xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
This is my php code
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST['name']);
echo $value;
?>
Have been working on this for days and I really appreciate any help that you can offer.
Thank you!
here it's:
print_r($GLOBALS['HTTP_RAW_POST_DATA']);
I think that it needs to parse the whole post first.
<?php
include_once('JSON.php');
$json = new Services_JSON();
$value = $json->decode($_POST);
echo $value;
?>
But also do you need these includes?
http://www.php.net/manual/en/function.json-decode.php
include_once('JSON.php');
$json = new Services_JSON();
can you not just do this?
echo json_decode($_POST)
An even better solution (see here) is use:
$json = json_decode(file_get_contents("php://input"), true) ?: [];
print_r($json);
I have a variable localStorage.lastUpdate which stores a timestamp such as 1332237161. I need to pass that timestamp to the server which im trying to do by the line below with:
listener.php?q="+localStorage.lastUpdate
I also have another variable, localStorage.numUpdates that should receive the number of updates back from the server. I am confused whether I can use the below code with xml to run commands. Can my server side php file do something of the following
echo "localStorage.numUpdates=".$currentCount.";";
echo "localStorage.lastUpdate=".time().";";
where it would take affect on my localStorage variables in the javascript portion?
function contactServer()
{
if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlhttp.responseText;
}
}
xmlhttp.open("GET","listener.php?q="+localStorage.lastUpdate,true);
xmlhttp.send();
}
Any information would be helpful, thanks!
That won't work (and don't use eval()!).
But you can just output JSON in your PHP script:
echo json_encode( array('lastUpdate' => time(), 'numUpdated' => $currentCount) );
And in your JavaScript code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = JSON.parse(xmlhttp.responseText);
localStorage["lastUpdate"] = result["lastUpdate"];
localStorage["numUpdated"] = result["numUpdated"];
}