How can I pass data from client to server use raw AJAX? - javascript

Hello I have already search but they often use jquery ajax to pass data from js to PHP(server-side). but for my project it has a bunch of pure js code so I should use raw AJAX to pass data.
For example, if I want to send a variable "Imgname" that value = 13 and want to echo in php page.
this is my try
<script>
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert('send to server successfully');
}
};
xmlhttp.open("POST", "test2.php", true);
xmlhttp.send("Imgname=13");
}
</script>
in test2.php
<?php
$temp = $_POST['Imgname'];
echo $temp; /////output should be 13
?>
but error Undefined index: Imgname in C:\xampp\htdocs\test2.php on line 2

You need to make sure that you're sending the correct content-type:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Try sending the header:
var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);

Related

How to pass datepicker value to php without reloading the page using XMLHttpRequest();

How to pass datepicker value to PHP without reloading the HTML page using XMLHttpRequest();
I am using this date value for further query and displaying in the same html page.
<input type="date" id="month" onchange="myFunction(this.value)">
<script>
function myFunction(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("month").value = this.responseText;
}
};
xmlhttp.open("POST", "chart.php", true);
xmlhttp.send("value=" + str);
}
</script>
<?php
$date = "";
if(isset($_POST["value"])){
$date = $_POST["value"];
}
?>
I believe the function parameter str is giving you the date value you selected if yes, then you are missing the header information for content-type. Please set it as follow after xmlhttp.open("POST", "chart.php" , true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

XMLHttpRequest appending payload to the uri

I'm making a simple POST XMLHttpRequest, it is successfully posting the data but also the paylod getting appended to the URL. Is there anyway the data doesnt appended to the URL
var payLoad= JSON.stringify(ItemJSON);
var xmlhttp = new XMLHttpRequest();
xmlhttp.addEventListener("readystatechange", function () {
if (xmlhttp.readyState < 4){
}
else if (xmlhttp.readyState === 4) {
if (xmlhttp.status == 200 && xmlhttp.status < 300){
console.log("Success",xmlhttp.responseText);
}
}else{
alert("Error!! \\n There was an error while saving. Please retry again later.");
}
});
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(payLoad);
}
Response :
https://sample.com/api/apipipelines?apiName=asdasdaaaaaa&orgUnit=ASA&apiProductName=asdasd&leadDeveloperName=Sandeep&leadDeveloperEmail=sa11as1%40sandsssy.com&baseUrl=%2Fapplication%2Foip%2Fv1%2Fcase-management%2F&projectOwnerName=alisa&projectOwnerEmail=sa%40sasssssndy.com
It is because the header that you used while posting the content:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Change it to
xmlhttp.setRequestHeader("Content-Type", "application/json");
Reference for you: What is the difference between form-data, x-www-form-urlencoded and raw in the Postman Chrome application?

POST value from JavaScript to PHP via AJAX without jQuery

I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.
I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.
JS (from index.html) :
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP (from test.php) :
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.
What am I doing wrong ?
There are few things wrong in your code, such as:
Even through you defined send_ajax() function, you didn't call it anywhere in the code.
With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:
request.send("name="+valueToSend);
So the complete JavaScript code would be like this:
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("name="+valueToSend);
}
}
send_ajax();

pass two different variables in javascript?

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.

XMLHttpRequest no return value

i am unable to receive a response from the php file.
Javascript
var http = new XMLHttpRequest();
var url = "http://localhost/php_bollywood_romance.php";
var params = "film="+movie_name_entered;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
I have even tried to do this.....
var http = new XMLHttpRequest();
if ("withCredentials" in http)
{
var url = "http://localhost/php_bollywood_romance.php";
var movie_name_entered="hi";
var params = "film="+movie_name_entered;
http.open("POST", url, true);
}
else if (typeof XDomainRequest != "undefined"){
http = new XDomainRequest();
var url = "http://localhost/php_bollywood_romance.php";
var movie_name_entered="hi";
var params = "film="+movie_name_entered;
http.open("POST", url);
} else {
http = null;
}
if (http){
http.onload = function(){
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
document.write(http.responseText);
callback(http.responseText);
alert("hey");
}
}
http.send(params);
};
PHP
<?php
{
$name = $_POST["film"];
$file ='data_bollywood_romance.txt';
$current=file_get_contents($file); //gets existing content from the file
$current ="$current \n $name \n";
file_put_contents($file,$current); //put newstuff
echo 'hi';
return 'yes';
}
?>
However this also does not seem to work... if i do alert("http.response") after http.send(params)...it alerts an alert with nothing written on it. I thought this might be because there is same origin policy problem so i tried to do Cross-domain Ajax with Cross-Origin Resource Sharing but that didnt work either( that is the second code). Thanks for your help in advance.
You cannot set this two headers:
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
Previous thread about your problem
I tried it without and worked fine.
Personally i would go all the way using jQuery Ajax, but thats just "lazy me" :)

Categories