Reputation: 93913
I'm using Ajax and jQuery to do some cool client-side stuff. Basically, if the user chooses a subject from a from a drop-down list, I want to auto-populate the page with a set of book details.
However, I've built the Ajax from Google results and bits of string. I don't know if what I've done is up-to-date, or whether there are now much neater ways of doing it!
Here's what I have: can it be improved?
$("#subjectlist").change(function() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var book_details = eval(xmlhttp.responseText);
alert(book_details[0]["url"]);
// To be added: extra code to populate HTML results.
document.getElementById("book_results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/subject_json/?id=" + $("#subjectlist").val(),true);
xmlhttp.send();
});
Thanks for any advice!
Upvotes: 2
Views: 207
Reputation: 437574
What you are doing is coding the Ajax request yourself. There's no need to do that, as jQuery has a whole class of Ajax methods that will automate this for you.
Some of them will also automate handling the content returned from the Ajax call. In this specific case, load
will work great, as deceze says.
Upvotes: 1
Reputation: 522412
You can probably abbreviate this whole function body into a single .load()
call. Also check out the rest of the jQuery AJAX functions.
Upvotes: 3