Posting js variables to PHP not running in any method - javascript

In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");

If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);

When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.

Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}

Related

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";

Data not getting passed via Ajax to PHP script

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

PHP not receiving JSON send by Ajax

I am trying to send some JSON data to a PHP file using Ajax. Here is my JavaScript code:
function updateJSON(){
var xmlhttpa;
if (window.XMLHttpRequest){
xmlhttpa = new XMLHttpRequest();
} else {
xmlhttpa = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttpa.onreadystatechange = function(){
if (xmlhttpa.readyState==4 && xmlhttpa.status==200){
console.log("Sent")
}
};
xmlhttpa.open("POST", "update.php", true);
xmlhttpa.send("json=" + JSON.stringify(json));
};
And here is the PHP file that processes the request:
<?php
$json = $_POST["json"];
file_put_contents('data.json', $json);
Unfortunately this isn't working. How can I repair my code?
Please, no jQuery.
Thanks!
Also, if you vote down, please tell me why so I can improve this question.
You should add line with setting Content-type when you POST your data.Try this:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Also :
xmlhttp.send("json=" + encodeURIComponent(JSON.stringify(json)));

Retrieving AJAX data in PHP

I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?
JS:
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(value);
}
You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.
You can try to read the raw post data:
$post = file_get_contents('php://input');
echo $post; // hello
Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
// Tell the server you are sending form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Send it as a query string
xhr.send('value='+value);
}
Then in your PHP, you can access $_POST['value'].
echo $_POST['value']; // hello
If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values
echo "<pre>";
print_r($_POST);
echo "</pre>";
From there you will know how to use the data in any file. You can do the same thing with $_GET
Try this, replace your xhr.send with
JS
xhr.send('value='+value);
PHP
echo($_POST['value']);

Categories

Resources