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?
Related
I'm new to ajax, I am trying to send the html page data to php without reloading the current page. When I click on submit button it just blink "processing..."
html file
<!DOCTYPE html>
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
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);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>`
Php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Edit 1
I added alert message in onreadystatechange. It showing three alert messages 2,3,4 respectively.
alert(hr.readyState);
There are multiple things i can see:
</script> a closing of the script which doesn't have any opening tag in the head.
The variable vars doesn't create a query string as it is missing a ?.
So, the complete changes would be:
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "?firstname="+fn+"&lastname="+ln;
//----------^---put this at start.
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);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
Or you can send it as:
hr.send({ firstname:fn, lastname:ln });
this is my javascript of first page
<script>
function MessageDetailsById(id)
{
$("#active"+id).css({"color":"red"});
var http = new XMLHttpRequest();
var url = "Ajax.php";
var adm = "<?php echo $admno; ?>";
var params = "Id="+id;"adm="+adm;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(params);
window.location.href="#";
}
</script>
this is the coding of ajax.php
<?php
include("model.php");
$DB=new database;
if(isset($_POST["Id"]))
{
$DB->updateMassageTitleStauts($_POST["Id"],$_POST["adm"]);
}
else
{
header("Location:index.php?ajaxmas=wHgfghks^^%&fnjfskjdfb");
}
?>
i want to send one variable of php and another is id of a div... how to send two parameters and recieves them on other side ??? please correct this code in details i am not expert ???
For the post data encoding:
var params = "Id=" + id + "&adm=" + adm;
Use & for separator.
Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax
I am developing a slider to set my budget and would like to achieve the value which I set in slider1.php. However, when I tried using the code below, I encountered an error
"Notice: Undefined index: slideStatus in C:\xampp\htdocs\1204763e\slider1\slider1.php on line 4
Thank you , says the PHP file"
In slide.php, I inserted this set of code:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(val){
var hr = new XMLHttpRequest();
var url = "slider1.php";
var ss = document.getElementById('sliderStatus').innerHTML = val;
var vars = "sliderStatus="+ss;
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;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="range" name="slide" min="0" max="100" value="50" step="2" onChange="ajax_post(this.value)" />
<br /><br />
<span id="sliderStatus">50</span>
<br/><br/>
<div id="status"></div>
</body>
</html>
In slider1.php, I inserted this set of code:
<?php
echo 'Thank you '. $_GET['slideStatus'] . ', says the PHP file';
?>
You seem to try to access "slideStatus" but you are posting "sliderStatus".
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.