AJAX JSON Post to PHP - php

I'm trying to post JSON String via AJAX to PHP, but all examples not work.
First of all I learn https://www.w3schools.com/js/js_json_php.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post
Then i write own code. But no one of my example code below not working. And return one result:
index.php:6:string '[object Object]' (length=15)
index.php:7:null
index.php:8:null
First variant:
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Second variant:
<?php
if (isset($_POST['JsonPost'])) {
var_dump($_POST['JsonPost']);
var_dump(json_decode($_POST['JsonPost'], true));
var_dump(json_decode($_POST['JsonPost']));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Please help.
PHP Version 5.6.28
XAMPP v3.2.2 on Windows 10 (64-bit)
Browser Chrome 56.0.2924.87 (64-bit)
UPDATED
Working Example.
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
//var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
var JsonStr = JSON.stringify(SomeObject);
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Many thanks to all who answered.

var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
Here you are:
Creating some JSON
Setting the JSON as the value of an object property
Implicitly converting the object to a string (which will be "[object Object]")
Sending that string as the request body
But since you are trying to post JSON you should skip steps 2 and 3 … just pass the JSON:
RequestObject.send(JSON.stringify(SomeObject));

Change in you Second variant this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
to
RequestObject.send("JsonPost=" + JSON.stringify(SomeObject));
Why:
var JsonStr = { creates an new real javascript object
but this object can not used with + to concate it

Your problem is this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
that is still a javasript object, you have to stringifly the whole thing
so this should wok:
var JsonStr = JSON.stringify({JsonPost: SomeObject});
RequestObject.send(JsonStr);

Related

Assign php variable to javascript with AJAX

I use AJAX to call a php script. From within php I need to update a JavaScript variable:
<script>cf = <?php echo $cf; ?>;</script>
It seems that when JavaScript is generated asynchronously in this way, nothing in JavaScript is updated.
Here is the code as requested by Rainmx93.
The PHP code:
<?php
$inr = str_replace( ',', '.', $_POST[ 'inr' ] );
$cf = 0; // will be passed to a JavaScript global variable
$decrStr = '
<h3>Some text</h3>
';
if ( $inr <= 0 ) { // string is evaluated by php as 0
echo '<p>Some Error message.</p>';
}
elseif ( $inr < 1.5 ) {
$cf = -2;
echo '<p class="my-red-box">Some feedback.</p>' . $decrStr;
}
?>
<script>
cf = <?php echo $cf; ?>;
</script>
The JavaScript code:
var form_data = "inr=1";
var xhr = new XMLHttpRequest();
xhr.open("POST", "/backend/filename.php", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = this.responseText;
document.getElementById("result").innerHTML = result;
}
}
xhr.send(form_data);
use JSON to parse data from php to script
example :
<?php
$var = "something";
?>
<script>
var new = <?php json_encode($var); ?>;
</script>
<?php
//Something can be here
?>

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

JSON data is not receiving in AJAX

This is my JavaScript file. It is not showing data received from PHP file.
var b1 = document.getElementById('button1');
b1.addEventListener('click',ajax_post());
function ajax_post()
{
document.getElementById("status").innerHTML="You have pressed submit button";
var hr = new XMLHttpRequest();
if(!hr)
{alert("cant create object");}
else {
alert("object created");
}
var url = "popup.php";
var fn = encodeURIComponent(document.getElementById("firstname").value);
var ln = encodeURIComponent(document.getElementById("lastname").value);
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function()
{
var obj = JSON.parse(hr.responseText);
document.getElementById("status").innerHTML=obj.firstname;
}
hr.send(vars);
return false;
};
and my php file is:
<?php
$header = "Content-Type: application/json";
header($header);
if (isset($_POST['firstname']))
{
$fnam=$_POST['firstname'];
$lnam=$_POST['lastname'];
$data=array("lastname"=>$fnam,"lastname"=>$lnam);
json_encode($data);
}
else
{
$data=array("firstname"=>"haider","lastname"=>"rehman");
echo json_encode($data);}
?>
If there is any error please let me know, I am beginner in programming.
you need to echo the json_encode()
replace
json_encode($data);
by
echo json_encode($data);

how to parse html already store in variable

I want to parse a shoutcast page like this :
http://relay.181.fm:8800/played.html
So, i just make ajax to call a php file. The php file return all the content of the page.
i store the html content to a var in js. Here is the code:
PHP:
function getcontent($server, $port, $file){
$cont = "";
$ip = gethostbyname($server);
$fp = fsockopen($ip, $port);
if (!$fp){
return "Unknown";
}
else{
$com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\n"
."Accept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible;"
." MSIE 6.0;Windows NT 5.0)\r\nHost: $server:$port\r\n"
."Connection: Keep-Alive\r\n\r\n";
fputs($fp, $com);
while (!feof($fp))
{
$cont .= fread($fp, 500);
}
fclose($fp);
$cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
return $cont;
}
}
echo (getcontent("relay.181.fm", "8800", "/played.html"));
Here is my js:
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
And that is what i want to get:
$(document).ready(function(){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();
time[i]=$('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
});
if i copy the xhr.response content and i put it in the html file and i execute this js, it return me exactly what i want.
but i dont get how i can do when the html is in a variable... :'(
PS: i work on a wamp env., And a node.js env.
Since you tagged it with jQuery, why not use the built in ajax functionality:
$.ajax({
url: 'http://localhost/getsong.php',
dataType: 'html'
}).done(function(data){
//do something with the HTML
var $html = $(data),
tdtexts = $html.find('table:eq(2) tr td:first').text();
});
Is this what you're asking for?
I think, you can use innerHTML to resolve
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=xhr.response;
document.getElementById('#div').innerHTML = parsed;
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
Proceeding further after getting response may help you like,
var xhr = new XMLHttpRequest();
var parsed;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parsed=$.parseHTML(xhr.response);
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
};
xhr.open("GET", 'http://localhost/getsong.php', true);
xhr.send(null);
By using $.ajax()
$(function(){
$.ajax({
url:'http://localhost/getsong.php',
dataType:'html',
success:function(parsed){
var songs=new Array();
var time=new Array();
for (var i = 0; i < 10; i++) {
songs[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(1)').text();// use find function for parsed string
time[i]=$(parsed).find('table:eq(2) tr:eq('+(i+1)+') td:eq(0)').text();
};
}
});
});
I think you're looking for jQuery.parseHTML(). It will parse your string into an array of DOM nodes.
http://api.jquery.com/jQuery.parseHTML/
Here's a quick example for your case:
$.get('http://relay.181.fm:8800/played.html')
.done(function(data) {
var parsed = $.parseHTML(data);
// Now parsed is an array of DOM elements which you can use selectors on, eg:
var song1 = $(parsed).find('table:eq(2) tr:eq(1) td:eq(1)').text();
console.log(song1);
});

Problem in php ajax post value

I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.

Categories