Unable to make php $_REQUEST from XMLHttpRequest data - javascript

I am trying to make XMLHttpRequest from my html frontend to the php microservice backend, sending data from the input to be manipulated, and displayed on html output
The function I am trying to execute is triggered by 'onlick'
Frontend
function markRequired()
{
input_text = document.getElementById('input-text').value
input_text2 = document.getElementById('input-text2').value
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var j = JSON.parse(this.response);
mark_required = j.answer;
displayMark();
}
};
xhttp.open("GET",markURL+"?input_text="+input_text+"?input_text2="+input_text2);
xhttp.send();
return;
}
}
Backend
<?php
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
require('functions.inc.php');
//main array
$inputtext = $_REQUEST['input_text'];
$furthertext = $_REQUEST['input_text2'];
$totalsofar = getTotal($inputtext, $furthertext) // In php unittest the function works, so i know it's not the problem
$output['string']=$inputtext."=".$answer;
$output['answer']=$totalsofar;
echo json_encode($output);
exit();
Whenever I run my html front end and call the function, markRequired() I am not getting any response. Status code is 200 and I can see the sent data in the request URL.
When I try to return the input string, I am getting a null response.
I can't use cURL for this particular project otherwise I would have.
Any help would be much appreciated!!

Related

I'm trying to get value in javascript to return it in PHP in JSON format

I created a date selection function with display of the choice at the bottom (Second box in green). I would now like to be able to retrieve the user's choice in PHP and then send it in JSON format. Thank you in advance for any suggestion or help.
enter image description here
Here's my code:
function setToSelected(me){
const x = document.querySelector("span.active");
if (x !== null) {
x.classList.remove("active");
}
me.className='active';
console.log(me.id);
var dateselected=me.id.split('-')
var day=dateselected[0].split('_')[0]
var daynum=dateselected[0].split('_')[1]
var month=dateselected[0].split('_')[2]
switch(day){
case 'lun':
day='Lundi'
break;
etc...
default:
console.log("erreur conversion day")
}
switch(month){
case 'jan':
month='Janvier'
break;
case 'fev':
month='Fevrier'
break;
default:
console.log("erreur conversion month")
}
document.getElementById("dateselected").innerHTML = "Selected restart date : "+day+" "+daynum+" "+month+" à "+dateselected[1]+"h"
}
});
So we have 2 technologies at work here, Javascript working in your front end and php working server side. To retrieve data server side in php you`ll need to do a post request to a php page from your front end because php is only executed serverside and not frontend. Steps as follows
get your date info in javascript
prepare data to send
send data to php page via xhr request
Example
// Step 1
var selecteddate = day+" "+daynum+" "+month+" "+dateselected[1]+"h";
// Now we have our javascriptobject called selecteddate;
// set target php page to post to
var url = "datereceiver.php";
// Step 2 create a post object
var dataToSend = {"fontenddate": selecteddate };
// Step 3 set request paramaters
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
// send request
xhr.send(selecteddate);
// set callback function to capture response from your php page(server)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// check response code
console.log(xhr.status);
// get your response from your php page
console.log(xhr.responseText);
}};
On the php side your (datereceiver.php) page can look something like
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$yourselecteddate = $_POST['frontenddate'];
$response = "date received";
}
else{
$response = "bad request";
}
// set response headers
header('Content-type: application/text');
echo $response;
?>

Posting js variables to PHP not running in any method

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';
}

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

How do I use AJAX to communicate with and run code on a server?

I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food == '')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Categories

Resources