I am trying to get Ajaz to pull data from mysql using a php file every 5 seconds and the process continues. It seems to work great in firefox but does not update in IE.
Can anyone help make this platform independent?
Ajax/Jquery Code
function startprogress() {
$.get("status.php");
setTimeout('updateStatus()', 500);
}
function updateStatus() {
$("#progress").load("status.php");
setTimeout('updateStatus()', 500);
}
PHP File
mysql_connect("localhost","root","password") or
die("Could not connect: " . mysql_error());
mysql_select_db("table");
$sql="SELECT current, total FROM status WHERE id = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "Completed: " . $row['current'] ." of " . $row['total'];
}
Then I have an empty div with id of progress in my HTML file where I have the onClick event to trigger the startprogress() function.
Can anyone help with this?
Thanks much.
When you use setInterval you should do something like this:
var id = setInterval(function() {
// Do something each interval
}, 1000);
clearInterval(id); // When you want to clear it
Some exemple here and here.
Related
I have developing the one application using titanium.
Here the values are inserted successfully.But i didn't get the success message from webservices code.
I have using following code for insert a databaase :
In titanium side code :
function StaffRegistration(){
if($.staff_firstname.value != "" && $.staff_firstname.value != null){
var request = Ti.Network.createHTTPClient({
onload:alert(this.responseText),
onerror: function(e){
Ti.API.debug(e.error);
alert(this.responseText);
},
timeout:1000,
});
request.open("POST","xxx/xxx.php");
var params = ({"staff_firstname": $.staff_firstname.value,"staff_email": $.staff_email.value,"staff_password": $.staff_password.value,});
request.send(params);
}
else{
alert("Please enter the firstname");
}
Ti.API.info("Result for registration = " + this.responseText);
};
I have using a following php(webservice code) :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$staff_firstname = $data['staff_firstname'];
$staff_email = $data['staff_email'];
$staff_password = md5($data['staff_password']);
include "db_connect.php";
$db = new DB_CONNECT();
$result = mysql_query("SELECT staff_email,staff_firstname from at_staff WHERE staff_email = '$staff_email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($queryresult=mysql_fetch_array($result)) {
$uname[]=$queryresult['staff_firstname'];
$uemail[]=$queryresult['staff_email'];
}
if(in_array($staff_firstname,$uname) and in_array($staff_email,$uemail)) {
$response='{"Error":"1","Message":"Username and Email already exist"}';
echo $response;
} else if (in_array($staff_firstname,$uname)) {
$response='{"Error":"1","Message":"Username already exist"}';
echo $response;
} else {
$response='{"Error":"1","Message":"Email already exist"}';
echo $response;
}
} else {
$response='{"Error":"1","Message":"Successfully Registered"}';
echo $response;
$data=array("staff_firstname"=>"'".$staff_firstname."'",
"staff_email"=>"'".$staff_email."'",
"staff_password"=>"'".$staff_password."'"
);
echo $response;
}
?>
How can i get the $response in titanium from this webservice url.
#user2218667
Ti.API.info("Result for registration = " + this.responseText);
will NEVER work as you show in the first piece of code .
why ? because you send a request which will take like 1 seconde (for exemple), obviously, your programm won't wait 1 sec after
request.send(params);
i will continue the programm and when the request return a result, it will get into
onload(e) :
and here only you will be able to have your $result.
is this ok? well now, if this.responseData isn't effective, I don't have the solution .Can you check your line : "} else {" ,i supose there is a if above in the code? are you sure $result is defined upper?
Can you try the same request without titanium with a basic html form to be sure $result is write correctly in this case, like this, we will know if the problem come from php or from the link betwin php & titanium.
well , i supose it's asynchronous request, so the folowing may not work
Ti.API.info("Result for registration = " + this.responseText);
coud you try :
onload : function(e) {
Ti.API.info(this.responseText); // maybe Ti.API.info(this.reponsedata) according to your php.
},
onerror : function(e) {...
in my mind, if you receive JSON information (it trully look's like), you need
this.responseData //instead of this.responseText
This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'> </div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?
Hello I'm working on a shoutbox and I need help with auto updating them via ajax.
Here is my shoutbox with ?getShouts=true at the end:
Here is my shoutbox without that:
My goal here is to run a web request and get the contents of the shoutbox in ?getShouts and update on the page I'm in.
This PHP code is run on the top of the page:
if(!empty($_GET['getShouts']))
{
$sbinfo = "";
$rows = $db->query("SELECT * FROM shouts order by shoutid DESC limit 20");
while($row = $rows->fetch_array(MYSQL_ASSOC))
$sbinfo .= $row['username'] . ": " . $row['shout'] . "<br />";
}
That stores the markup for the text into one string.
later in php file it displays the markup by: if(!empty($_GET['getShouts'])) echo $markup;
Here is my ajax I'm currently running:
<script>
$(document).ready(function() {
getMessages();
});
function getMessages()
{
//make request
var req = new XMLHttpRequest();
req.open("GET", location.href+"?getShouts=true", true);
req.send(null);
document.getElementById("shouts-box").innerHTML = req.responseXML.getElementsById("shouts-box")[0].innerHTML;
//loop
window.setInterval(getMessages,3000);
}
</script>
any ideas?
I have found a solution for this using:
$('#div').load('index.php?getShouts=true #div');
I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.
I'm an AJAX novice and I'm having major trouble trying to get data out of mySQL and into my javascript function.
What I want to do is loop through my data in php and somehow send that data into various named divs on the page.
Here's the code from my javascript page:
function loadPageContent(){
var projectID = getQuerystring('pid');
var templateID = getQuerystring('t');
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var url="getImages.php"
url=url+"?projectID="+projectID
url=url+"&templateID="+templateID
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("statusdebug1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
Here's the code for my php page:
<?php
$projectID = $_GET["projectID"];
$templateID = $_GET["templateID"];
include_once('includes/php/conn.php');
$sql ="select * FROM imageSel WHERE projectID='$projectID' AND templateName = '$templateID'";
$results=mysql_query($sql, $link);
if(!($mysql_rs = mysql_query($sql, $link)))
die("Error in executing query");
echo "<script language='JavaScript'>";
while($row =mysql_fetch_assoc($results) ){
$imageSelID = $row['imageSelID'];
$templateName = $row['templateName'];
$tNode = $row['box'];
$image = $row['image'];
$sql2 ="select * FROM products WHERE productid='$image'";
if(!($mysql_rs = mysql_query($sql2, $link)))
die("Error in executing query");
//Retrieve values
$row2 = mysql_fetch_array($mysql_rs);
$productname = $row2['productname'];
$subcategoryid = $row2['subcategoryid'];
$sql3 ="select * FROM subcategory WHERE subcategoryid='$subcategoryid'";
if(!($mysql_rs = mysql_query($sql3, $link)))
die("Error in executing query");
//Retrieve values
$row3 = mysql_fetch_array($mysql_rs);
$foldername = $row3['foldername'];
$foldername = strtolower($foldername);
$theImage = '<img src="images/lowres/' . $foldername . '/' . $productname .'" />';
echo "document.getElementById(".$tNode.").innerHTML=".$theImage.";";
}
echo "</script>";
?>
That's typically not how I would implement AJAX.
AJAX, when done correctly, should send data to the browser, then let the browser decide what to do with it.
Try using json_encode to put the data you want to send to the browser in JSON format, then on the Javascript end use a JSON library to decode the data then handle it appropriately.
Good luck!
please use this code :
xmlHttp.open("GET",url,false);
because if you are keeping its true then it will call asynchronize ajax.
Please correct if i am wrong.
You are setting the Ajax response to the innerHTML of the div. But you output javascript in your PHP (which becomes your Ajax response). Try outputting just the img tag without the javascript wrapper. Or, even just outputting "Hello world";
EDITED TO ADD: You're using javascript getElementById and innerHtml on the client side and the server side. It's redundant. You probably want to keep it on the client side, ie, your html and javascript