unable to pass variable to other page using ajax - php

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);
?>

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
?>

ajax send a request in ajax and get the response

Morning! Please i will like to get some data from mySQL(like getting the number of rows of a mySQL table using ajax). Please how can i do it? Here are my 2 pages. The first one send a number to the php page and the second one do a request to the database and send the result to the page in ajax(the first one). The table voisin_par_distance has 3 columns: cel_id, cel_id_1 and cel_id_2 Thanks.
<!DOCTYPE html>
<html>
<body>
<script>
var xhr1 = new XMLHttpRequest();
var i=1;
var j=4;
xhr1.onreadystatechange = function() {
if (xhr1.status == 200 && xhr1.readyState == 4) {
document.getElementById('content').innerHTML = xhr1.responseText;
}
};
xhr1.open('GET', 'test.php?i='+i+'&j='+j, false);
xhr1.send('');
</script>
<?php
// I would line to get for example the number of rows of table voisin_par_distance which is returned by test.php
$m = (int) $_GET['n'];
echo $m;
?>
</body>
</html>
and this is the php page which is in the same directory.
<?php
$dbname='BD';
try {
$bdd = new PDO( 'mysql:host=localhost;dbname=BD', 'root', '' );
}
catch ( PDOException $e ) {
die("Could not connect to the database $dbname :" . $e->getMessage() );
}
$i = (int) $_GET['i'];
$j = (int) $_GET['j'];
//to select the number of rows of my table
$req = $bdd->prepare("SELECT serveur FROM voisin_par_distance WHERE cel_id_1=':cel_id_1' AND cel_id_2=':cel_id_2'");
$req->execute( array(
'cel_id_1' => $i,
'cel_id_2' => $j
) );
$nbre_ligne = count( $req );
?>
<!DOCTYPE html>
<html>
<body>
<script>
var nbre_ligne = <?php echo $nbre_ligne; ?>
var xhr = new XMLHttpRequest();
var a = 2;
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'show_map.php?n='+nbre_ligne);
xhr.send('');
</script>
</body>
</html>
Best and Easy way to use ajax:
$.ajax({// on an event
type: "GET",
url: "test.php", #with valid path
data: {col1: "value1", col2: "value2"},
cache: false,
success: function (responce) {
// alert your response to check data
if (responce.length > 0) {
var data = JSON.parse(responce); // Parse JSON
//Your logic here
}
}
});
In Your PHP file, return data in json format. e.g.
echo json_encode(array('col1' => $val, 'col2' => $val2));
exit;
I hope this will help you.

AJAX JSON Post to 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);

Creating a button that deletes data being displayed

Right now I have a program that uses AJAX to read in a XML file and a json file. The problem is once the user clicks one of these buttons the text stays on the page forever. I was wondering if there was a way to make a button that would delete the text and sort of start over. I tried making a reset button but it didn't work. Here is the code that I have. Thanks for the help in advance.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>" + responseObject[i].name
+ " lived during the " + responseObject[i].pet
+ " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3>Dinosaur Web Services</h3>
<div id="home"></div>
<button type="reset" value="Reset">Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();">JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();">XML Dinos</button>
</form>
</body>
</html>
You can empty the div before inserting the new value in it. Like below i have done for one of the div, and with same you can do to other.
Add this to your script
<script>
function reset() {
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = ""; // empty the div here
divObj.innerHTML = output;
}
</script>
and add this button in your HTML
RESET
Here you go:
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml");
xmlHttp.send();
}
function getJSON() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
function resetDivs(){
document.getElementById('msg').style.display = "block";
document.getElementById('dinoJSON').innerHTML = "";
document.getElementById('dinoXML').innerHTML = "";
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<div id="msg">Select a button</div>
<button type="reset" value="Reset" onclick="resetDivs();"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>

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