Just beginner in php, I want to call php method using AJAX. I tried every thing but don't know what error is. Not getting any response from object xmlhttp.
Heres my java script code :
function loadData(){
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0) {
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
}
}
My js file is on "projectname/javascript/script.js" and my php file is in "projectname/code/GetItemsInDD.class.php" dir.
Why don't you use jQuery for making AJAX requests? Its as simple as this, include jQuery in your page
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
and JS code,
$.ajax({
type: 'GET',
url: '../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method',
success: function (data) {
document.getElementById("ddItems").innerHTML = data;
}
});
This way, you don't need to check for the readyState and status thing
jQuery follows object oriented approach for declaring XMLHttpRequest objects, so you won't have to worry about creating multiple objects for making more than one AJAX requests.
function loadData(){
var xmlhttp;
var mID=ddItems;
var method=2;
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("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true);
xmlhttp.send();
}
I have made 2 desired changes to your code, try running it now. Make sure the URL is correct.
function loadData()
{
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else //For some versions of IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.send();
}
}
Change 1 : You may be running the code in an older version of IE, where ActiveXObject is used.
Change 2 : The open() method should not be called if the readyState changes ( as you have written it within the IF block), readyState changes only after the ajax call is initialized by the open() method and then send by the send() method.
Related
I need to pass some data over GET URL which is not in form, is there any way to include non-form data into GET method?
http://localhost/land1/index.php?visitorName=&visitorPhone=&submit=Submit
which is ok for form elements like visitorName and visitorPhone, but i need to pass some other info also with this, like some fixed non-form data.
And i have to use only html, in form submitting page, no php.., target is php.
You can use input type=hidden for this purpose.
For e.g.
<input type="hidden" name="fixedData" value="some data" />
Use Ajax in this case-
<script type="text/javascript">
function loadXMLDoc() {
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 == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "/myUrl?<[parameters]>", true);
xmlhttp.send();
}
</script>
You can add form as well as non-form parameters here -
xmlhttp.open("GET", "/myUrl?<[parameters]>", true);
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+"");
Hi everybody!
I have a problem and I have no idea how to fix it!
I have a simple HTML page with a button:
<input type = "submit" value = "ok" onclick="f1()"/>
I also have a script on this page:
<script>
function f2()
{
var firstBtn = document.createElement("button");
firstBtn.appendChild(document.createTextNode("firstBtn"));
document.body.appendChild(firstBtn);
var xmlhttp = CreateRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseText;
document.body.innerHTML += response;
}
}
firstBtn.onclick = function()
{
alert("inside f2 onclick");
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
}
function f3()
{
var secondBtn = document.createElement("button");
secondBtn.appendChild(document.createTextNode("secondBtn"));
document.body.appendChild(secondBtn);
var xmlhttp = CreateRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = xmlhttp.responseText;
document.body.innerHTML += response;
}
}
secondBtn.onclick = function()
{
alert("inside f3 onclick");
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
}
function f1()
{
f2();
f3();
}
function CreateRequest()
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// code for IE6, IE5
return xmlhttp;
}
</script>
So now, when I click one of the buttons (firstBtn or secondBtn), another one is not responding to the click event! Does anybody know why?
As #vishwanath said (see comments to this question), when I doing
document.body.innerHTML += response;
I'm destroying and recreating all the content of my page therefore I'm losing my events.
I'm trying to find the answer somewhere around but i can't,
So i'm having a .bind() event and I want when's triggered to make a get query from a php file with JSON like AJAX does.
I have tried the following which doesn't work:
$(document).ready(function() {
$("#adivhere").bind("valuesChanged", function(){
// Some variables here
var max2 = 10
var min2 = 5
//The classic AJAX Request
function afunc(max2,min2){
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");}
//The classic AJAX onreadystatechange function
xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200){
//The code triggered
var fets = jQuery.parseJSON( xmlhttp.responseText );
var t = fets.date.split(/[-]/);
var d = new Date(t[0], t[1], t[2]);
alert(d);
}}
//The XHR request with the .php file and the
// two values that sends
xmlhttp.open("GET","getdates.php?max2="+max2+"&min2="+min2,true);
xmlhttp.send();
};
});
It looks like you're using jQuery, so this should work:
$(function(){
$('#adivhere').bind('valuesChanged',function(){
var max2 = 10;
var min2 = 5;
$.getJSON('getdates.php?callback=?', {max2: max2, min2: min2}, function(json){
alert(json);
var t = json.date.split(/[-]/);
if (t && t.length) {
var d = new Date(t[0], t[1], t[2]);
alert(d);
}
});
});
});
There's already an awesome $.getJSON method in jQuery that will do all of the heavy lifting for you, including return your results as JSON.
You'll need to make your getdates.php script echo the callback and wrap your results in parentheses so it returns as actual jQuery.
There are several "errors" in your script:
"afunc" is never called, so why should it be executed?
the parenthesis are not closed properly; at the end there are two missing: )}
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();
}