Re-accessing input text data through JS from a PHP file - javascript

I have a server which I am storing standard text inputs once a submit button has been clicked, I have done this successfully and now need to recall all the inputs on a different button click. My lack of understanding of PHP starts to kick me as I have little to no idea how to retrieve this, I know that data within PHP files once ran is deleted so I need to create some sort of "storage" ( I found the use of $_SESSION to be the go to thing for this).
I then need to use my JS file to somehow recall the data that is temporarily stored but again have no idea how I can get an array that is stored on a PHP file across to a JS file.
Any brief explanation oh how this is done would be greatly appreciated as I am extremely new to PHP!
For reference I currently have:
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Form Was Submitted");
// var returnData = xhttp.responseText;
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("Data retrieved")
// var returnData = xhttp.responseText;
}
}
xxhttp.open("GET", "gethint.php", true);
xxhttp.send();
}
HTML:
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
PHP:
<?
session_start();
echo $_SESSION["input_data"] = $_POST;
print_r($_POST);
echo "Text Submitted". $_POST["input"];
print_r($_REQUEST);
echo "Text Retrieved" . $_REQUEST["input"];
?>

In your php you can encode the post data as json like so:
$_SESSION['input_data'] = json_encode($_POST);
And in your js you can the get the data by decoding it like so:
var data = JSON.parse('<?php echo $_SESSION["input_data"]; ?>');
This will give you a js object that you can access using the name you gave your input tags in your html.
ex: data.textInput would get that value of the textarea.

To easily access the php data in js , you can store the data in session.also use json format to throw data to js and access it in js via jeson array key value format if you have multiple form field to store and access.
Use json_encode() to throw from php to js.
Also you can save this data in cookie. Session and cookie are temporary way to store data. For permanent storage use a database like mysql and call this from js with json.

Related

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

Incorrect format of a JSON for generate an JSON object with JSON.parse

I have a web that draws a tree. inicio_pru.php creates a JSON which represents the tree.This JSON is passed to a JavaScript file for creting the tree.
inicio_pru.php, is called in two different moments, first , when the page is charged , it creates the JSON and passes it to example_pru.js in order this can draw it. 2nd, when the tree is already created, and user clicks a node of the tree, this invoques inicio_pru.php from example_pru.js with an object XMLHttpRequest and inicio_pru.php generates the JSON the same way as the 1rst time and this is sent to the XMLHttpRequest with an "echo" command.
It Works in the first case, but not in the second that generates the following error:
Unexpected token '
inicio_pru.php:
function main_p ($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros) {
......
//Here, $arbol is saved in the correct format
if ($tipo_var=='BIFURCADORES'){
$file = fopen("archivo.txt", "w");
//$file = fopen($desc_var.".txt", "w");
fwrite($file, $arbol . PHP_EOL);
fclose($file);
}
return $arbol;
}
//main program
if (!is_null($idnodo)) {
// main_p , has saved $arbol with each field of the JSON in double quotes
$arbol=main_p($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros);
//this sentence has saved $arbol at the discwith each field of the JSON without double quotes
exec('echo '.$arbol. ' >>/tmp/pista11', $output, $error);
//This is sent to example1_json_pru.js throght an objet XMLHttpRequest
echo $arbol;
}
else
$arbol=main_p($ID,$tipo_var,$desc_var,$idnodo,$t_ancestros);
As you can see, $arbol, is saved in two files:
archivo.txt , correct, it place each field in double quotes, but in pista11, fileds appear without these double quotes:
archivo.txt , (correct):
{"id":"53530","name":"Bifurcadores <ul ....
pista11 , (incorrect):
{id:53530,name:Bifurcadores <ul ......
In inicio_pru.php at the "else" sentence, $arbol is passed to another .php , that sends it to .js example_pru.js, and it works:
grafos_template_otro_json_fr_pru.php:
<!-- Files -->
<script language="javascript" type="text/javascript" src="../mapas/assets/js/example1_json_pru.js"></script>
<script type="text/javascript">
var datos=<?php echo $arbol ; ?>;
var ID=<?php echo $ID ; ?>;
var tipo_var=<?php echo $tipo_var ; ?>;
</script>
</head>
<body onload="init(datos,1,ID,tipo_var);">
(init is una function of example1_json_pru.js)
However, when init_pru.php is called from the XMLHttpRequest and it pases $arbol to example1_json_pru.js this way, it doesn't work, and generates the error mencioned before:
XMLHttpRequest:
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
var http = new XMLHttpRequest();
var url = "inicio_pru.php";
var params = "idnodo="+ node.id + "&ID=" + ID + "&id_arbol=" + tipo_var;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
//astonishingly, alert shows the fields of the JSON in quotes despite pista11 (file saved just before sending $arbol XMLHttpRequest object), showed them wihthout double quotes
alert (http.responseText);
//This is the sentence that generates error:
json=JSON.parse(http.responseText);
st.loadJSON(json);
//compute node positions and layout
st.compute();
//optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), "current");
st.onClick(node.id);
}
}
};
Could you please help me? Thank you very much indeed
the issue is that your json has invalid format.
archivo.txt , (correct):
{"id":"53530","name":"Bifurcadores
pista11 , (incorrect):
{id:53530,name:Bifurcadores
in above example you can see you are missing " " in variables and values.

how do you connect an ajax post to a specific conditional in PHP file?

So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Post Javascript to PHP and then retrieve in another javascript

I m trying to post the value from my java_post.js into php_post.php and then retrieve in another javascript page, index.html. So far i can post the value into the php_post.php and retrieve back into my java_post.js as alert(data)
but i cannot retrieve from my index.html
Java_post.js
var url_link ="index.html";
//On Click Select Function
$("#table_hot").on('click', 'tbody tr',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
$.post('PHP_post/php_post.php',
{
postvalue:value
},
function(data){
alert(data);
}
);
});
//Window Pop Out Function
function hotspot_pop(url_link){
newwindow = window.open(url_link, '', "status=yes,
height=500; width=500; resizeable=no");
}
The value is retrieve when the client click the selected table and then post into the php_post.php. The php_post.php will filter the result and return to index.html.
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
echo $filtered_students;
So now i m able to retrieve the value and post into as an alert for my java_post.js but the value is no pass into index.html and i receive the error for undefined postvalue.
<html>
<script src="js/jquery-1.11.1.min.js"></script>
<body>
<div id="result"></div>
<script>
var xmlhttp_user = new XMLHttpRequest();
var url_user = "PHP_post/php_post.php";
xmlhttp_user.onreadystatechange=function() {
if (xmlhttp_user.readyState == 4 && xmlhttp_user.status == 200) {
document.getElementById("result").innerHTML=xmlhttp_user.responseText; }
}
xmlhttp_user.open("GET", url_user, true);
xmlhttp_user.send();
</script>
</body>
</html>
So my problem is now, is there any method that allow me to show the value in index.html from php_post.php. As a reminder the alert(data) from java_post.js is just a testing purpose to show the value did post and return from php_post.php
The issue you're having is that when you pass the data into your PHP file and receive the data back in your JavaScript, the information only lasts as long as your current request.
To fix this issue, consider using PHP Session variables to store your data, so that you can retrieve it later.
Example:
// php_post.php
<?php
start_session(); // initializes session for persistent data
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
$_SESSION["filtered_students"] = $filtered_students; // You can now retrieve this in
// Another PHP file
?>
Now in another file (you would switch your HTML file to get from php_get.php):
//php_get.php
<?php
start_session(); // Don't forget to start the session
echo $_SESSION['filtered_students'];
?>
More information here: http://www.w3schools.com/php/php_sessions.asp
You can set the desired value into PHP session while at php_post.php.
This way, you can retrieve the session's value on any page you desire.

post data to PHP page in external server and load content from JavaScript in local computer

I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>

Categories

Resources