JS is not parsing PHP ResponseText - javascript

I have a JS-PHP script where the JS sends information to the PHP script and then displays the PHP response in my HTML page. The script works properly if I display the responseText in one area. When I try to parse the responseText so I can display it in different areas, the script doesn't work. Where am I going wrong?
End of my PHP Script:
...
$expert = $obj;
$pro = $obj1;
$superview = $obj2;
echo json_encode(array(first=>$expert,second=>$pro,third=>$superview));
?>
PHP response:
{"first":1860,"second":1100,"third":340}
JavaScript:
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4 && xmlhttp.status==200) {
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("geo").innerHTML='' + response.first;
document.getElementById("geo1").innerHTML='' + response.second;
document.getElementById("geo2").innerHTML='' + response.third;
}
}
HTML:
<div id="geo" ></div>
<div id="geo1" ></div>
<div id="geo2" ></div>
However, if I do not parse the text in JS, but just use the entire responseText, then the script works and displays the responseText in my HTML properly.
JavaScript - no parsing:
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response1 = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response1;
}
}
How can I parse the PHP response so I can display different variables in different areas in HTML?

Related

Unable to make php $_REQUEST from XMLHttpRequest data

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

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

Why is PHP not receiving my AJAX request string?

I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];

Categories

Resources