javascript not being called - php

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.

Related

AJAX - PHP update of multiple divs

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.

Button calls ajax function multiple

Quick notes. I am not using jQuery so don't suggest it.
When pressing the button which has the onclick="ajaxfunction();" i get an alert saying "Error during AJAX call. Please try again " and then I get the alert saying success, twice :S ... Why is this happening?
I don't understand why this is happening, as it calls the error, and then goes to the other part of the if statement...
Thanks in advance!
<script>
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
var url="insertProduct.php";
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var name = document.getElementById("name");
var code = document.getElementById("code");
xmlhttp.open("POST",url,true); //calling insertProduct.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("name=" + encodeURIComponent(name.value) + "&code=" + encodeURIComponent(code.value)); //Posting to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
}
}
</script>
After finishing the task you can call return;
Likes below.
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText;
return;
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
return;
}
}
I hope this will help to you.

Ajax post displaying an inadequate message

I am new to AJAX methods. I want to post some infos that are processes by a php page, call it page.php
In my html page, I have put this code :
<script type="text/javascript" charset="utf-8">
//I have put the function getXMLHttpRequest() on a separate js file
function getXMLHttpRequest() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
callback(xhr.responseText);
}
};
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=proposition");
}
function postData(Data) {
alert(Data);
}
</script>
<button onclick="request(postData);">...</button>
In page.php, I have a method
protected function comment(){
//some code processing the posted infos (that works fine)...
//to debug, I have put a
echo('Hello world');
}
The fact is I don't get any 'Hello world' but a huge alert message with all my webpage code displayed.
Anyone has an idea ?
Best,
Newben
You are defining a function in page.php, but never calling it.
And remove the protected keyword because it doesn't make sense (you are not making a class)
Try
function comment(){
//some code processing the posted infos (that works fine)...
//to debug, I have put a
echo('Hello world');
}
comment();

JavaScript function not responsive

I have the following code, which is the core part of my small AJAX application. I am not getting any errors, it is just that nothing happens. I am guessing there is a more efficient way to do what I am trying to do.
Here is the code:
var xmlHttp
var layername
function update(layer, part, pk, query)
{
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
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 GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(json_encode(<?php echo $row2["ARTICLE_DESC"]; ?>));
child1.document.close();
}
and an example of how I am calling the function from php
onclick="update(\'Layer3\',\'2\','.$pk.'\',\'0\',)">'
pk or query will never be passed at the same time, only one of them will ever be passed.
edit: I am also wondering if it would make more sense for the makewindows function to take a parameter, or stay as it is. Are there advantages and disadvantages for each approach?
Looks like you may have some javascript errors:
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
Use Firefox and Open the javascript console to get the javascript errors, then try to fix the lines it complains about.
Javascript will stop running as soon as it encounters an error.
Also, checkout firebug if you haven't already. Great tool!
I'd check the HTML the PHP is generating. Assuming $pk is a string it looks like you're missing an opening quote. Try this:
onclick="update(\'Layer3\',\'2\',\''.$pk.'\',\'0\',)">
json_encode is a PHP function, and thus you need to modify that particular line like so:
child1.document.write(<?php echo json_encode($row2["ARTICLE_DESC"]); ?>);

element not being removed from DOM

I have code to delete a record from mysql, displayed in a table via php, and subsequently delete the table row from the page. The record is deleted, however nothing changes in the page or the DOM, and it should change instantly.
Here is the javascript code to delete from the DOM
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);
}
} 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);
}
}
Which is called from php like so:
echo '<tr id=\"article_' . $pk . '\">' . "\n";
echo '<td>DELETE</td>' . "\n";
$pk is the primary key of the record.
The resultant html is fine(obviously since the record is deleted)
DELETE
But the page is not updated in any way.
Why?
I just threw your code into a test page and it works for me when I remove the:
document.getElementById(layer).innerHTML=xmlHttp.responseText;
line that's just before the line:
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
The document.getElementById(layer).innerHTML=xmlHttp.responseText; is causing an error.
Edit:
I'll just add that my 'version' of get_records.php is simply a php page the echos 'result=true' for my own testing purposes, so if you're still running into issues then I would suggest that your PHP script, while deleting the correct data, isn't returning the correct string - you should check what actually gets output to xmlHttp.responseText
Edit 2:
Your PHP code never actually returns 'result=true' in a manner which your responseText will recognise. You have:
if($cmd=="deleterec") {
mysql_query('DELETE FROM AUCTIONS WHERE ARTICLE_NO = ' . $pk);
}
so you will delete the correct item but you have no echo 'result=true'; anywhere so your if statement checking for responseText is never going to get called.
EDIT 3:
My current test code (which works fine in firefox [untested in other browsers]).
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject(){
var objXMLHttp = null;
if (window.XMLHttpRequest){
try{
objXMLHttp = new XMLHttpRequest();
}catch (e){
objXMLHttp = false;
}
}else if (window.createRequest){
try{
objXMLHttp = new window.createRequest();
}catch (e){
objXMLHttp = false;
}
}else if (window.ActiveXObject){
try {
objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
objXMLHttp = false;
}
}
}
return objXMLHttp;
}
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") {
console.log(xmlHttp.responseText);
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);
}
}
</script>
<table>
<tr id="article_260343387801">
<td>Name</td>
<td>DELETE
</td>
</tr>
</table>
This works fine in combination with the php code (with the database connection/query stuff commented out for my personal testing).
I don't immediately see why:
row.parentNode.removeChild(row);
wouldn't work... are you sure you're actually getting there? Your error reporting is problematic:
document.getElementById(layer).innerHTML=xmlHttp.responseText;
‘layer’ is a <tr>, and you can't assign innerHTML on a <tr> in IE. Instead, you will get an ‘Unknown runtime error’ exception and the script will stop.
(Plus, it's undefined what would happen if you tried to put text directly inside a <tr> without a <td> around it.)

Categories