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

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

Related

PHP file path not found when I have JavaScript run a PHP script with XMLHTTPREQUEST (404 error); what to do?

When I hit the button on the UI to have the JS communicate with PHP to pull up a "Hello world" page, I am getting a "{"timestamp":"2021-06-10T20:14:59.671+00:00","status":404,"error":"Not Found","message":"","path":"/hello.php"}" in the browser.
In the Eclipse console, it says: 2021-06-10 16:52:27.193 WARN 16688 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": projectname/src/main/webapp/WEB-INF/jsp/hello.php]
What do I do? Here's some code I have, and I have tried many file path formats where I refer to the PHP file. But it's all the same error!
Here's some of my code:
JSP page (just the Javascript part of it):
<button onclick=refreshData()>Say Hello</button>
<div id="content" />
<script type="text/javascript">
function refreshData(){
var display = document.getElementById("content");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "hello.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
display.innerHTML = this.responseText;
} else {
display.innerHTML = "Loading...";
};
}
}
</script>
PHP
<?php
print "<p>Hello World</p>";
?>
This is in Spring MVC using Eclipse. I have the JavaScript on a JSP file page. What do I do to fix this? Thanks!
I always use:
$('#content').load("hello.php");
Just be sure your .php file is in the same folder

Passing variables from javascript to php file

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.

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 there any way to pop an alert in a page only after a .php file has finished executing in php server?

is there any way to pop an alert only after a .php file running from php server is done executing? this may be the only way to fix my problem if there is...
my .php is:
<?php
$output = exec("arduino_debug.exe --upload RIKDuino\RIKDuino.ino
IF !ERRORLEVEL! == 0 (
echo upload success!!
pause)
IF !ERRORLEVEL! NEQ 0 (
echo upload failed
pause) 2>&1" );
echo $output;
?>
my function that executes the .php file in my html page
function UploadToRIK()
{
ForIde();
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status== 200)
{}
}
xmlhttp.open("POST","Arduino/upload.php",true);
if(window.confirm ('Code will be Uplaoded to RIK Robot! Please Press OK to Continue...'))
{
xmlhttp.send("upld");
}
}
You are almost there. Just add the logic you want inside the callback function which is attached to the onreadystatechange event:
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status== 200)
{
//put some logic, for example:
alert('All good! ' + xmlhttp.responseText);
}
}
This way you will see the alert popping out when a response is received (and the http status is 200), after your PHP script finishes.
You can also check for other states (or http statuses different from 200), in the case of failure, for example and treat them properly.
For further info about it, try
readyState
and
XMLHttpRequest

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.

Categories

Resources