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.)
Related
Learning AJAX.
I have the following AJAX script, i am using it primarily for navigation (backend php):
function ajaxFunction(linked) {
var ajaxRequest;
var loading = $('#loading');
if(loading.length > 0) {
loading.css('display', 'block');
}
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function() { **//READY STATE HERE!**
if(ajaxRequest.readyState == 4) {
var ajaxDisplay = $('#wrapper');
loading.css('display', 'none');
ajaxDisplay.html(ajaxRequest.responseText);
if($('#search_field').length > 0) {
$('#search_field').focus();
}
if($('#year').length > 0) {
$('html').scrollTo('#year');
}
startValidation(); **// VALIDATION FUNCTION HERE!**
}
}
// Now get the value from user and pass it to
// server script.
if(linked == 'addNewPage' || linked == 'add') {
var queryString = "?page=add";
queryString += "&action=customer&add=new&ajax=ajaxRequest";
} else if(){} etc...
I have downloaded the h5validate plugin to take advantage of the HTML5 validation i already have in place, the problem is when i load the content through AJAX any .ready functions get unbound from the DOM and don't work. I have tried calling the function after ReadyState==4 but it still won't launch. The function works if i navigate to it directly (without AJAX) and use:
window.onload = startValidation();
Validate trigger:
function startValidation() {
$('.row').h5Validate({
errorClass:'red'
});
}
Where am i going wrong here?
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.
I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx
I made a website that depends on PHP, AJAX and Javascript.
The problem here is that the website is unstable which means sometimes the validation is working and some times it is not working at all.
The validation code is written in JavaScript. Does this mean that we need more special conditions?
The code for validation:
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val)
{
var req = Inint_AJAX();
req.onreadystatechange = function ()
{
if (req.readyState==4)
{
if (req.status==200)
{
document.getElementById(src).innerHTML=req.responseText;
}
}
};
req.open("GET", "traditional_locate.php?data="+src+"&val="+val);
req.send(null);
}
window.onLoad=dochange('cities', -1);
function submitform()
{
if(document.form1.onsubmit())
{
document.form1.submit();
}
}
function validate()
{
var p_o_box=(document.form1.p_o_box.value);
var owner_name=(document.form1.owner_name.value);
var cities=(document.form1.cities.value);
var post_office=(document.form1.post_office.value);
if(cities == 0)
{
alert("Please Choose city");
document.form1.cities.focus();
return false;
}
else if(post_office == 0)
{
alert("Please Choose post office");
document.form1.post_office.focus();
return false;
}
else if (p_o_box=="")
{
alert ("Please Write P.O.Box");
document.form1.p_o_box.focus();
return false;
}
else if(owner_name=="")
{
alert("Please Write Owner Name");
return false;
}
else if(p_o_box!="")
{
var a=new Array;
<?php
session_start();
$zipinfo=$_SESSION[zip_code];
$conn=mysql_connect('localhost','root','');
mysql_select_db('post_db',$conn);
$query="select p_o_box from p_o_box where zip_code='$zipinfo' ";
$result = mysql_query ($query , $conn ) or die ( mysql_error ());
$rows=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
for($i=0;$i<count($n); $i++)
{
echo "a[$i]='".$n[$i]."';\n";
}
?>
var ss=0;
for(i=0;i<a.length;i++)
if(a[i]==p_o_box)
{
var ss=1;
}
if (ss==0)
{
alert('not correct p.o. box');
document.form1.p_o_box.focus();
return false;
}
else
{ return true;}
}
return true;
}
</script>
Very hard to answer because I don't see a question.
What exactly does not work?
But I can suppose some problems:
Are you sure, that body.onload runs? Sometimes doesn't...
scripting is not crossbrowser
session_start() should fail because there is an output before and headers can't be sent.
you said that validation fails, but where is it being called?
please, provide more exact question and more clear example of code which does not work (i.e. I'm not sure, that source of submitform() is so nessecary).
Validation should be done on the server side. What happens when a use disables their JavaScript?
Also, that block of JavaScript will only execute the PHP when the page loads, and not everytime the user validates.
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.