AJAX: POSTed value arriving in $_GET - php

I have the following JavaScript code in the header of my page; note that I use POST:
function sendInput() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://.../somefile.php?someInput=123', true);
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
alert('ready: ' + xmlhttp.responseText);
}
}
};
xmlhttp.send();
}
I call the function in body onload:
<body onload="sendInput();">
In the PHP file $_POST is empty. The value for someInput is found in $_GET.
Shouldn't an AJAX request done with POST arrive in $_POST?

When you are using the url to form your variables is GET. In order to send via post you need to change your code like this:
function sendInput() {
var params = "someInput=123";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://.../lsomefile.php', true);
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
alert('ready: ' + xmlhttp.responseText);
}
}
};
xmlhttp.send(params);
}

Yes, You couldn't get any values in $_POST. because no values posted by you. Please refer the below for posting data to particular URL
Send POST data using XMLHttpRequest

Related

How to go back to a function in jquery

I have some buttons when a user click one of them they update the content of the page through ajax then the buttons are hidden and some new buttons are available for user. The problem is when i hit the back button it doesn't go back to the previous function. I want the user to go back to the previous set of buttons here is my code :
$(".buttonset1").click(function() {
$('#div1').css("display","none");
id = $(this).attr("value");
query = 'ajax.php?id='+id;
myQuery(query);
$('#div2').css("display","block");
});
$(".buttonset2").click(function() {
$('#div2').css("display","none");
value = $(this).attr("value");
query = 'ajax.php?id='+id+'&var1='value;
myQuery(query);
$('#div3').css("display","block");
});
Now div2 is shown to the user.... myQuery function does the ajax query
function myQuery(url) {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("sql").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', url, true);
xmlHttp.send();
}
Solved it was pretty simple
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
var url = State.url;
myQuery(url);
});

Synchronous request with ajax in a loop

I have a for loop which contains ajax request. The request is working aynchronously. So i can't reach the result of request in time. How can i solve this problem without using any library?
Thanks.
var availables = document.getElementsByClassName("available");
for(var i=0;i<availables.length;i++){
var element = availables[i];
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest;
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "control.php?user=" + element.innerText, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
element.setAttribute("class" , "result available " + result);
if(result == "online")
element.innerHTML = "" + element.innerText + "";
}
}
}
First of all, I'd suggest putting your xmlhttp.onreadystatechange function before you do xmlhttp.open and xmlhttp.send. It's possible that it's sending and returning and since it's running asynchronously, it's getting back before you're onreadystatechange function can be defined/executed. Something like that.
Anyway, you can always do it all synchronously by setting the last argument in xmlhttp.open to false. This will make javascript wait after xmlhttp.send before continuing, but either way you'll still need to put onreadystatechange before open and send.
var availables = document.getElementsByClassName("available");
for(var i=0;i<availables.length;i++){
var element = availables[i];
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest;
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
element.setAttribute("class" , "result available " + result);
if(result == "online")
element.innerHTML = "" + element.innerText + "";
}
}
xmlhttp.open("GET", "control.php?user=" + element.innerText, true);
//xmlhttp.open("GET", "control.php?user=" + element.innerText, false); //If you want to do it synchronously
xmlhttp.send();
}
It is very bad practice to make your ajax calls synchronously xmlhttp.open("GET", "control.php?user=" + element.innerText, true) because you cannot interact with your application until an ajax request ends. I think in your case it is better to send every next request in the onreadystatechange callback of the previous one.

Trying to Retrieve values from PHP using AJAX

This is what I am trying. I am trying to call a function trial with retrieves a value from a PHP for values 1 to 29 and display the result in text input boxes named T1, T2...T29.
function calculate() {
for (var i = 1; i < 30; i++) {
trial(i);
}
}
function trial(i) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('T' + i).value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "MANAGER/manager.php?rownum=" + i, true);
xmlhttp.send();
return;
}
It is not working. Could you please suggest a solution?
The issue is that you are declaring the variable xmlhttp globally, so you are overwriting the callbacks and everything on each iteration. Use the var keyword to make it local.

AJAX transfer large amount of data using $_POST method

I would like to transfer a large amount of text to the server using AJAX. I would like to attach this text using the POST method, but I get the following error:
request failed: URI too long (longer than 8190)
My javascript code:
function loadXMLDoc(data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://www.mydomain.com/test2.php?blob=" + data, true);
xmlhttp.send();
}
My php code:
$dataraw = $_GET["blob"];
file_put_contents('/path/to/my/file/newfile.txt', $dataraw);
echo 'file saved';
You should change this
xmlhttp.open("POST","http://www.mydomain.com/test2.php?blob=" + data,true);
xmlhttp.send();
to this:
xmlhttp.open("POST", "http://www.mydomain.com/test2.php", true);
var payload = "blob=" + data;
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.setRequestHeader("Content-length", payload.length);
xmlhttp.send(payload);
In POST, parameters should go in the body of the message, not the URL.
At the same time, you should expect the parameters on the server-side in $_POST - that's where the body parameter will end up in in PHP.
You don't add post-data to the URL. Please check this link to find an example of a post-request:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

how can i use returned values from javascript functions in php?

<script type="text/javascript">
function mehdi(rno)
{
alert(rno);
return rno * 10;
}
</script>
<input type="button" name ="submit" value="ثبت و تایید" onclick= " mehdi('10')">
<?php
?>
how can i use from returned value from mehdi() function?
In this case you can't since PHP is used only to render HTML.
You will have to use AJAX (AHAH) for it:
http://en.wikipedia.org/wiki/Ajax_%28programming%29
You can't! Javascript runs on the browser, after your PHP script has finished executing.
You can't PHP is processed first and then page executes javascript.
you can send Ajax request thought to your PHP scripts.
You can't do it directly. You have to use AJAX.
Once code comes to client side and it executes there, your server side script would have terminated already.
If you do need to send JavaScript return values, pass them back to server using AJAX.
you could do an ajax request within the medi function and the request could sent it via post to an file like "mehdi_js_result.php" :)
var ajaxify = function(obj) {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
xmlHttp = null;
}
}
}if (xmlHttp) {
obj.method = obj.method.toUpperCase();
xmlHttp.open(obj.method, obj.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(obj.method == 'POST') {
if(typeof(obj.params) != 'undefined') {
xmlHttp.setRequestHeader("Content-length", obj.params.length);
}
}
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
var json = eval(xmlHttp.responseText);
if(json.success) {
if(typeof(obj.success) == 'function'){obj.success(xmlHttp.responseText);}
}
else {
if(typeof(obj.failure) == 'function') {obj.failure(xmlHttp.responseText);}
}
}
};
if(obj.method == 'POST' && typeof(obj.params) != 'undefined') {
xmlHttp.send(obj.params);
}
else {
xmlHttp.send(null);
}
}
};
function ajax(mehdi_result) {
ajaxify({
method: 'POST',
url: 'mehdi_js_result.php',
params: 'result='+result,
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
failure: function(response) {
var json = eval(response);
alert('failure callback function! '+json.data);
}
});
}

Categories