Very simple ajax add to cart - php

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.

Related

Refreshing webpage via JavaScript that is triggered by HTML select with AJAX

I have a strange problem where I cannot get a php webpage to refresh that is triggered by a pulldown. Here is the main file (SelectForceRefresh.php):
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1" /><!-- Optimistically rendering in Chrome Frame in IE. -->
<title>My form</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
function ConfigFileSelection(id)
{
$.ajax({
type: "GET",
url: "RefreshConfig.php",
data: "confFile = " + id,
success: function GotHere()
{
alert("Got here!");
}
});
}
</script>
<select name="userconfigoption" onchange="ConfigFileSelection(this.value);" >
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</body>
</html>
And here is the 'link' file (RefreshConfig.php):
<?php
if(isset($_GET['confFile'])){
CopyUserConfig($_GET['confFile']);
}
function CopyUserConfig($id)
{
header("Location: SelectForceRefresh.php");
exit;
}
?>
The problem is that the javascript function is fired when I make a selection from the pulldown because I see the alert "Got here!", but the other php file is never triggered for the refresh. I have been on this for three days not knowing what I'm missing. I have reviewed the other solutions here on Stack Overflow like this one:
on Change of dropdown list showld call the php function
Where I tried to learn this technique from, but they simply do not work.
What am I missing here? Both files are in the same directory. Thanks in advance.
You can not let the PHP file that you target with your AJAX function refresh your webpage.
The best way is do if in the success function of AJAX (so with JavaScript).
Something like:
$.ajax({
type: "GET",
url: "RefreshConfig.php",
data: "confFile = " + id,
success: function GotHere() {
window.location.reload();
}
});

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)
}
});

$.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>

How to use different pages for form input and results using AJAX

So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337

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