Reputation: 4170
I want to make an AJAX call to the server periodically, the server script(PHP) should make a new XML file. The XML file is then read by another javascript function and displayed on webpage. How do I accomplish this? Heres the Jquery code I have:
setInterval(
function(){
$.Ajax({url: 'register.php'});}, 5000
);
the PHP code that is being requested:
session_start();
$user = $_SESSION['username'];
$uID = $_SESSION['UserID'];
$host="127.0.0.1:3306";
$db_name='wf_db';
$tbl_name="tasks";
$connect = new mysqli("$host","root"," ","$db_name")or die('Can\'t connect to database!');
$sql = "SELECT * FROM $tbl_name WHERE UserID='$uID' and Task_Completed='0'";
$query_data = mysqli_query($connect,$sql)or die('Couldnt get data');
$row = mysqli_num_rows($query_data);
chmod("result".$uID.".xml", 0755);
if($row != 0){
$file = fopen("result".$uID.".xml",'w')or die("Cannot Open File");
$_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
$_xml .="<tasks>\r\n";
while ($result = mysqli_fetch_array($query_data)) {
if ($result["TaskID"]) {
$_xml .="\t<task>\r\n";
$_xml .="\t\t<AssignDate>" . $result["Assign_Date"] . "</AssignDate>\r\n";
$_xml .="\t\t<TaskID>" . $result["TaskID"] . "</TaskID>\r\n";
$_xml .="\t\t<TaskSubject>" . $result["Task_Subject"] . "</TaskSubject>\r\n";
$_xml .="\t\t<Notes>" . $result["Notes"] . "</Notes>\r\n";
$_xml .="\t</task>\r\n";
} else {
$_xml .="\t<task title=\"Nothing Returned\">\r\n";
$_xml .="\t\t<AssignDate>none</Assign_Date>\r\n";
$_xml .="\t\t<TaskID>none</TaskID>\r\n";
$_xml .="\t\t<TaskSubject>none</TaskSubject>\r\n";
$_xml .="\t\t<Notes>none</Notes>\r\n";
$_xml .="\t</task>\r\n";
}
}
$_xml .="</tasks>";
fwrite($file, $_xml);
fclose($file);
}
else {
echo 'Oops something went wrong!';
}
This is what I have so far, what am i missing? I am new to PHP and AJAX so there might be errors in the code.
Upvotes: 0
Views: 697
Reputation: 38
Try using setTimeout JS function to make the calls.
var T = setTimeout("myAjaxFunction");
function myAjaxFunction(){
//do what you want.
$.ajax({...});
}
Upvotes: 1
Reputation: 31033
make an ajax call like
setInterval(
function(){
$.ajax({
url: 'register.php',
type:'GET',
dataType:'text/xml',
success:function(xml){
//here is your xml sent from the server
//parse it using $.parseXML
//then manipulate it according to your will
},
error:function(jxhr){//error handler that will be called if something goes wrong
console.log(jxhr.responseText);
}//error handler ends
});//ajax call ends
}, 5000);
here are some useful links you must look into
Using jQuery to parse XML returned from PHP script (imgur.com API)
Parsing XML from php using jquery
Upvotes: 0