trying to change a php variable via js and echo back but its not working, been on it for days!!
I have a function handleServerResponse() called below, that alerts connection status, and getting the ok at status 200 so cant understand why my php variabe is not changing! driving me insane!
function process() // send the info to the server
{
if(xmlHttp)
{
try
{
xmlHttp.open("GET","myFile.php?phpvar="+jsvar,true);
xmlHttp.onreadystatechange = handleServerResponse; //alerts connection status = all ok
xmlHttp.send(null);
}
catch(e)
{
alert(e.toString());
}
}
}
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
Any help at all would be greatly appreciated.
Cheers
The following code achieves the aim you've stated. Not sure what your problem is, since you've neglected to post a complete example.
phpVarTest.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function myAjaxGet(url, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
function onDocLoaded()
{
byId('testBtn').addEventListener('click', onTestBtnClicked, false);
}
function onTestBtnClicked(e)
{
var jsvar = 'some arbitrary text';
var url = 'phpVarTest.php?phpvar='+jsvar;
myAjaxGet(url, onAjaxDone);
}
function onAjaxDone(ajaxObj)
{
byId('outputDiv').innerText = ajaxObj.response;
}
</script>
<style>
</style>
</head>
<body>
<button id='testBtn'>Initiate ajax request</button>
<div id='outputDiv'></div>
</body>
</html>
phpVarTest.php
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
output
// server side script
<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>new phpvar value = some arbitrary text
Note: you should place the comment in the php file inside of the php tags - otherwise, you'll see it in the output, as shown above.
Related
I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key "data"' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function.
My code is:- This gets 'str' from the previous function and is formatted correctly.
function getGame(str){
//Sends data to the php process "saveGame.php".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
it then goes the the 'saveGame.php' where the problem occurs on line 2.
<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
I think my code of the process is okay but there is a problem with passing the "data" variable and I not sure what it is.
I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.
I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.
<!DOCTYPE html>
<head>
<title>Test program</title>
<script language="javascript">
function formatOutput() {
// lots of formatting goes on here
var formattedText = "This is a test"; //test data
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>
</body>
</html>
Hope this okay. I'm a bit new to this.
You are missing a post key
try changing this line to
var data = 'data='+str;
So i am trying to send a string into a php file using ajax but the http.send is not working, maybe something is wrong with the code? (i am just a beginner)
mainlink= 'a link';
id= 'an id';
$(document).click(function(){
var http = new XMLHttpRequest();
var link = mainlink+id;
http.open("POST", 'test.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function(){
if(this.status == 200) {
console.log (link);
}
}
http.send("link="+link);
});
test.php:
<?php
if (isset($_POST['link'])){
echo $_POST['link'];
} else{echo "error";}
?>
i tried both GET and POST.
This works. Are you sourcing in jQuery? Paste this tag inside the head tag of your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
It also seems probable that you want to console log this.responseText instead of link so you actually log what the server is responding rather than what you sent. Here is the exact code I used to get this working:
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var mainlink = 'a link';
var id = 'an id';
$(document).click(function(){
var http = new XMLHttpRequest();
var link = mainlink + id;
http.open("POST", 'test.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function(){
if (this.status == 200){
console.log(this.responseText);
}
}
http.send("link=" + link);
});
</script>
</head>
</html>
PHP:
<?php
if(isset($_POST['link'])){
echo $_POST['link'];
}
else{
echo "error";
}
?>
You can see it working live here. Is your pathname correct for test.php?
I need to get the IP of the client. I am able to get it through PHP variable
"$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined.
any solution?
PHP code:
<?php echo $_SERVER['REMOTE_ADDR'];?>
HTML CODE:
<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>
JavaScript code:
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ip.php");
xhttp.send();
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById("ip").value;
alert(ip);
}, 1000);
}
First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:
var ip = document.getElementById('ip').value;
You should use Node.textContent to get the text content:
var ip = document.getElementById('ip').textContent;
Code example (without AJAX request):
function ip() {
document.getElementById('ip').innerHTML = '127.0.0.1';
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById('ip').textContent;
console.log(ip);
}, 1000);
}
<body onload="ip(); ip2();">
<kbd id="ip" ></kbd>
You want your Ip Address in java script , so have to put ip address in that tag i think.
<?php $ip_address = $_SERVER['REMOTE_ADDR'];?>
<body onload='ip(); ip2();'>
<kbd id='ip' ><?php echo $ip_address; ?></kbd>
<?php echo $_SERVER['REMOTE_ADDR'];?>
<html>
<head>
</head>
<body onload='ip();'>
<div id='ip' ></div>
</body>
</html>
<script>
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
ip2(this.responseText);
}
};
xhttp.open("POST", "try.php");
xhttp.send();
}
function ip2(stringvalue) {
setTimeout(
function() {
var ip = document.getElementById("ip").value;
alert(stringvalue);
},2000);
}
</script>
run this code you might found what is the problem.
I started learning Ajax and I did this simple HTML page that displays a user input, when he types the name of a book (stored in an array in the php file), using ajax, the user can see below the input the results while he types, this is the part I couldn't manage to do, Here's the code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bookstore.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="process()">
<h1>
Hadhemi's BookStore !
</h1>
Enter the book you want to order
<input type="text" id="userInput">
<div id="underInput"> </div>
</body>
</html>
And this is the JS file
// 3 functions : create an object, communicate and response
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //check for IE
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest(); // ! IE
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Can't Create that object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
book = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","book.php?book=" + book,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
//sends back an xml file
if (xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML= message;
setTimeout('process()',1000);
}
else
{
alert("OOps! Something went wrong!");
}
}
}
And this is the PHP file :
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
echo'<response>';
$book = $_GET['book'];
$bookArray = array('Book1','Book2','Book3');
if(in_array($book, $bookArray))
echo 'We do have'.$book.'!';
elseif ($book='')
echo 'Enter a book name idiot!';
else
echo 'We dont have'.$book.'!';
echo'</response>';
?>
I can't manage to display what the JS file is supposed to do, anyone knows how to fix it?
EDIT: I placed all the files in the www folder under Wamp.
There are a few things wrong in what you posted.
Firstly, you have a typo in:
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
^ the "n"
Which should read as encoding.
Having errors set to be displayed on your server would have thrown you the following:
XML Parsing Error: XML declaration not well-formed Location: http://www.example.com/book.php?book.php?book= Line Number 1, Column 21:
Plus, do keep in mind that, and as I stated in comments that Book1 and book1 are not treated the same, therefore the array keys are considered as case-sensitive.
Consult the following answer on Stack:
https://stackoverflow.com/a/5404753/
You're also doing an assignment for while using a single equal sign:
elseif ($book='')
^
rather than a comparison, which should contain an additional equal sign:
elseif ($book=='')
^^
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.error-reporting.php
Plus, make sure that PHP is indeed installed, running and properly configured.
I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.