Can't get Ajax works
I have a problem with Ajax. I'm totally noob with Ajax, and I apologize for such a stupid question.
I have a list of elements (loaded by a db) that I want to manage, i.e. Remove, Modify their name..; I want to use ajax to change db and the list.
But I want that the page is modified only AFTER the db has been modified. I can modify the page before the db is modified but it's not what I want.
That's my code:
function setXMLHttpRequest() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function modifyCat(n,newN){
xhrObj = setXMLHttpRequest();
var url = "modifyCat.php?action=modify&cat="+n+"&newCat="+newN;
xhrObj.open("GET", url, true);
links = document.getElementById("cat").getElementsByTagName("a");
updatePage(links);
xhrObj.send(null);
}
function updatePage(links) {
if (xhrObj.readyState == 4) {
var risp = xhrObj.responseText;
//code that works... if not put inside th开发者_运维技巧is if!
}
xhrObj.send(null);
}
ModifyCat.php is
//...
else if($action='modify'){
$n = cleanSimpleString($_GET['cat']);
$nN = cleanSimpleString($_GET['newCat']);
$qry = "UPDATE Categorie Set Nome='$nN' WHERE Nome='$n'";
$check = mysql_query($qry) or $db=0;
}
As I understand if (xhrObj.readyState == 4)
should do want I'm asking. Instead with that If nothing happens (in the page, the php is correctly loaded). Without that If the page is correctly reloaded but while the db is working..
edit.
I would like to do that without framework, I think it's a simple thing that can be solved simply.
Thank you.
If you're "totally noob with Ajax" I'd recommend using an Ajax library, such as jQuery. Have a look at their Ajax page and you'll see that it's much more straightforward than working directly with XHR objects.
Also, you've got a typo - you've use hrObj
in modifyCat
.
You can either use the XMLHttpRequest to do a synchronous or asynchronous request. A synchronous request is easier to program, but will block your page until the result becomes available. An asynchronous request will execute a callback function when the result has become available. There are a number of events for which the callback will be executed, readyState = 4 means the result is available, see also:
http://en.wikipedia.org/wiki/XMLHttpRequest#The_onreadystatechange_event_listener
(and of course the rest of that article)
Having said that, take the suggestions elsewhere to heart, it is much easier (and more cross-browser compatible) to use jquery (or similar javascript/ajax library) to do this stuff.
It would save you a lot of headache if you just used jquery - it can be as easy as doing this:
$.get("modifyCat.php", { action: "modify", cat: n, newCat: newN },
function(data){
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
精彩评论