POST value from JavaScript to PHP via AJAX without jQuery - javascript

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();

Related

How can I get the substatus code of the exception with java script? like 500.1

I would like to read the substatus code of the exception like 500.1 on the client side. How to achieve this?
here is my code on the server side:
if(string.IsNullOrEmpty(userEmail)) {
Response.StatusCode = 500;
Response.SubStatusCode = 1;
Response.StatusDescription = "Email fehlt";
return;
}
Client side:
if (xhr.status == 500 && thrownError.indexOf("Email") > -1) {
alert('Email is missing...');
}
else {
alert('Error...');
}
On client side you can use the getAllResponseHeaders() method of XMLHttpRequest.
If a correct http header is really sent, it will read it.
Example:
var request = new XMLHttpRequest();
request.open("GET", "ajax.php", true);
request.send();
request.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(this.getAllResponseHeaders());
}
}
Output is separated by "\r\n".
If somehow the substatus cannot go through, maybe you can use another http header field for your goal, even if it is not according to the standards...

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

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);

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

Making a Javascript Loop request in rails view

I need to download a file from a link I am given. In order to do this I must make a get request to that link. It can have 3 states:
1. Code 200 and the download will begin once the request landed
2. Code 202 which means I must repeat the request because the file is being uploaded
3. Error code and I must create a dom element that shows that.
How it works:
I make a request to this rails action:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
#export = export_form.export
else
show_errors export_form.errors
end
end
This in turn starts the file upload. Which I don't know when it's ready(depending on how big the file it is). Now I must create a javascript get request to a link that follows the indications I have given at the beginning of the post. And integrate it in the by_month.html.erb view from rails . The javascript I managed to write is:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However I don't think it works. Any ideas of how I can do this?(redirect_to_main and make_error_css are functions that I will implement myself later).
Update As per the comments below
Can you try this,
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest() is where the request is made again if the status is 202.

My data posts to a new page rather than the specified div

Why does my post data appear on a new blank page rather than the div I specified? This script is in the head of a page called order.php. I want the data submitted to be written in the "message" div I created on order.php. But when I submit, I am redirected to update.php where the data is written on a blank page.
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XLMHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("message").innerHTML = xmlhttp.responseText;
}
}
parameters = 'child_name'+document.getElementById('child_name').value;
xmlhttp.open('POST', 'update.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
you current page is order.php and your posting it to update.php by doing this xmlhttp.open('POST', 'update.php', true);
This might be due to normal form submission event.
use a simple jquery
$("#form").submit(function(){
$.post("update.php",{paramertes:'child_name_'+$("#child_name").val()},function(data){
$("#message").html(data);
})
return false;//don't forget to use this
})

Categories