AJAX - PHP update of multiple divs - php

Good morning everyone, i have this code, took from w3schools
var xmlhttp
function showCustomer(str,str2)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="/Script/ajaxdb/aaaaa.php";
url=url+"?id="+str;
url=url+"&id2="+str2;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4) {
document.getElementById("TXTHINT").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I would like to change the name of the ID into
document.getElementById("TXTHINT").innerHTML=xmlhttp.responseText;
I would like to have something like
document.getElementById("TXTHINT1").innerHTML=xmlhttp.responseText;
document.getElementById("TXTHINT2").innerHTML=xmlhttp.responseText;
document.getElementById("TXTHINT3").innerHTML=xmlhttp.responseText;
and so on..
i tried
document.getElementById("TXTHINT"+str).innerHTML=xmlhttp.responseText;
cause i need the value of the variable str, to have the id name as TXTHINT1, TXTHINT2, TXTHINT3 and so on....
but id doesn't work.
Can someone help me ?

I would prefer to set a class attribut for all elements you want to change.
For example:
<div id="TXTHINT" class="txthints"></div>
<div id="TXTHINT1" class="txthints"></div>
Now you could easily iterate through all elements with class atrribut "txthints" and set the content.
var divsToChange = document.getElementsByClassName('txthints');
var newContent = xmlhttp.responseText;
for(i=0; i < divsToChange.length; ++i ) {
divsToChange[i].innerHTML = newContent;
}

You Should specify a global var to access it in other functions.
var xmlhttp
var str_global;
function showCustomer(str,str2)
{
str_global=str;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="/Script/ajaxdb/aaaaa.php";
url=url+"?id="+str;
url=url+"&id2="+str2;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4) {
document.getElementById("TXTHINT"+str_global).innerHTML=xmlhttp.responseText;
}
}

Try this
xmlHttp.onreadystatechange=function () {
stageChanged(str, str2);
};
xmlHttp.open("GET", handlingURL, true);
xmlHttp.send(null); }
function stageChanged(str, str2) {
if(xmlHttp.readyState==4)
{
document.getElementById("TXTHINT"+str).innerHTML=xmlhttp.responseText;
//do something with the response
} }
STR is not defined as a global parameter so it will not be able to accessible in the response function, you need to pass str as a parameter.

Related

JS events. Only one of the event handler function is being called?

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.

can not send data to php by ajax

Hi all I am new in ajax and I am trying to get data from php code this is my ajax code:
function blodvotingview(contentid)
{
var xmlhttp;
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="index.php";
url=url+"?hp=1";
url=url+"&m=blogenvoting";
url=url+"&contentid="+contentid;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
And this is my html code {entry_id} is numeric parameter:
view
<p>Suggestions: <span id="txtHint"></span></p>
And this is php code I want to echo:
<?php
showcomment()
function showcomment()
{
echo "yes";
}
?>
But it doesn't work, please help me.
If you consider use jQuery and jquery.serialize plugin you can easy do this by this example:
$.post('URL', $('#form_id').serialize(), function(r) {
console.log(r);
});
or
$.post('URL', $('#form_id').serialize(), function(r) {
console.log(r);
},'json'); // to parse response as JSON
or
$.get('URL', function(r) {
console.log(r);
},'json'); // to parse response as JSON
Try this
function blodvotingview(contentid)
{
var xmlhttp;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.php?hp=1q="+str,true);
xmlhttp.send();
}
Should work fine,
Wezy

AJAX RSS JS responseXML returning null

{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="http://www.galatasaray.org/_ajax/dinamik_fikstur.php?no=6";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open('GET',url,true);
xmlHttp.setRequestHeader('Content-type', "text/xml");
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
xmlDoc=xmlHttp.responseXML;
alert(xmlHttp.responseXML);
document.getElementById("myDiv").innerHTML=xmlHttp.responseXML;
document.getElementById("takim2").innerHTML=
xmlDoc.getElementsByTagName("owner")[0].childNodes[0].nodeValue;
document.getElementById("takim1").innerHTML=
xmlDoc.getElementsByTagName("guest")[0].childNodes[0].nodeValue;
}
}
function GetXmlHttpObject()
{
var objXMLHttp=null;
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
Im new for ajax programming and I have a problem. responseXML returning null. How can I fix the problem? I tried responseText and returned empty. I searched a lot of source But I cant find a solution

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

javascript not being called

I have the following javascript functions, which when in a standalone file, will be called correctly from a page.
function deleteItem(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
if(xmlHttp.responseText == 'result=true') {
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function deleteRec(layer, pk) {
url = "get_records.php?cmd=deleterec&pk="+pk+"&sid="+Math.random();
if (confirm("Confirm Delete?")) {
deleteItem(layer, url);
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
return xmlHttp;
}
It is called like so:
echo '<td>DELETE</td>' . "\n";
This displays the confirm dialog, and will delete the page if OK is clicked, as it should.
However.
When my other necessary functions are placed in the js file, nothing will happen.
function update(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
function updateByPage(layer, query, pg) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&pg="+pg+"&sid="+Math.random();
update(layer, url);
}
function deleteItem(layer, url) {
var xmlHttp=GetXmlHttpObject();
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
if(xmlHttp.responseText == 'result=true') {
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function deleteRec(layer, pk) {
url = "get_records.php?cmd=deleterec&pk="+pk+"&sid="+Math.random();
if (confirm("Confirm Delete?")) {
deleteItem(layer, url);
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
return xmlHttp;
}
function makewindows(html) {
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
There does not seem to be anything wrong with the JavaScript itself, so I am wondering if something is being canceled out somehow. Even when changing deleterec() to a simple alert nothing happens.
I wonder if there's an error being detected in your JS code? If your Javascript has a syntax error in it, the browser will probably just not run any of it. If you're using a debugger like Firebug, this will help you track down the error.
Alternatively, try adding one function at a time, which will tell you which one is breaking things.
First, in this text block:
if(xmlHttp.responseText == 'result=true') {
// Here you remove the appropriate element from the DOM rather than trying to update something within the DOM
var row = document.getElementById(layer);
row.parentNode.removeChild(row);
}
document.getElementById(layer).innerHTML=xmlHttp.responseText;
You don't actually want this line:
document.getElementById(layer).innerHTML=xmlHttp.responseText;
Additionally, try placing the deleteRec function first before the deleteItem function in the list of functions.
I would also recommend that you test this in Firefox with Firebug installed. This will show you any Javascript errors that are occurring on the page.
Try using FireBug to follow the code that does work.
Also if you have a complete page to show, that may clear things a bit.
maybe the html tag you are using to include the js file into your page is not correct
the correct way to include a script is
<script type="text/css" src="myfile.js"></script>
the following will not work
<script type="text/css" src="myfile.js" />
I would also recomend you to use Firefox's Error Console that is a nice app that will let you know if there are any issues.

Categories