Applying AJAX to rating system - javascript

So I've create this rating system that sends number 1-5 to a textfile, depening on which star the user clicked on.
At the same page we have a counter who counts number of votes, and the total amount of all votes.
The progress works fine, but I want to enchance it some.
Here is my code:
<form name="Star" id="Star">
<div id="rating-area" class="shadow">
<img src="star-icon.png" id="thumb1" data-value="1" />
<img src="star-icon.png" id="thumb2" data-value="2" />
<img src="star-icon.png" id="thumb3" data-value="3" />
<img src="star-icon.png" id="thumb4" data-value="4" />
<img src="star-icon.png" id="thumb5" data-value="5" />
</div>
</form>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ Star : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes in file: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Total: " . $sum;
?>
Im kind of new to this php, but is it possible to do an AJAX request so that we don't have to reload the page to get the updated count numbers?
What I need help with is to create an AJAX call so when the user onclick a star, the page will call for data from the textfile without realoading the whole page.
I think I posted all the necassary information, if not, please tell me and I will edit and try to give you the information.

Firstly I would rather store this information in database than a text file but the concept is the same.
1.) Create a new PHP that reads the text file and gets the new 'Count' of votes or 'Score' whatever information you want to send back. For simple usage I would just echo this value.
2.) Add some more Javascript to go fetch this value after we have added the users count.
The example below gives a good overview of the concept (From W3Schools - http://www.w3schools.com/php/php_ajax_database.asp). This example would take and then replace the return value into the webpage with the css 'ID' of 'txtHint'. This specfic example also gets the entire page and loads it into this ID, this will be fine if you are only echo'ing the vale to your browser.
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
This should help you out, if you struggle getting it to work post back your code and can debug on from that.

Related

Submit issues with form that interact with an API

I have a form that interacts with an API, I used a simple auto submit:
<script type="text/javascript">
window.setTimeout(function(){
document.getElementById('formSubmit').submit();
},1000*20);
</script>
and it worked great in the testing environment. We moved into a new environment and the setup of the hardware was slightly different, realized that didn't work and altered it. Now my auto submit isn't working. The API developers suggested I use watchdog instead so I applied a code according from #Drakes and modified it to interact with my application. This also did not work. I am a noob with Watchdog, and most things in the development world, did I skip a set up with watchdog that wasn't referenced in the previous question?
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
setInterval(function(){ watchdog(); }, 20000);
I think you haven't posted the field values [Fields of the form]. The AJAX code you have used is checking if some value got changed or not every 20 second. But as much as I can understand you wanted to submit your form every 20 second. In that case the AJAX post code need some editing. May be the following thing can solve your problem. Here I am assuming your form having two fields and hence two values are getting submitted. If you have more then you have to modify it as per your requirement.
EDITED MY TESTCODE (This is tested)
The html code along with the AJAX script is as follows -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function watchdog(value1,value2) {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// write any code as this block will be executed only after form succesfully submitted.
document.getElementById("showresponse").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);// You can use this responseText as per your wish
}
}
xmlhttp.open("POST","process.php?value1="+value1+"&value2="+value2,true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
window.setInterval(function(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
// thus store all required field values in variables ,
//here as instance I am assuming the form has two fields , hence posting two values
watchdog(value1,value2);
}, 20000);
function submitIt(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
watchdog(value1,value2);
}
</script>
</head>
<body>
<form id="formSubmit">
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<button type="button" onclick="submitIt();">Submit</button>
</form>
<div id="showresponse"></div>
</body>
</html>
The php code of process.php will be as follows -->
<?php
if(isset($_REQUEST['value1']) && isset($_REQUEST['value1']))
{
$value1 = $_REQUEST['value1'];
$value2 = $_REQUEST['value2'];
echo "Values are respectively : " .$value1." and ".$value2;
}
else
{
echo "Data not found";
}
?>
While testing the above code sample dont forget to keep both html and process.php files in same folder and then test it. The above shown "Run Code snippet" button will not show you any effect of the php code as it only runs html and javascript. So to test it properly you should keep it on some server - local or online .

php javascript code to call php function from javascript

Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.

ajax query on secondary page

Background
I've read through several posts and tutorials here on AJAX, and I've gotten it to work great - on one page, but I'm still new to utilizing AJAX so I hit a rough spot that I can't understand how to fix.
I have my main page, ajaxtest.php which contains a drop-down with this code:
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?></select></a>
which pulls this function:
<script>
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Sending the selection from the database off to my second page, getuser.php.
The user then sees the rest of the initial page populated with the results of getuser.php, which contains the bulk of my code and the HTML tables populated with the SQL info.
This is working fine.
Issue
My issue stems from the fact that once (and pardon my lack of technical jargon,) getuser.php is populated into the <div> that is inside of ajaxtest.php, I can't utilize any other JavaScript or AJAX functions or the entire page just refreshes as if I were to reload ajaxtest.php again from scratch and it puts me back to the initial blank screen with the dropdown menu.
On getuser.php, within the <form> that surrounds the entire table, there is a submit button:
<form action="" method="POST" onsubmit="test()">
and
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
and this is supposed to link to my JavaScript test() function that simply reads:
function test() {
alert("yo");
}
but when I click the button, the entire page refreshes instead of executing this function. Why is this?
If I manually go to localhost/getuser.php?q=John%20Doe instead of "having this page load inside of my ajaxtest.php <div>" and click the button, it works just fine and I get the JavaScript alert to pop up. What am I doing wrong here?
Try editing the function test() to return false
function test() {alert("yo"); return false}
and change the line
<form action="" method="POST" onsubmit="test()">
into
<form action="" method="POST" onsubmit="return test()">
Now it shouldn't refresh the page. Function used in onsubmit needs to return true or false.

How to pass a string containing back slash and front slash from PHP query page back to JavaScript using AJAX

Here I am retrieving values of database using AJAX and PHP. I stored the path of images like photos/image1.jpg in database. While retrieving that data from database and sending them back that data is not getting printing back as it has backslashes or fronth slashes in them. So what is the process to send that data back to main pages which contain special characters while using AJAX?
My JavaScript code:
function getdata(eve)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("grayscreen").innerHTML=xmlhttp.responseText;
} }
xmlhttp.open("GET","picdetails.php?q="+eve,true);
xmlhttp.send();
My PHP code
<?php
include 'config.php';
$query2="select * from Sampletable where sublabel= '".$_GET['q']."'";
$query=mysql_query($query2);
if(mysql_num_rows($query)>0)
{
$count=0;
while($res= mysql_fetch_array($query))
{
if($count==0)
{
$ans= "<img src=". $res['image']."\>";
echo $ans;
}
else {
echo "<img src=".$res['image']." style='display:none'/>";
}
$count=$count+1;
}
}
?>
Here $res['image'] is the path of image which is like images/image1.jpg which will be retrived from database.
Output in the screen is
"<img src="\\">"<img src="style='display:none'/">
But output is supposed to be
<img src="images/images1.jpg"/> <img src="images/images2.jpg" style='display:none'/>
The problem is the data which is retrieved from are images/images1.jpg and images/images2.jpg which is not getting echoed back as it has front slash in it.
How to print that data?
Change:
$ans= "<img src=". $res['image']."\>";
To:
$ans= '<img src="'. $res['image'] .'"/>';
This should work.
Hope it helps!

Javascript AJAX responseText problem in IE

I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.
Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.
Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp
i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)

Categories

Resources