Show data in real time with AJAX/Jquery/PHP - php

I am fairly new to PHP but was looking at this tutorial. http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
I want to test a similar concept to display data from my database on a page when someone submits data via a form.
eg there is a page where you choose what color shoes you want and a page with a leaderboard to see how many times each color has been chosen.
I have no problem submitting the form but don't no where to start to look to get the contents to display on the leaderboard using ajax. Can anyone point me in the right direction here please?

you should start with this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.ajax({
url: '/ajax.php',
type: "POST",
data: "value="+$(this).val,
cache: true,
dataType: "JSON",
success: function(response){
$("#leader-board").append("you choose "+ $(this).val + "color : " +response.count + " times");
}
});
});
});
</script>
</head>
<body>
<label for="txtValue">Enter a value : </label>
<input type="text" name="txtValue" value="" id="txtValue">
<div id="leader-board"></div>
</body>
</html>
and you ajax.php file look like this
<?php
//if your data return result like this so you have to do this process
$data = array("count"=>5);
echo json_encode($data);
?>

You can send you form data and get your response in your div which have an id 'yourDivId' like below. You should to make a one more column 'countcolor' in your table . Increment it when a user request a particular color.
$.ajax({
url: base_path + "/folder/test.php",
data: "id="+id,
type: 'GET',
success: function (resp) { document.getElementById('yourDivId').innerHTML=resp;},
error: function(e){ alert('Error: '+e); }
});

After you submit the form, you need to get the pertinent data, echo it back (if you're using ajax, you want to echo is back using json_encode();), and then put it in the "leaderboard" div. e.g.
Action page for submitting to database
<?php
header('Content type: application/json');
// after you've submitted the data to the database, get the data for the leaderboard
$leaderboard_data = array();
$leaderboard_data = your_function_to_grab_data();
echo json_encode($leaderboard_data);
?>
On the page where you submit the form
$.ajax({
url: 'insert/path/to/action/here',
success: function(data) {
$("div#leaderboard-div").html(data)
}
});

Related

ajax "post" request failed

I am using ajax for the first time and passing data to another file using ajax request. The request goes through if I pass it using get which is by default but the moment I change it to post it does not work.
$.ajax({
type:'POST',
url:'pageAjax2.php',
data:'name='+name,
success: function(data){
$('#content').html(data);
}
})
If I remove the type:'POST'; everything works but if have it in the code nothing works . Can someone please help me with this.
All good here. What version of jQuery are you using ?
I'll post my code :
File jq.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(function(){
var name = 'Telmo Dias';
$.ajax({
type:'POST',
url:'pageAjax2.php',
data:'name='+name,
success: function(data){
$('#content').html(data);
}
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
File pageAjax2.php :
<?php echo "Hello ".$_POST['name'];?>
Result:
thank you guys i just checked and pageAjax2.php had been set to get instead of using post so i just changed it to post and everything works now
thank you

Very simple ajax add to cart

Ok I am trying to wrap my head around how to add something to a cart and have it show in the page without reloading the page.
So I have tried to write something very simple so I can wrap my head around how exactly the logic works and is properly written. In my example I have a div in the page for the session['cart'] and a drop down.
One option with value of 'red' and the other option with value 'blue'. When I select the option with value of 'red', I want 'red' to show in the div located right after body tag insession['cart']. When I select the option with value of 'blue', I want 'blue' to show in session['cart'].
I am attempting to do this through an ajax post to a page called 'cart_update.php'. I have been struggling with a more advanced model of this for a week and I thought it would be a good idea just to write something simple so i could really understand and learn what is really going on. Any help is really appreciated!
Here is my code and I know its way off. I am just trying to learn.
index.php
<?php session_start(); ?>
<!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=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style type="text/css">
body {
margin-top: 200px;
}
</style>
</head>
<body>
<div align="left" style="display:block;width:200px;height:200px;background:#ccc;border:solid 1px #009966;">Color Chosen<br /><?php echo $_SESSION['cart']; ?></div>
<div align="center"><form method="post" action="">
<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#color-selection").on("change", function(event){
var color = $("#color-selection").val();
var add = "add";
var dataString = {color: color, type: add}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
</script>
</body>
</html>
and here is my cart_update.php
<?php
session_start();
$type = json_decode($_POST['type']);
if(isset($_POST["type"]) && $_POST["type"]== $type)
{
$color = json_decode($_POST['color']);
$_SESSION['cart'] = $color;
}
?>
It's hard to tell what's not working when you don't tell us what error/warning you get. You should look into your js-console (with firebug or another debugging tool)
Looking at your code though, I see some things..
$(document).ready(function(){
$(".add_to_cart").onClick(function(){
var dataString = "color=" + color;
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
onClick won't work in this context. Use on() instead. http://api.jquery.com/on/
The second thing is that you should use JSON-formatted strings when sending data.
$(document).ready(function(){
$(".add_to_cart").on("click", function(event){
var dataString = {color: color}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
In your html you have hidden fields with several forms with defined colors. Instead of that approach I would make a select-list within one form so it would be kind of easy to grab the value of the color, and you wouldn't have to create a new form for each color.
Something like this:
<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
Then in your js, you can get the selection of color by doing something like this:
color = $("#color-selection").val();
To get a response-value when ajax-call is done, then use the done()-callback. It's also a good practice to assign a return-type.
$(document).ready(function(){
$(".add_to_cart").on("click", function(event){
color = $("#color-selection").val();
var dataString = {color: color}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString,
dataType: "json" //This indicates the expected return-type
}).done(function(data) {
$("#thecoloris").html(data.color); //response from php. Set the color in the div id="thecolorid"
});
});
});
In your php-code you will have to decode the json-data:
<?php
session_start();
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$color = json_decode($_POST['color']);
$_SESSION['cart'] = $color;
}
echo $_POST['color']; //Output color (that is sent to this php through ajax) - This acts as the return value data in the ajax-function done()
?>
Usually the outputted value should be encoded in json-format with json_encode($variable) but in this case $_POST['color'] is already in json-format because it was sent to the php from js in json-format.

php and ajax passing form value

Hi how would I echo the form input "date" in a PHP file from the code below. (data: "name=Peter&location=Sheffield" + $('input[name="date"]').val(),)
at the moment I have echo "todays date ".$_POST['date']."<br>"; but it doesnt seem to work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript"
src=http://code.jquery.com/jquery-latest.js>
</script>
<script type="text/javascript">
// This functions starts the ajax to show the output from post.php
function StartAjax(ResultsId){
$.ajax({
type: "POST",
url: "postTest.php",
cache: false,
data: "name=Peter&location=Sheffield" + $('input[name="date"]').val(),
success: function(html, status){
$("#"+ResultsId).append(html);
$('#status').append(status);
}
});
}
</script>
</head>
<body>
<h1> Run Club</h1>
testing
<form>
date: <input type="text" name="date"><br>
</form>
Click Here to see updates from postTest.php
<div id="ResultsId"></div>
<div id="status"></div>
</body>
</html>
You have to put a date key in your query string
data: "name=Peter&location=Sheffield&date=" + $('input[name="date"]').val(),
alternatively you should pass an object to data so jQuery will format the query string for you.
data: {name: "Peter", location: "Sheffield", date: $('input[name="date"]').val()},
function StartAjax(ResultsId){
var date = document.getElementsByName("date").val();
$.ajax({
type: "POST",
url: "postTest.php",
cache: false,
data: "name=Peter&location=Sheffield&date=" + date,
success: function(html, status){
$("#"+ResultsId).append(html);
$('#status').append(status);
}
});
}

$.ajax data not posting specified value to $_POST

Okay, what have I done wrong here?
I'm trying to .POST data from a Form with JQuery $.ajax function and return json data. But every time the post data is null.
Here is the HTML/JQuery Part
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
</head>
<body>
<form action="testform" method="post">
OLD ID:
<input id="OldID" name="OldID" type="text"><br>
NewID:
<input id="NewID" name="NewID" type="text"><br>
<input id="do" name="do" type="button" value="Get New ID">
</form>
<script type="text/javascript">
var CID = $('#OldID').val();
$(document).ready(function(){
$('#do').click(function(){
sendValue();
});
function sendValue(CID){
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>
</body>
</html>
Here's the PHP page
<?php
if (isset($_POST['OldID'])){
$value = $_POST['OldID'];
}else{
$value = "ELSE VALUE";
}
echo json_encode(array("NewID"=>$value));
?>
I'm sure this is a simple mistake on my part but I'm just going in circles at this point.
Thanks in advance!
$('#do').click(function(){
sendValue();
});
should be:
$('#do').click(function(){
sendValue("VALUE TO SEND TO THE SERVER");
});
because
function sendValue(CID){
takes the scope of CID which it seems you might think should be this var CID = $('#OldID').val();
Your mistake is that you are getting the value of the OldID field in your script, and not on some event handler method. This causes when the script is loaded (when the page is being viewed), the value of the text input is kept on variable CID. and when the user clicks on the #do button, then the value of CID is still the same as the one when the page was loaded. So no value is stored in CID variable, so no value is sent via AJAX.
Define another function (Say sendOldID) that reads the value of the text input in the CID variable, and then calls the sendValue() method with CID paramter. The use that function as the event handler of the #do button clicked.
<script type="text/javascript">
$(document).ready(function(){
$('#do').click(function(){
sendOldID();
});
function sendOldID() {
var CID = $('#OldID').val();
sendValue(CID);
}
function sendValue(CID) {
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>

jQuery AJAX live update on multiple elements on the same page

I'm delving into some AJAX and I'm trying to utilise jQuery.
I have an index page which links to multiple pages and next to each page is a view count.
I would like the view count to refresh and automatically update every couple of seconds so that those on the page can view live updates of the page counts.
I've come accross the following script that works well based on a single Ajax element on the page, but what about 10 or more?
Is there a more efficient way (short of cutting and pasting the statement 10 times) to get all the fields to update individually?
<?php
// File: ajax.php
// Ajax refresh hits
if(isset($_GET['refresh'])){
// Uses the get_page_views() function which takes an ID and retreives that page view count. The ID is passed by the AJAX script.
if($_GET['refresh'] == 'hits') echo get_page_views($_GET['id']);
};
?>
This si the code to the HTML page.
<!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=utf-8" />
<title>Ajax - PHP example</title>
<script language="javascript" type="text/javascript" src="jquery-1.3.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
//ajax.php is called every second to get view count from server
var ajaxDelay = 1000;
setInterval(function(){
// Refresh details.
$('#zone-111').load('ajax.php?refresh=hits&id=111');
$(#zone-222').load('ajax.php?refresh=hits&id=222');
$(#zone-333').load('ajax.php?refresh=hits&id=333');
$(#zone-444').load('ajax.php?refresh=hits&id=444');
$(#zone-555').load('ajax.php?refresh=hits&id=555');
}, ajaxDelay);
});
</script>
</head>
<body>
<div align="center" id="zone-111">--</div>
<br />
<div align="center" id="zone-222">--</div>
<br />
<div align="center" id="zone-333">--</div>
<br />
<div align="center" id="zone-444">--</div>
<br />
<div align="center" id="zone-555">--</div>
<br />
</body>
</html>
Any suggestion on how I can make this script/code more efficient would be greatly accepted.
Kind regards,
P.
Send all of the ids at once as a JSON array. On the server side, build a JSON object containing key/value pairs of the ids/counts. Then iterate through the keys on the client when you get the result and set each count in turn in the related DIV.
$(document).ready(function(){
//ajax.php is called every second to get view count from server
var ajaxDelay = 1000;
var ids = [];
$('[id^="zone-"]').each( function() {
ids.push( this.id );
});
setInterval(function(){
$.ajax({
url: 'ajax.php',
dataType: 'json',
type: 'get',
data: { refresh: 'hits', ids: ids },
success: function(data) {
for (var key in data) {
var div = $('#zone-' + key).html( data[key] );
}
}
});
}, ajaxDelay);
});
Thanks for the JSON suggestions, I wasn't quite sure how to implement it though and I've come up with this solution that works quite well so far. Feedback would be great.
<script type="text/javascript" language="javascript">
$(document).ready(function(){
setInterval(function(){
$('.views').each(function(){
$(this).load('ajax.php?id='+this.id);
});
}, 5000);
});
</script>
And in the HTML you just assign the class 'views' to the element that you want updated and the store the 'ID' as the id eg:
<p class="views" id="123"><!-- content appears here. --></p>

Categories