jQuery AJAX live update on multiple elements on the same page - php

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>

Related

Submiting a form with jquery/AJAX isn't working when clicking the submit button

I am trying to submit a form with jquery/AJAX but my function is never called when I am clicking on the submit button.
My website looks like that:
CarMenu.php
<html lang="en">
<html>
<head>
<meta charset="ISO-8859-1">
<title>ArsenalAutoBrokers - Backend - add car</title>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
<link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
<script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
<script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
<script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
<script charset="UTF8" src="../js/app/carForm.js"></script>
<script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
<div id="container">
<div id="leftMenuContainer">
<ul id="menu">
<li id="addCarItem">Add car</li>
<li id="saveCarItem">Edit cars</li>
</ul>
</div>
<div id="rightMainContent">
</div>
<div class="clear"></div>
</div>
</body>
</html>
On that page, I am using jquery menu and I am loading the data into the div with the id 'rightMainContent'.
The javascript code to do this looks like: carForm.js
$(document).ready(function () {
$( "#menu" ).menu({
select: function(event, ui) {
if (ui.item.attr('id') === 'addCarItem') {
$("#rightMainContent").load(
'/CarDealer/CarForm/CreateCar/AddCar.php');
}
}
});
});
If you are clicking on the 'addCar' menu item parts of the site will load from this php site:
<script type="text/javascript">
$('input[type=submit]').button();
//$('#activeCheck').button();
$("#activeCheck").attr('checked','checked');
$('#saveButton').hide();
$('#tabs').tabs();
$('#accordion' ).accordion({heightStyle: "content"});
$('#tabs').tabs({
activate: function (event, ui) {
var act = $("#tabs").tabs("option", "active");
if (act == 0 || act == 1) {
$('#saveButton').hide();
} else {
$('#saveButton').show();
}
}
});
$('#fileToUpload').on('change', function(){
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
if (files.length > 10) {
$('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
$('.info').show();
} else {
$('.info').html('');
$('.info').hide();
}
});
</script>
<form id="carSaveForm"
action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
enctype="multipart/form-data">
<div id="tabs">
<ul>
<li>General Car Information</li>
<li>Car Descriptions</li>
<li>Picture Upload</li>
</ul>
<div id="tabsGen">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
</div>
<div id="tabsDescr">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
</div>
<div id="tabsPics">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>
</div>
</div>
<br> <input id="saveButton" type="submit" name="submit" value="save" />
</form>
This site is containg only form elements like input buttons, file pickers, etc.
Well, so far so good. Everything is displaying properly but if I am clicking the submit button this function isn't getting called: addCar.js
$('#carSaveForm').on('submit', function(event){
event.preventDefault();
var formData = new FormData();
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
formData.append('carBrand' , $('input[name=carBrand]').val());
formData.append('carModelYear' , $('input[name="carModelYear"]').val());
formData.append('carModel' , $('input[name=carModel]').val());
formData.append('carTrim' , $('input[name="carTrim"]').val());
formData.append('carDriveTrain' , $('input[name="carDriveTrain"]').val());
formData.append('carCondition' , $('input[name="carCondition"]').val());
formData.append('carType' , $('input[name="carType"]').val());
formData.append('carFuelType' , $('input[name="carFuelType"]').val());
formData.append('carTransmission' , $('input[name="carTransmission"]').val());
formData.append('carEngine' , $('input[name="carEngine"]').val());
formData.append('carCylinder' , $('input[name="carCylinder"]').val());
formData.append('carMileage' , $('input[name="carMileage"]').val());
formData.append('carExteriorColor' , $('input[name="carExteriorColor"]').val());
formData.append('carInteriorColor' , $('input[name="carInteriorColor"]').val());
formData.append('carLocation' , $('input[name="carLocation"]').val());
formData.append('carVin' , $('input[name="carVin"]').val());
formData.append('carStock' , $('input[name="carStock"]').val());
formData.append('carPrice' , $('input[name="carPrice"]').val());
formData.append('carPriceDetails' , $('input[name="carPriceDetails"]').val());
formData.append('carTax' , $('input[name="carTax"]').val());
formData.append('carTaxDetails' , $('input[name="carTaxDetails"]').val());
formData.append('carCurrency' , $('input[name="carCurrency"]').val());
formData.append('carOnline' , $('input[name="carOnline"]').val());
formData.append('carDescr' , $('input[name="carDescr"]').val());
formData.append('carBodyDescr' , $('input[name="carBodyDescr"]').val());
formData.append('carDriveTrainDescr' , $('input[name="carDriveTrainDescr"]').val());
formData.append('carExteriorDescr' , $('input[name="carExteriorDescr"]').val());
formData.append('carElectronicsDescr' , $('input[name="carElectronicsDescr"]').val());
formData.append('carSaftyFeaturesDescr' , $('input[name="carSaftyFeaturesDescr"]').val());
formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
data : formData, // our data object
contentType: false,
processData: false,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function (data) {
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
return false;
});
I have no clue why this function is never getting called, I have tried everything, I have googled a lot but I am not getting it. I am searching for the error the whole day but I can't see it.
Please help me.
Your help is apreciated.
Thanks in advance.
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
For instance, this button has been added to the DOM via AJAX:
<input id="saveButton" type="submit" name="submit" value="save" />
In order to properly handle this (if it is the only form with this id added to the page) is to delegate the click or submit event:
$(document).on('click', '#saveButton', function(event) {...
In addition, if you continue to add forms as you show here, you will have duplicate id's in your page and id's must be unique. Failure to make them unique will result in a number of problems.
Make sure to watch the AJAX request / response in the browser's console as outlined here to find and correct errors that you may be having.
change $('#carSaveForm').on('submit', function(event) to $('#carSaveForm').on('click','#saveButton', function(event)
Cut (ctrl+x) this line from CarMenu.php
<script charset="UTF8" src="../js/app/addCar.js"></script>
And paste (ctrl+v) the script in AddCar.php

Passing value from ajax to php variable in same page

Since 3days i am trying my best to get the solution from Ajax & PHP, i tried all tutorial but i am unable to get the solution, i am new to Ajax,Jquery but my question is really simple to you all.
i have developed website using jquery & PHP, i have created menu using HTML (ul, li) so what i want is, if i click on menu item ajax should send value to php variable and then execute php function, but all this should happen in same page,..
Please help me to resolve the issues.
So far, I have tried the following:
JavaScript:
<script type="text/javascript">
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "oldindex.php",
data: val,
success: function() {
alert("Hi, testing");
}
});
});
</script>
PHP and HTML:
<input type="submit" id="btn" value="submit">
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
</form>
<div id="number_filters">
1
2
3
</div>
so if i click on href, i should get the value to php variable it should happen in same page only
index.php page
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
alert("Hi, testing");
alert( result );
}
});
});
});
</script>
<input type="submit" id="btn" value="submit">
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
</form>
<div id="number_filters">
1
2
3
</div>
ajax.php page
<?php
echo ( $_GET['val'] );
Let's see:
1- If you are doing a AJAX call, your page won't be refreshed. So if you try to send variables to the same page that makes the AJAX call it won't work, here's why. When you are able to see the page and execute the AJAX call, the code is already on the client side (your web explorer), there no PHP will be seen or executed (PHP is executed on the server only), so it's imposible for the same page to capture and process variables you pass to it using AJAX (since AJAX WON'T refresh the page, that's the point of AJAX).
2- If you are using AJAX you don't have to call to the same page. Call to another PHP, it will make the server side work for you, then return the result:
success: function(data) {
alert("Hi, server returned this: "+data);
}
3- When you pass variables using AJAX you have to assign the variable a name, so it can be read in the PHP side:
data: {value: val},
4- For what you have in your question, you don't start the AJAX call clicking a href, you have the AJAX function linked to a input type=submit, it also is outside a form.. so let's do this better:
<button id="btn">submit</button>
Here is your solution as given sample code:
<?php if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['q'];
exit;
} ?>
<!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>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(e) {
e.preventDefault();
var val = "Hi";
$.ajax ({
url: "test8.php",
// wrong query. you are not passing key , so here q is key
data: 'q=' + val,
success: function(returnResponseData) {
alert('Ajax return data is: ' + returnResponseData);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<input type="submit" name='button' id="btn" value="submit">
</form>
</body>
</html>

Manipulating Form Values After jQuery.load

Good evening everyone,
I am currently trying to cleanup my inline JS and break it up into its own .js file, as well as breaking up some of my code into functions. Below I provide my code, I have an HTML file with an empty div named #main. On document ready I want to call my firstLoad function. It simply calls $("#main").load("login.php"); Seems simple enough, however my next step is that on submit of the form I want to serialize the submitted data, turn to string and submit via post. This for some reason will work if I hard code the form into the index.php file, but not if I use .load to fill in #main. I can't figure out why this is, I am sure it's simple if someone could explain it little that would be wonderful. My code follows:
UPDATE
After more searching I came across this thread that says the following:
As it turns out, the jquery .load() function is working flawlessly,
and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any
"callback" function included by the programmer, just like any other
jquery function that accepts a callback as one of its "arguments". The
.load() function is complete once it either errors or successfully
begins the HTML replacement and loading of new content, but that is
IT! The content will then take however long it takes to load, but your
.load call is already complete before that. Therefore, expecting the
callback to run after the .load content has loaded will only
disappoint you. ;)
I hope others can learn from this just as I did, including those who
thought what I thought was the case. Proof: as stated in the jquery
ajax .load page, the callback is executed when the request completes,
not when the load completes. Eureka. Whoops.
Which leads to the follow up question, how can I manipulate the form after the load content has been added to the DOM? This is surely a simple fix, but I am new to AJAX and could use a nudge in the right direction. I notice adding a document(ready) within the login.php script works properly as it is added with the html, but it doesn't seem like the cleanest way of doing things, as I'm trying to keep out inline JS. Any more advice?
/UPDATE
PHP/HTML
index.php
<?php
session_start();
$sessionNumber = session_id();
?>
<!doctype html>
<!-- Conditional comment for mobile ie7 blogs.msdn.com/b/iemobile/ -->
<!--[if IEMobile 7 ]> <html class="no-js iem7" lang="en"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MyMobile</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/h/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/m/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="img/l/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="img/l/apple-touch-icon.png">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body>
<div id="container">
<header id="header">
<img alt="Logo" src="img/logo.png" />
<div id="blackHead">Please sign-in to continue</div>
</header>
<div id="main" role="main">
</div>
<footer id="footer">
<div id="greyFoot">
© 2012 ACME<br />
<pre id="result"></pre>
</div>
</footer>
</div> <!--! end of #container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/firstLoad.js"></script>
</body>
</html>
login.php
<?php session_start();
$sessionNumber = session_id();
?>
<!-- begin login form -->
<?php if(isset($_SESSION['sessionemail'])){ ?>
Logout
<?php }else { ?>
<form id="logForm" name="login" method="post" action="#">
<label for="sessionemail">Email</label><br />
<input id="sessionemail" type="email" name="sessionemail" autofocus="autofocus" autocapitalize="off" maxlength="150" required="true" value="" class="inputText" /><br />
<label for="password">Password</label>
<input id="password" type="password" name="password" required="true" value="" class="inputText" /><br />
<br />
<input type="hidden" name="sessionid" id="sessionid" value="<?php echo $sessionNumber; ?>" />
<input type="hidden" name="subtocall" id="subtocall" value="g2.web.login.sub" />
<input type="submit" value="Sign-In" name="submit" class="submitBox" />
</form><!-- end login form -->
<?php } ?>
And finally, my JS/Jquery
firstLoad.js
//function serializes our object
(function($){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
//firstLoad function runs on document ready
//it loads the login form into the main div and slides
//the container down
(function($){
$.fn.firstLoad = function(){
return this.each(function() {
$("#container").slideUp("slow", function(){
$("#main").load('./login.php', function(){
$("#container").slideDown("slow", function(){
});
});
});
});
};
})(jQuery);
//logParse takes the loginResponse from the server
//changes from string to object, runs a check for authentication then
//manipulates the object dropping excess keys and adding new relevant ones for
//the intial to do list call
(function($){
$.fn.logParse = function(xml){
return this.each(function() {
//parse the JSON login check string from the XML response
var loginResponse = $(xml).find('string').text();
//setup isBad variable for error check
var isBad = false;
//convert to JSON object from parsed string data
loginResponse = $.parseJSON(loginResponse);
//check if the sessionID is correct and user authenticated properly
if((loginResponse.SESSIONID != "<?php echo $sessionNumber; ?>") || (loginResponse.ISAUTHENTICATED == 0)){isBad = true;}
//if error flag is raised alert and bounce back to login
if(isBad){
alert("Unauthorized connection, please try again.");
}
//if there are no errors
else{
alert("so far so good!");
//set up a new JSON object for to do list passback
//and import the values from the lognResponse object
//var todoPost =
}
});
};
})(jQuery);
$(document).ready(function(){
//hide screen for slidedown
//$("#container").addClass("noShow");
//allow cross domain scripts
$.support.cors = true;
//call firstLoad function to slide in the login prompt
$("#main").firstLoad(function(){
//create JSON object to store form input for AJAX POST
//create submit listener
$("#logForm").submit(function(){
alert("inside submit");
//parse form into formObj for data passing and manipulation
var formObj = JSON.stringify($("form").serializeObject());
//output initial formObj into result pane
$("#result").text(formObj);
$("#main").text("submitted: " + formObj);
//AJAX POST call
$.ajax({
//type of communication
type: "POST",
//action for form
url: "http://mydomain.com/JSONService.asmx/G2WebRequest",
//data to be passed
data: "request="+ formObj,
//type of data passed in
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//enable cross domain
crossDomain: "true",
//data type returned from webservice
dataType: "xml",
//if login POST was successful
success: function(xml){
alert("post successful");
$.logParse(xml);
},
//if login POST failed
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
});
You are probably setting up the listener on $("#logForm") before the login form is fully loaded into the DOM. This would explain why the login form works when hardcoded. You can test this by alert($("#logForm").length);- this will be zero if not found.
If this is the case you will need to ensure you wait until the login page is completely loaded before attempting to attach the listener. I would probably make firstLoad call a function once load completes.
Good luck.
JQuery.on() solved this issue. Took me a while to figure that out.

Pass global javascript variables to php

I have a index.php file where I have canvas game. This game is loaded from separate game.js file where I have variable: ballsCought. I want this wariable and name inputet to text input pass on click to another php file. my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple Canvas Game</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
function score(){
$('#score').fadeIn(1000);
$('#score').load("load_players.php");
};
setInterval(score , 1000);
var nam = $("#name").val();
$('#submit').keyup(function(e){
if(e.keyCode == 13){
$.post('upload_score.php','n=' +nam, 'score=' +ballsCought);
}
});
$('#submit').click(function(e){
$.post('upload_score.php','n=' +nam, 'score=' +ballsCought);
});
});
</script>
</head>
<script src="game.js"></script>
<body>
<canvas id="canvas" width="525" height="525"></canvas>
<br /><p><span id="points"></span><input type="text" id="name" placeholder="Name..."/><input type="submit" id="submit" value="Submit"/></p>
<br /><span id="score"></span>
</body>
</html>
But this post function is not working any idea? THank you...
Looks like your $.post method is not correct. If you want to pass data to the PHP page you need to use the JavaScript object notation like so:
$.post('upload_score.php', {n: nam, score: ballsCought});
You can read more about the various ways to call $.post from the jQuery Docs page
Now there could still be problems with your PHP page. You should use something like Firebug to see the Ajax request and any errors that might be returned.

Show data in real time with AJAX/Jquery/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)
}
});

Categories