Passing CallbackFunction as Parameter for Ajax-Request - php

I want to get content for my website asynchronously. Now that I have more than one requests for my server I thought it would be great to seperate the "conntection Stuff" into another function:
function conToServerAsync( url, postParams, func )
{
var xmlHttp;
if( window.XMLHttpRequest )
{
xmlHttp = new XMLHttpRequest();
}
else
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = func;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postParams);
}
Now I have this other function which is executing the "conToServerAsync" function like this:
function findSearchResult(value)
{
conToServerAsync( "Classes/Async/liveSearch.php", "sVal="+value, function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
document.getElementById("searchResult").innerHTML = xmlHttp.responseText;
document.getElementById("searchResult").style.border="1px solid #A5ACB2";
}
});
}
Now whats actually interesting about my case is that I've checked everything and every parameter that is passed in is valid. Then I tried to allocate the function that is given in the last parameter "conToServerAsync( "Classes...", "sVal..", function(){...}" directly to the onreadystatechange:
...
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
document.getElementById("searchResult").innerHTML = xmlHttp.responseText;
document.getElementById("searchResult").style.border="1px solid #A5ACB2";
}
}
... and it works perfectly :S So definitly the error is about passing the function on a wrong way and I have no idea. Cos my case is that specific I made a own question about it.
Thank you for answering :)

You're trying to use xmlHttp from the callback, but it's out of scope. I suggest the following approach:
function conToServerAsync( url, postParams, func )
{
var xmlHttp;
if( window.XMLHttpRequest )
{
xmlHttp = new XMLHttpRequest();
}
else
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
func.call(xmlHttp, xmlHttp);
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postParams);
}
function findSearchResult(value)
{
conToServerAsync( "Classes/Async/liveSearch.php", "sVal="+value, function(xhr)
{
document.getElementById("searchResult").innerHTML = xhr.responseText;
document.getElementById("searchResult").style.border="1px solid #A5ACB2";
});
}

On my implementation of the XMLHttp wrapper I use the Function.prototype.call to call the callback function from the XMLHttp Object scope, So you can use the keyword this to access properties and I also pass the responseText as a parameter for convenience.
if(typeof func=="function")
func.call(xmlHttp, xmlHttp.responseText);
You can easily print the response on the callback
function callback(response){
alert(response);
}
But you can still have access to all properties of the XMLHttp Object
function callback(response){
alert(this.status); //200
alert(response);
}
Full code:
function conToServerAsync( url, postParams, func ){
var xmlHttp;
if( window.XMLHttpRequest ){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 && xmlHttp.status==200){
if(typeof func=="function")
func.call(xmlHttp, xmlHttp.responseText);
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postParams);
}
function findSearchResult(value){
conToServerAsync( "Classes/Async/liveSearch.php", "sVal="+value, function(response){
document.getElementById("searchResult").innerHTML = response;
document.getElementById("searchResult").style.border="1px solid #A5ACB2";
});
}

Since the function you passed to xmlHttp.onreadystatechange is called with xmlHttp as the context you can use this to refer to that object.
function findSearchResult(value)
{
conToServerAsync( "Classes/Async/liveSearch.php", "sVal="+value, function()
{
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("searchResult").innerHTML = this.responseText;
document.getElementById("searchResult").style.border="1px solid #A5ACB2";
}
});
}

Related

How could I send the information in AJAX at POST?

Sorry for my english...
How could I send the information that's in Ajax with POST? (info, info_1, info_2)
Now, I'm sending it with GET
edit: i try to do what people here said me to do, but when i call the POST variable in the page that i send for him the info, its show me eror... why?
the new code:
var xhr = new XMLHttpRequest();
xhr.open("POST",url,true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
document.getElementById(name).innerHTML = this.responseText;
}
};
xhr.send("info="+str+"&info_1="+info_1+"&info_2="+info_2);
return false;
the first code:
var xhr = new XMLHttpRequest();
xhr.open("GET",url+"?info="+str+"&info_1="+info_1+"&info_2="+info_2,true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
document.getElementById(name).innerHTML = this.responseText;
}
};
xhr.send();
return false;
Change "GET" to "POST" and put the data (in the same form as in the query string, but without the ? prefix) as the argument to the send() method instead of in the URL.
I used this code. It worked
function getXMLHttpRequestObject()
{
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function callme1(){
var http = new getXMLHttpRequestObject();
var url = "yourpage.php";
var reply;
var conf=true;
var parameters = "info="+str+"&info_1="+info_1+"&info_2="+info_2;
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", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
}
Just call function callme1() and it will post the request to yourpage.php
This is how to send Post request in ajax
var str="hrl";// initialize str
var info_1="hi"; // initialize info_1
var info_2="hi"; // initialize info_2
var url="index.jsp"; // initialize url
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST",url,true);// initialize url
xmlhttp.send("info="+ str +"&info_1="+ info_1 +"&info_2="+info_2+"");

auto update data from AJAX posting form

I am using an AJAX script to post data from a form and return the processed data from a php file. The script is below.
function loadXmlDoc(hashtag){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("hashtag=" + hashtag);
}
However I want to auto update the results. how would I get this to auto update so it checks for more data? Or what would be the best way?
There seems to be nothing about getting AJAX forms to auto refresh from what I've seen so any help would be greatly apprecaited
Try this way. It should auto-update the result every 10 seconds.
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
function loadXmlDoc(hashtag){
var repeat = function () {
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("hashtag=" + hashtag);
};
repeat.hashtag = hashtag;
setInterval(function() { repeat(); },10000);
}

AJAX Not Responding

So I'm trying to just alert out my "Hello" from my php file, it's pretty straight forward but it's not working for some reason.
JS
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "hello.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
dynamic();
PHP
<?php
echo "Hello";
?>
HTML
<html>
<head>
<title>Hello</title>
<script src="dynamic.js"></script>
</head>
<body>
test
</body>
</html>
I can't get the alert box to alert my "Hello". It should just come straight from responseText.
You didn't invoke send method. It sends the request MDN
xmlhttp.send();
If you want to put any data in POST put it in send methods parameter as urlencoded form.
xmlhttp.send("foo=bar&hello=world");
try this:
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "hello.php", true);
xmlhttp.send(null);
}
dynamic();
I think you forgot to send the request:
xmlhttp.send();
try this
xmlhttp.setRequestHeader("Content-type", "text/plain");
or
xmlhttp.setRequestHeader("Content-type", "text/html");
instead of
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
and you have to put
xmlhttp.send(null);
beside the answer, logging in php file is a useful behaviour in similar situations.

Ajax Call Sometimes Works, Sometime works and refreshes, Sometimes refreshes and fails …?

Currently I got this code:
function post_positive(id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("post"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","post_review.php?id="+id+"&type=positive",true);
xmlhttp.send();
return false;
}
For my ajax call I just the function post_positive(). Sometimes it shows the result, sometimes with page refresh, sometimes nothing.
You use jQuery ajax() method for ajax it is easy to understand and working properly
function post_positive(id){
$.ajax({
type:'get',
url:'post_review.php',
data:{ 'id':id,'type':'positive' },
success:function(result){
$("#post"+id).text(result);
}
});
}

AJAX: sending xmlhttp requests in a loop

I have this function below and I call that function in a loop I get the alert n times but only n-1 or sometimes n-2 responses
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
//document.getElementById("warnings_panel").innerHTML+=xmlhttp.responseText;
}
}
alert("in ajax)
xmlhttp.open("GET","getresponse.php?start="+ start + "&end=" + end,true);
xmlhttp.send();
I have made a class (that you can modify easily) for calling a function in loop and it calls the functions correctly. Maybe this could apply to your need.
(Also if anyone sees something wrong it's good to hear from others)
test.htm
<html>
<head>
<script type="text/javascript">
function myXmlHttp() {
/*constructor simulator*/
this.setPersitent=
function (file, onReadyFunc,params,loop)
{
myXmlHttpObj.loop = loop;
myXmlHttpObj.file=file;
myXmlHttpObj.onReadyFunc='myXmlHttpObj.'+onReadyFunc;
myXmlHttpObj.params=params;
myXmlHttpObj.mySetRequest();
}
this.setParams=
function ( params )
{
myXmlHttpObj.params=params;
}
<!--Standard initial code-->
this.mySetRequest =
function ()
{
request = false;
try { request = new XMLHttpRequest(); }
catch (trymicrosoft) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (othermicrosoft) {
try {request = new ActiveXObject("Microsoft.XMLHTTP");}
catch (failed) {request = false;}/*catch3*/}/*catch2*/}/*catch1*/
if (!request)
alert("Error initializing XMLHttpRequest!");
} /*func*/
this.mySendReq=
function()
{
var url = myXmlHttpObj.file;
request.open("POST", url, true);
//Some http headers must be set along with any POST request.
request.setRequestHeader
("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", myXmlHttpObj.params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = eval(myXmlHttpObj.onReadyFunc);
request.send(myXmlHttpObj.params);
}
this.listenPHP =
function ( ) {
if ( request.readyState == 4) {
if ( request.status == 200)
{
alert(request.responseText);
myXmlHttpObj.loop--;
if(myXmlHttpObj.loop>0)
{
myXmlHttpObj.setParams("js_rand="+Math.random()+"");
myXmlHttpObj.mySendReq();
}
}//inner if
else{alert("status is " + request.status);}
}//outer iff
}//function
}//END
myXmlHttpObj = new myXmlHttp();
myXmlHttpObj.setPersitent
('getresponse.php', 'listenPHP',"js_rand="+Math.random()+"",3) ;
myXmlHttpObj.mySendReq();
</script>
</head>
<body >
</body>
</html>
and getresponse.php
<?PHP
echo 'I recived this random from js:',$_POST['js_rand'],'
this rand is from php:',rand(1,9999);
?>
onreadystatechange gets terminated when your function ends because the xmlhttp object gets removed as it is not a global variable. Am I right?
Better would be to put only the AJAX request in a function, so that the xmlhttp object is only created once (I used a shorter version to create the xmlhttp object in this example).
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function request() {
xmlhttp.open('GET', 'getresponse.php?start=' + start + '&end=' + end, true);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
}
Generally, this should work, but we need more information about how you actually run that loop to know what might be wrong.
I also added encodeURIComponent and changed the condition inside the callback function, because status isn't always 200 when readyState reaches 4.
function request(start, end) {
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open('GET', 'getresponse.php?start=' + encodeURIComponent(start) + '&end=' + encodeURIComponent(end), true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4)
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else {
// status ≠ 200, output useful error message
}
};
xmlhttp.send();
}

Categories