Passing variables from javascript to php file - javascript

I have worked on API (zomato) that gives me restaurant details. I want to insert them into my local database, but I have a problem with passing the variable to PHP because it's too much big for $_GET to handle it. I tried to use $_POST but The output of the post was empty.
// JS code
function showCafes(str){
var xhttp;
xhttp = new XMLHttpRequest();
console.log(str);
xhttp.open("GET","https://developers.zomato.com/api/v2.1/search?entity_type=city&q=t&start="+str+"&count=20" , true);
xhttp.send();
var restaurants="";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var r=JSON.parse(this.responseText);
var rest ={
name : r.restaurant[1].restaurant.name
};
$.post("addFromApi.php", rest);
window.location.href="addFromApi.php";
// PHP code
<?php
print_r($_POST);
?>
I expected from the PHP code to print the name of the first element in it.
// Sample output From API
{"results_found":1,
"results_start":0,
"results_shown":1,
"restaurants":
[{"restaurant":{
"R":{"res_id":18692654},
"id":"18692654",
"name":"East Village"}

I have solved it with making a form from js like this
document.getElementById("cafes").innerHTML += '<form id="rests" action="addFromApi.php" method="post"><input type="hidden" name="q" value="'+restaurants+'"></form>';
document.getElementById("rests").submit();
//resturants is the variable that I wanted to pass to php.

Related

Is there a way to pass data along with redirect after form submit?

I'm creating a form to query some internal sources for some of our employees. The data received is coming back as JSON. But basically the flow is this:
HTML Form > to PHP > redirect data to HTML results page to be formatted nicely.
If there is a simpler way I am open for suggestions but I'm trying to pass the JSON that PHP script returns to the results page to be formatted nicely.
I tried using the example from w3schools but it's not working.
This is all on an internal Linux Web Server.
test.html
...
<form action="../dir/dir/xxx.php" method="GET">
IOC/Indicator:<input type="text" name="ioc">
<input type="submit" value="Submit"><br>
</form>
...
xxx.php
...
$result = print_r((curl_exec($ch)));
echo $result;
curl_close($ch);
header( 'Location: ../../dir/results.html' );
...
results.html
...
<p id="results"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("results").innerHTML = myObj;
}
};
xmlhttp.open("GET", "../dir/dir/xxx.php", true);
xmlhttp.send();
</script>
...
End results should be on the lines of:
user submits IOC,
IOC gets ran through the PHP script,
user gets redirected to the results page where data from PHP script would be displayed

Is it possible to load content and variables via xmlhttprequest?

is it possible to load content AND variables from a *.php-File with xmlhttprequest?
I have a index.php:
<script>
function loadsite() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("divrequest").innerHTML = this.responseText;
}
};
xhttp.open("GET", "siterequest.php", true);
xhttp.send();
}
$(document).ready(loadsite());
</script>
<div id="divrequest"></div>
My siterequest.php:
<?php
echo "some dynamic content";
echo json_encode(array($var1,$var2,$var3));
echo "more dynamic content";
?>
Am I able to get the variables? Or did I misunderstand the function of XMLHttpRequest?
EDIT:
If I use
var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);
I will get the code of the whole page.
XMLHttpRequest sends an HTTP-request to the server to access the desired page. PHP is executed before the response data is sent back to you, in which case it's translated to HTML. Therefore, you can't get the variables using this approach with JavaScript. That happens before you even receive the data.

AJAX and PHP sending "HTTP get request" to the same page

My application gathers some client related information via JavaScript and submits it via AJAX to a php page.
See the code below:
index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.
How can I solve this issue?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.
If you do really want to merge, add it to the top of index.php (before printing data):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}

Ajax xmlhttprequest with POST to php file

Hello guys I am kina new in ajax and I have an issue, I want to call a php file to do some db queries from the javascript file. JS code
$(document).ready(function(){
$(".delete").click(function(){
var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4 && xhttp.status==200){
$(".delete").css("color", "pink");
}
};
xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("date="+date+ "&hour="+time);
});
});
And php file.
<?php
session_start();
require_once("../connection.php");
if($_SESSION["password"]!=null)
{
if(!empty($_POST["date"]) && !empty($_POST["hour"])){
$_SESSION["msg"]= "<script type='text/javascript'> alert('The appointment has been removed!');</script>";
$date=$_POST["date"];
$hour=$_POST["hour"];
...
I would like to point that the request is going properly, the php file is running if I sent data through html form with post,the problem is when I try it through the js file. The status is 200 and the readyState is going to 4 eventually. Is this below right when I call it from js??
$_POST["date"]
$_POST["hour"]
Did you try to add some brackets ?
if(xhttp.readyState==4 && xhttp.status==200) {
$(".delete").css("color", "pink");
xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("date="+date+ "&hour="+time);
}
The code is completely right, I found the mistake on method date. If I give date("Y-m-d", strtotime($date)) and the var $date instead of - has / or w/e it wont change the date to the format you expect.

Update a php variable with AJAX Javascript

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";

Categories

Resources