how can i create a widget that loads asynchronously using ajax, js and php
Now this widget has items that should be provided by a php file.
For example the javascript should write a table in this div.
<div id="widget"></>
It should dynamically replace the c开发者_StackOverflow中文版ontent with the html provided through ajax. Does anyone know how to do this.
Also, can it be possible to create an anchor, like <a href="onclick:reload();"></a>
to reload the article without loading the whole page. Thanks.
I would like to learn ajax, but for now this is a one off thing for now and I don't want to learn whole ajax just to create this widget, although I would like to learn it. So please provide me with sites that have tutorials on this with code or possible me help me a little with the code(that will be really very helpful :D )
Create the ajax call and use the onreadystatechange callback to use the response:
<script type="text/javascript>
xhr = new XMLHttpRequest();
xhr.open("GET", "/yourpage.php?get=widget", true);
xhr.send(null);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status==200) {
var widget = document.getElementById ("widget");
widget.innerHTML = response.xhr.responseText;
}
};
</script>
The following is a standard ajax template for something like this. You can anchor the function to your link as you stated in the question, I named the function reload for ease. Now, you have to have a backend script that will get the request and process it and respond. I usually have a programname_process.php script and I send it action post variables depending on what it is trying to do. For example, to reload a certain section, have the post variables be something like "action=reload&extent=minimum" or whatever you might need. Then check for the action variable in your process class construct, depending on the value, send it to a function to process, and then when you get the HTML in a big string that should replace the div contents, just echo it and it will end up in the responseText variable, and poof, then appear in your div.
I went all caps in the places you need to edit for your uses:
<script type="text/javascript">
var xmlhttp;
function reload() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","YOUR PROCESSING SCRIPT",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("POST VARIABLES");
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById('widget').innerHTML=xmlhttp.responseText;
}
}
};
</script>
You can do something like this (using jQuery):
function callWidget(){
$.ajax({
url: "script.php",
success: function(data){
$("#widget").html(data);
}
});
}
And in your anchor you can use:
<a href="#" onClick="callWidget();">Reload</a>
精彩评论