I have some experience with Nodejs so I wanted to try some php too.
I want to make a GET request in a php file and get a response. While I get data, I receive them twice. I cheked the network tab on my browser and I see only one request. The html/javascript code works without a problem on nodejs, php persists on sending data twice. Why does this happen?
Html file:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>Hello User!!</p>
<button id="button">Get Request</button>
</body>
<script>
document.getElementById("button").onclick = function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php?id=HI", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 || this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.send();
};
</script>
</html>
test.php file:
<?php
ini_set('display_errors', 1);
$id = $_GET["id"];
if($id == "HI"){
echo ("Noice!");
}else {
echo ("I am sowwy :3");
}
?>
Disclaimer: "I understand this code does nothing important and always sends the same response. It is just an experiment to get myself familiar with php".
Thanks for your time.
You are not sending the responset twice but logging it twice.
onreadystatechange should be:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (this.status === 200) console.log(this.responseText);
}
};
Related
While learning JQuery and AJAX, I came across some exercises with GET requests to external files. (https://www.w3schools.com/xml/ajax_php.asp)
My JQuery script is as follows:
function displaySuggestions(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("suggestions").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
document.getElementById("suggestions").innerHTML = this.responseText;
}
}
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
Code is executed with following HTML code:
<div>
<h2>Display sugestions while typing</h2>
<div>
<form>
Fill in employee: <input onkeyup="displaySuggestions(this.value)">
</form>
Suggestions: <span id="suggestions"></span>
</div>
</div>
The output of the alert function is the whole PHP file as text.
Not sure if I am doing something wrong with the PHP file itself as I get the same result with an exact copy of the example code from the link above. I have created a file "gethint.php" with an exact copy of the PHP example code displayed at the bottom of the page from the link above
Ajax submit to self PHP file, but seems the PHP function do not execute.
<?php
function request(){
echo "<h1>requested</h1>";
}
?>
<html id="html">
<button id="btn_click" onclick="request1()">click</button>
</html>
<script type="text/javascript">
function request1(){
document.write("<h1>been clicked</h1>");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/index.php", true);
xmlhttp.send();
}
</script>
The JavaScript execute success, but seems the PHP code did not execute.
To add to what gibberish said, however, there's more to it. You must also keep in mind you don't seem to be executing the function at all.
A PHP function does nothing unless it is called.
function request() {
echo "<h1>Hello</h1>"
}
The function above will not be affected unless you call it:
request() // <h1>Hello</h1>
Also AJAX is best used when keeping requests simple. You send a request /path/to/file.php then that requests should return a plain text response or a JSON object, or a fully rendered static page if you are using a modal or some static item on your site.
/path/to/file.php
<?php
if( $_GET['clicked'] ) {
// do whatever
echo json_encode([
'user_id' => 1,
'total_clicks' => $_GET['clicked'],
'random_number' => rand(100, 999)
]);
}
The JS can easily handle the response:
function request(id) {
return fetch(`/path/to/file.php?clicked=${id}`)
.then(res => {
console.log(res);
body.innerHTML += res.user_id;
body.innerHTML += res.total_clicks;
})
.catch(err => console.error(err));
}
This will be the simplest way to have your server return information from the DB and make your page content as interactive as you need it to be,.
$_SERVER['HTTP_X_REQUESTED_WITH'] help us to detect an AJAX request
<?php
//Check Here Ajax Request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
function request(){
echo "<h1>requested</h1>";
}
request();
die;
}
?>
<html id="html">
<body>
<button id="btn_click" onclick="request1()">click</button>
<div class="response" id="result" ></div>
<script type="text/javascript">
function request1(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open("GET", "./index.php", true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // <-- ADD this
xmlhttp.send();
}
</script>
</body>
</html>
I have a checkbox that whenever it is checked it calls another php script using Ajax, now on the php script I got 3 text boxes with a button, and whenever the Button is pressed, Ajax will be preformed to call another php script. all of that are preformed in the same page!, it is just like this
PHP -> Ajax -> PHP -> Ajax -> PHP
Is it possible, or too much to process?!
my first Ajax is:
<script type = 'text/javascript'>
function load(cb, pos)
{
if (cb.checked == false)
{
document.getElementById(pos).innerHTML="";
return;
}
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById(pos).innerHTML = xmlhttp.responseText;
}
xmlhttp.open('GET', "trying.inc.php?pass='true'", true);
xmlhttp.send();
}
</script>
The second Ajax that is in "Tring.inc.php":
<script type = 'text/javascript'>
function check()
{
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById('adiv').innerHTML = xmlhttp.responseText;
}
Parameters = "OldPass="+document.getElementById('OldPass').value+"&newPass="+document.getElementById('newPass').value+"&Confirm="+document.getElementById('ConfirmPass').value;
xmlhttp.open('POST', 'Trying2.inc.php', true);
xmlhttp.setRequestHeader ('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(Parameters);
}
</script>
that calls "Trying2.inc.php".
now when I am at "trying.inc.php" page, Ajax works in calling "trying2.inc.php", but from the main page I can call "trying.inc.php" however, "trying.inc.php" can't call "trying2.inc.php", I hope it is clear because I don't know how to explain it more. If it is possible what can I do to achieve it, please support it with code. Im doing this for learning purposes please don't be harsh on me, Thanks in advance.
If you are using jquery, you could use bind/live on the elements newely added to the dom, thus you must be able to do this.
This question may have been asked a million times in the past but I am yet to come across a solution. So I ask again, hoping a less
aggressive answer like "Look somewhere else" or "Don't repeat
questions". If the reader feels the urge to type any of or similar to
the aforementioned sentences, I can only request the reader to refrain
from doing so and ignore this post completely. Any help is greatly
appreciated.
The problem
In my program, an AJAX script works to communicate with a PHP script. There are no syntax errors. The AJAX receives the responseText well and alerts it out.
alert(request.responseText); //this works as desired
But fails to return it to another function.
return(request.responseText); //this actually returns undefined
The full code
Client file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
<script type="text/javascript" language="javascript">
function createXMLHttp()
{
var xmlHttp = null;
if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajax_phprequest(data, php_file)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return request.responseText; //changed from return(request.responseText;);
}
}
}
function foo()
{
alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
}
</script>
</head>
<input type="button" id="somebutton" value="Call foo()" onclick="foo();" />
<body>
</body>
</html>
The full code
auth.php file
<?php
$user;
$pass;
if (isset($_POST['user'])) $user = $_POST['user'];
else
{
echo 'err_u_Username is not specified';
exit();
}
if (isset($_POST['pass'])) $pass = $_POST['pass'];
else
{
echo 'err_p_Password is not specified';
exit();
}
if ($user = 'defuser' && $pass = '123456') echo ('That\'s right!');
else echo ('That\'s not right!');
?>
This can easily be solved by including the code in the same file as the document. But I wish to call the function from a different file and then return it to the file that has foo() or the document. Simply, I want the AJAX function to return the responseText without it giving an `undefined' every time. If this has anything to do with synchronization: I want to know of any workarounds against this problem.
The gist of it has already been mentioned, but I would like to go into a bit more depth as to why this doesn't work.
You have the following code:
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return(request.responseText);
}
}
Basically, you are setting the onreadystatechange event to the value of an anonymous function. In that anonymous function, you are returning a value, which won't be returned to the caller of ajax_phprequest(), but to the caller of the anonymous function, which is the event system and which doesn't care much about what value is returned.
This happens this way because it all happens asynchronously. In other words, you call ajax_phprequest() and all that happens at that moment happens behind the screens. The user can continue working like nothing has happened. However, in the background, the php file is requested and hopefully returned. When that happens, you get to use the contents, but the moment at which you called ajax_phprequest() has long since passed.
A proper way would be to use a callback function instead. It could look something like this:
function ajax_phprequest(data, php_file, callback)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
callback(request.responseText);
}
}
}
function foo()
{
ajax_phprequest("user=defuser&pass=123456","auth.php", function (text)
{
alert(text);
});
}
That is because the call is ASYNCHRONOUS so you cannot return from stack the usual way, i.e. your alert(ajax_phprequest("user=defuser&pass=123456","auth.php")); is evaluated before the ajax response is returned ... you need to use a callback:
function callback( text ){
// something
}
...
if (request.readyState == 4){
callback( request.responseText );
}
The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.