I honesty did every possible search, watched lots of tutorials, but still cant make it work. The mistake is somewhere in connetion between javascript and php. The strange point is that connection is successfull and script works if I click the submit button when the page is in a process of reloading.
Please, help.
I call two variables, $l1 and $l2 from the php require-once which do some work on the page, then I use them in Java script to send to PHPfile onclick of submit button;
Button:
<input class ="button vote" type = "submit" onClick= "javascript: somefunction();" value = "do it" />
Function:
function somefunction(){
var hr = new XMLHttpRequest();
var url = "index.php";
var wn = "<?php echo $l1 ?>";
var ls = "<?php echo $l2 ?>";
var vars = "wn="+wn+"&ls="+ls;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
php acceptor on the same page:
<?php if (isset ($_POST ["wn"])){
$wnn = $_POST['wn'];
$lss = $_POST['ls'];...
try this:
var wn = document.getElementById("wn").value;
var ls = document.getElementById("ls").value;
I presume you ar calculating these either diectly, or from a $_SESSION variable perhaps? When you view the source on the completed page check if the variables are present, perhaps just after you assigne the variables within php.
<?PHP
if (isset($l1) && !empty($l1)) {
echo "L1 is $l1";
} else {
echo "L1 wasnt set";
}
?>
then make sure the value up top matches that you're seeing in your javascript
Related
I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
I am learning ajax and I have followed a tutorial to post some data to a text file via a php script but I can't get it to work. Is there something I have missed.
the following is the ajax.html page which is a input text with a button to post the data via ajax
<form name="testform">
Off Min:<input name="setOffMin" type="text" id="setOffMin" maxlength="2" size="1"/></br>
<button type="button" onclick="postStuff();">Submit</button>
</form>
<div id="status"></div>
<script type="text/javascript">
function postStuff(){
var hr = new XMLHttpRequest();
var url = "update.php";
var offM = document.getElementById("setOffMin").value;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(offM);
document.getElementById("status").innerHTML = "processing...";
}
</script>
this is the update.php file
<?php
$setOffMin = $_POST["offM"];
$f = fopen("test.txt", "w");
fwrite($f, $setOffMin);
fclose($f);
?>
I have been looking over this code all last night and cannot work out why it is not writing the data to the text file.
I have run the php script editing out the $_POST and putting in a variable and it does write to the text file. So the php should work and the text file permission is correct. I expect this is the ajax that I have done wrong.
any help will be great
You need to send offM as urlencoded like this:
var offM = 'offM='+document.getElementById("setOffMin").value;
Now when you click on Submit you call update.php?offM=YourText and PHP recieve var $_POST['offM'] with value YourText
Let say I submit data to a form with the following code
var xhr = new XMLHttpRequest(), formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage["username"]);
formData.append("pass", localStorage["password"]);
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
var value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}else{
alert("none");
}
};
xhr.open("POST", "http://joubin.me/uploads3/upload_file.php", true);
xhr.send(formData);
After upload.php is done, it redirects to another page called giveid.php and the only thing it displays is a text string with an id
say 1234
How can I with javascript capture this exact id.
Keep in mind, a different upload.php redirect will have a different id number on giveid.php?
I looked into the xmlhtml responses and could not figure it out.
Here is what form goes
$password = $_REQUEST['pass'];
$username = $_REQUEST['user'];
$image = $_REQUEST['img'];
echo $password;
echo "<br/>";
echo $username;
echo "<br/>";
echo $image;
$con = mysql_connect("localhost","ya","right");
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "could not connect";
}
$asql = "SELECT * FROM `ashkan`.`users` where user='$username' and pass='$password';";
$result = mysql_query($asql);
echo $result;
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
echo $count;
echo 11;
if($count == 1){
$sql = "INSERT INTO `ashkan`.`goog` (`user`, `pass`, `img`) VALUES ('$username', '$passwo$
}
mysql_query($sql);
mysql_close($con);
header( 'Location: giveid.php' ) ;
and here is the content of giveid.php
1234
Any help would be great.
Thanks
You need to use xhr.onreadystatechange to retrieve the response from the server.
Something like this might work.
var value;
var formData = new FormData();
formData.append("img", img);
formData.append("user", localStorage.username);
formData.append("pass", localStorage.password);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) {
value = xhr.responseText; // value should equal "1234"
alert( "value = " + value );
}
};
xhr.open("POST", "upload.php", true);
xhr.send(formData);
Info Here: http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Remember that header() must be called before any actual output is sent. So get rid of all the echos you have in the php file. Once you echo then that starts the output buffer for the response to the client.
Info Here: http://php.net/manual/pt_BR/function.header.php
I think this should be your only echo on the php page.
echo include( 'giveid.php');
Try using Google Chrome Dev Tool Network tab to view the response from your php webpage.
Launch Google Chrome,
Hit f12,
Click the network tab,
reload your page,
click on the ajax response page,
click preview to view the response.
Info Here: https://developers.google.com/chrome-developer-tools/docs/network
xhr documentation
Get xhr.response then parse it.
We usually return a json string so js can parse it easily.
googled xhr example
something like this:
xhr.onreadystatechange=function()
{
if (xhr.readyState!=4 || xhr.status!=200)
return;
var resp = xhr.responseText;
var parsed = eval(resp);
}
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>
I have a simple setup to allow a user to change his content on a page.
It calls up a query and populates the area with the results. My goal is to have the user enter in some new information, insert that info into the table, and requery the results.
Here is my Javascript function that is called:
function addLink(){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
}
}
Those PHP functions merely spit out the HTML, the displayContent() specifically for the actual table data.
Here is my HTML for adding some info to the database:
<center><br /><br />
Image URL: <input type='text' id='links_img' />
Link URL: <input type='text' id='links_link' />
<input type='button' onclick='addLink()' value='add' /></center>
Here is my PHP for adding the information:
<?php
mysql_connect([sensitive information]) or die(mysql_error());
mysql_select_db([sensitive information]) or die(mysql_error());
$result = mysql_query("INSERT INTO linksMod (Image URL, Link URL) VALUES ("$_GET['imgURL']","$_GET['linkURL']") or die(mysql_error());
mysql_close();
?>
Thee page does nothing when I click the 'Add' button.
Thanks for your help!
These lines:
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
need to be outside the "readystatechange" handler function. The way it's written now, they're inside the handler function and, since it isn't called, they'll never happen.
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
I don't think it's possible to embed php in javascript .