index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="cart_style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type:'post',
url:'store_items.php',
data:{
total_cart_items:"totalitems"
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
});
function cart(id)
{
var ele=document.getElementById(id);
var img_src=ele.getElementsByTagName("img")[0].src;
var name=document.getElementById(id+"_name").value;
var price=document.getElementById(id+"_price").value;
$.ajax({
type:'post',
url:'store_items.php',
data:{
item_src:img_src,
item_name:name,
item_price:price
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
}
function show_cart()
{
$.ajax({
type:'post',
url:'store_items.php',
data:{
showcart:"cart"
},
success:function(response) {
document.getElementById("mycart").innerHTML=response;
$("#mycart").slideToggle();
}
});
}
</script>
</head>
<body>
<p id="cart_button" onclick="show_cart();">
<img src="cart_icon.png">
<input type="button" id="total_items" value="">
</p>
<div id="mycart">
</div>
<h1>Simple Add To Cart System Using jQuery,Ajax And PHP</h1>
<div id="item_div">
<div class="items" id="item1">
<img src="product1.jpg">
<input type="button" value="Add To CART" onclick="cart('item1')">
<p>Simple Navy Blue T-Shirt</p>
<p>Price - $95</p>
<input type="hidden" id="item1_name" value="Simple Navy Blue T-Shirt">
<input type="hidden" id="item1_price" value="$95">
</div>
<div class="items" id="item2">
<img src="product2.jpg">
<input type="button" value="Add To CART" onclick="cart('item2')">
<p>Trendy T-Shirt With Back Design</p>
<p>Price - $105</p>
<input type="hidden" id="item2_name" value="Trendy T-Shirt With Back Design">
<input type="hidden" id="item2_price" value="$105">
</div>
<div class="items" id="item3">
<img src="product3.jpg">
<input type="button" value="Add To CART" onclick="cart('item3')">
<p>Two Color Half-Sleeves T-Shirt</p>
<p>Price - $120</p>
<input type="hidden" id="item3_name" value="Two Color Half-Sleeves T-Shirt">
<input type="hidden" id="item3_price" value="$120">
</div>
<div class="items" id="item4">
<img src="product4.jpg">
<input type="button" value="Add To CART" onclick="cart('item4')">
<p>Stylish Grey Chinos For Mens</p>
<p>Price - $140</p>
<input type="hidden" id="item4_name" value="Stylish Grey Chinos For Mens">
<input type="hidden" id="item4_price" value="$140">
</div>
<div class="items" id="item5">
<img src="product5.jpg">
<input type="button" value="Add To CART" onclick="cart('item5')">
<p>Comfortable Pants For Working</p>
<p>Price - $130</p>
<input type="hidden" id="item5_name" value="Comfortable Pants For Working">
<input type="hidden" id="item5_price" value="$130">
</div>
<div class="items" id="item6">
<img src="product6.jpg">
<input type="button" value="Add To CART" onclick="cart('item6')">
<p>Slim Track Pant For Jogging</p>
<p>Price - $90</p>
<input type="hidden" id="item6_name" value="Slim Track Pant For Jogging">
<input type="hidden" id="item6_price" value="$90">
</div>
</div>
</body>
</html>
Store_itms.php
<?php
session_start();
if(isset($_POST['total_cart_items']))
{
echo count($_SESSION['name']);
exit();
}
if(isset($_POST['item_src']))
{
$_SESSION['name'][]=$_POST['item_name'];
$_SESSION['price'][]=$_POST['item_price'];
$_SESSION['src'][]=$_POST['item_src'];
echo count($_SESSION['name']);
exit();
}
if(isset($_POST['showcart']))
{
for($i=0;$i<count($_SESSION['name']);$i++)
{
echo "<div class='cart_items'>";
echo "<img src='".$_SESSION['src'][$i]."'>";
echo "<p>".$_SESSION['name'][$i]."</p>";
echo "<p>".$_SESSION['price'][$i]."</p>";
echo "</div>";
}
exit();
}
?>
I'm using this to add an item to the cart. I've learned this from a tutorial. I've understood how his is working but Can anyone explain me how to remove an item from the cart ?
You must to make a similar remove function writed like cart()
Javascript Side
Imagine update_cart()
where you can multiplicate the quantity of an item
and "or" remove it one
(if you are too beginner, try to make removeFrom_cart() instead)
PHP Side
To remove an item of the session array,
you need his offset (getted by php or javascript)
and delete it by using unset(), like :
unset($_SESSION[...name..]);
Note:
I suggest you to change you saving structure
Instead of
$_SESSION['name'][]=$_POST['item_name'];
$_SESSION['price'][]=$_POST['item_price'];
$_SESSION['src'][]=$_POST['item_src'];
unset($_SESSION['name'], $_SESSION['price'], $_SESSION['src']);
Using
$item_offset // getted from ajax
$_SESSION[] =
[
"name" => $_POST["item_name"],
"price" => $_POST["item_price"],
"src" => $_POST["item_src"]
];
unset($_SESSION[$item_offset]);
Otherwise, you'll need to unset three different offset of _SESSION
Good luck !
Related
I have ajax based form submission and on success I want to show a success message. The elements are being generated dynamically by mysql results. Currently the success message for one shows up for all the elements in loop. How can I obtain this for that particular element. Some insight will be very helpful.
<?php if($row['section'] == 1) {?>
<ul class="list-group">
<li class="list-group-item active">
<div class="radio noMargin" id="<?php echo $sectionOne ; ?>info"><?php echo $no ; ?> <span class="glyphicon glyphicon-arrow-right"></span></div><?php echo "<font color='pink'>Ques ID :[".$row['id']."]</font>";?><div class="question"><?php echo $row['question'] ; ?></div>
<div style="float:right; margin-top:-20px;">
Marks:<?php echo $row['marks'] ; ?></div></li>
<?php
echo '<input type="hidden" name="question[]" id="questionId" value="'.$row['id'].'">';
echo '<input type="hidden" name="attempt" value="'.$attemptCount.'">';
echo '<input type="hidden" name="unit_id" value="'.$unit_id.'">';
echo '<input type="hidden" name="chapter_id" value="'.$chapter_id.'">';
$questionId = $row['id'] ;
$sqO =$db->query("SELECT id, options from tbl_options_mock_question WHERE question_id = ".$questionId."");
while($rowO=mysql_fetch_array($sqO))
{
?>
<li class="list-group-item wrp_radio">
<div class="radio noMargin">
<label>
<input disabled type="radio" class="checkedInfo" alt="<?php echo $no ; ?>" name="optionAns<?php echo $i ; ?>" value="<?php echo $rowO['id'] ; ?>">
<?php echo $rowO['options'] ; ?></label>
</div>
</li>
<?php } ?>
<div class="successMessage" style="display:none;"><font color="green"><b>Your notes for question is submitted successfully.</b></font></div>
<br>
<a class="click_notes" data-question-id="<?=$questionId?>"> <font size='2' color='blue'> Add Notes</font></a>
<br>
<div class="demo"></div>
</ul>
<?php $i++;$no++; ?>
<?php } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.click_notes').on('click', function() {
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html('<div class="comment_form"><span><b>X</b></span><form id="contactForm1" action="submit.php" method="post"><textarea required cols="50" class="span10" name="notes" rows="6"></textarea><br><input class="btn btn-primary" id="submitnotes" name="submit_notes" type="submit" value="Add Notes"><input type="hidden" name="submitValue" value="' + tid + '" /></form><br></div>');
});
$(document).on('submit', '#contactForm1', function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data) {
$('.comment_form').hide();
$(".successMessage").show();
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
},
});
}).on('click', 'span', function() {
$(this).parent().hide()
});
});
</script>
Here is a Fiddle I used for testing: https://jsfiddle.net/Twisty/gokfth37/41/
HTML
<ul class="list-group">
<li class="list-group-item active">
<div class="radio noMargin" id="section-1-info">
1
<span class="glyphicon glyphicon-arrow-right"></span>
</div>
<font color='pink'>Ques ID : 1</font>
<div class="question">
Question 1
</div>
<div style="float:right; margin-top:-20px;">Marks: Marks 1
</div>
</li>
<li>
<input type="hidden" name="question[]" id="questionId" value="1">
<input type="hidden" name="attempt" value="0">
<input type="hidden" name="unit_id" value="1">
<input type="hidden" name="chapter_id" value="1">
</li>
<li class="list-group-item wrp_radio">
<div class="radio noMargin">
<input disabled type="radio" class="checkedInfo" alt="1" name="optionAns1" value="1">
<label>Answer 1</label>
<input disabled type="radio" class="checkedInfo" alt="2" name="optionAns2" value="2">
<label>Answer 2</label>
<input disabled type="radio" class="checkedInfo" alt="3" name="optionAns3" value="3">
<label>Answer 3</label>
</div>
</li>
<li>
<div class="successMessage" style="display:none;">
<font color="green">
<b>Your notes for question is submitted successfully.</b>
</font>
</div>
<br>
<a class="click_notes" data-question-id="1">
<font size='2' color='blue'>
Add Notes
</font>
</a>
<br>
<div class="demo">
</div>
</li>
</ul>
I made some leaps and created HTML based on the PHP code you had. You can see here that I had to correct a lot of HTML Syntax. You should not have <ul> that have <input> or <div> elements as children. It should only be <li> elements that can then contain other elements.
So when the "Add Notes" button is clicked, a form is dynamically created that must have a unique ID and all the elements within must have unique IDs. This form will have a Close button, a Text Area, a hidden element and a submit button. When the form is submitted, the data from the form should be submitted via POST to a specific URL and upon successful submission, display the success note.
JavaScript
$(function() {
$('.click_notes').on('click', function() {
$(this).parent().find(".successMessage").hide();
$(this).hide();
var that = $(this);
var tid = $(this).data('question-id');
var form = $("<form>", {
id: "contact-form-" + tid,
action: "submit.php",
method: "POST",
class: "comment-form"
}).submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(data) {
console.log("Success");
$('.comment-form').hide();
that.parent().find(".successMessage").show();
that.show();
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
}
});
});
$("<span>", {
class: "close btn"
}).html("X").click(function() {
that.show();
$(this).parent().hide();
}).appendTo(form);
$("<textarea>", {
required: true,
cols: "50",
class: "span10",
name: "notes"
}).appendTo(form);
$("<input>", {
type: "hidden",
name: "submitValue",
value: tid
}).appendTo(form);
$("<button>", {
class: "btn btn-primary",
id: "submit-notes-" + tid,
type: "submit"
}).html("Add Notes").appendTo(form);
$(this).closest('li').find('.demo').html(form);
});
});
One of the benefits of creating content with jQuery is that you can bind callbacks when you create the object. So instead of mucking around with .on() you can also just call .click() or .submit() right when you're creating the objects. Either works, but sometimes one is easier to manage than the other.
In the example above, we create the form, bind a submit callback to it, add other elements, and the replace #demo with this newly created content. I also added some extra bits to hide a few things, if they are being shown.
When you see var that = $(this); it's sort of a little trick since we do not want to confuse this in some of the other callbacks, yet we may need to reference the original this, and we can, using that.
Hope this helps.
I suggested moving the message outside the loop so you only have ONE message. You could even show it in a dialog
Also you have more than one jQuery loaded. Just load latest or 3.x, not both
change id="contactForm" to class="contactForm"
The HTML is invalid. Move the </ul> to before the demo div
It would have been easier if you wrapped each question and demo div in a wrapper, but try this:
$(document).on('submit', '.contactForm', function(e) {
e.preventDefault();
var $currentForm = $(this);
...
success: function(data) {
$currentForm.hide();
$currentForm.prevAll(".successMessage:first").show();
},
I am trying to build a system where the product-container will display a form or a button depending on if the product is currently in the cart or not. I have an Ajax post system that seems to work fine, but I shall include that too. I have a front Controller which sends the Cart Content and the Products.
The problem is that when I refresh the page my form is supposed to replace the buy button for the given product, but it does not work. Only the Ajax post to Cart system works.
My view (which includes some of the javascript/php):
<?php $countP = 0; ?>
#foreach($products as $product)
<input type="hidden" id="product_id<?php echo $countP; ?>" value="
{{$product->id}}">
<div class="item main-product-container">
<a href="#"<i class="fa fa-exclamation" aria-hidden="true"></i>
</a>
<div class="product-img text-center">
<img src="{{url('img', $product->image)}}">
</div>
<p class="price text-center">{{$product->price}},- kr</p>
<div class="product-title">{{$product->name}}</div>
<script>
<?php foreach($cartContents as $cartContent) { ?>
if(<?php echo $cartContent->id ?> = {{$product->id}})
{
$('.cartBtn{{$product->id}}').hide();
$('.productForm{{$product->id}}').show();
} else {
$('.cartBtn<?php echo $product->id;?>').show();
$('.productForm<?php echo $product->id;?>').hide();
}
<?php } ?>
</script>
<form class="productForm{{$product->id}} productForm"
id="productForm<?php echo $countP;?>">
<input class="qty-input" name="qty" id="qty" type="integer"
value="1">
<input type="hidden" id="id" name="id" value="{{$product->id}}">
<input type="submit" id="ajaxSubmit{{$product->id}}"
class="cart-button" value="Legg til">
</form>
<button class="btn btn-default add-to-cart cartBtn<?php echo
$product->id;?>" id="cartBtn<?php echo $countP;?>">Kjøp</button>
</div>
<?php $countP++?>
#endforeach
</div>
My Ajax:
<script>
$(document).ready(function() {
$('.productForm').hide();
<?php $maxP = count($products);
for($i=0;$i<$maxP; $i++){
?>
$('#cartBtn<?php echo $i;?>').click(function() {
var product_id<?php echo $i;?> = $('#product_id<?php echo $i;?
>').val();
$.ajax({
type: 'get',
url: '<?php echo url('/cart/post');?>/'+ product_id<?php echo $i;?>,
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
},
success:function() {
$('#cartBtn<?php echo $i;?>').hide();
$('#productForm<?php echo $i;?>').show();
},
});
});
<?php } ?>
});
I have a module where a user can upload a profile picture. I want to do several things when a user uploads a picture to there profile, but I am trying to take it in steps, the first step being getting the picture saved and uploaded to the server. Right now, the user can select there picture just fine, after the user has chosen there picture, it gives a little notice that the picture is uploading. I don't know if something is supposed to show after uploading or if it is just supposed to go away (I joined a friend in getting this site done, the module was already here; I'm trying to get the functionality finished up and working).
This is what it looks like:
I have noticed though, that if you click save nothing seems to happen. Like the save button is not set up correctly or something.
I suspect that the the issue of the pictures not being uploaded is either because of the "Uploading..." text or the save button not working. I have tried to debug by echoing out if $_FILES is getting the picture that I am trying to upload, but the module does not reload to allow me to see if $_FILES is getting anything (it's not making it to the if loop of what happens after the save button has been clicked.
Here is the code for the module itself:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
</div>
<div class="modal-body">
<center>
<h3>Edit Profile Picture</h3>
<img src="images/default.png" name="aboutme" width="140" height="140" border="0" class="img-circle"></a></br></br></br></br></br></br></br>
</center>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_pic/change_pic.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-x2-axis" />
<input type="hidden" name="hdn-y2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary">Save</button>
</div>
</div></br>
<div class="container">
<div id="profile_pic_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Upload Profile Picture</h3>
</div>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_and_change.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary" name="save">Save</button>
</div>
</div>
</div>
</div>
</div>
</br></br></br></br></br>
</div>
</div>
</div>
This is the function.js where I think the "Uploading..." is coming from:
jQuery(document).ready(function(){
/* When click on change profile pic */
jQuery('#change-profile-pic').on('click', function(e){
jQuery('#profile_pic_modal').modal({show:true});
});
jQuery('#profile-pic').on('change', function() {
jQuery("#preview-profile-pic").html('');
jQuery("#preview-profile-pic").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-profile-pic',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
/* handle functionality when click crop button */
jQuery('#save_crop').on('click', function(e){
e.preventDefault();
params = {
targetUrl: '/upload_pic/change_pic.php?action=save',
action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
/* Function to get images size */
function getSizes(img, obj){
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0) {
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
} else {
alert("Please select portion..!");
}
}
/* Function to save crop images */
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
success: function (response) {
jQuery('#profile_pic_modal').modal('hide');
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#profile_picture").attr('src', response);
jQuery("#preview-profile-pic").html('');
jQuery("#profile-pic").val();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
I have attempted to comment out the line jQuery("#preview-profile-pic").html('Uploading....'); but that does not seem to remove the "Uploading..." text and the picture still does not upload.
If someone could help me figure out why the module is not working correctly, I would greatly appreciate it. If there is an easier way to get the functionality I am looking for, please let me know.
From my analysis, I did ran the code and found lots of more errors but the following are the key issues to address first.
Your code uses an assigned header file, as seen here ,that carries all the snippets for CDN jquery files. if you would have opened your console while its 'Uploading...' you would have noticed an error like one in this pic
First impression is that no jQuery.form.js file was found which is responsible for this function. If you go further and confirm that it is correctly loaded, Use this function here to check its loading:
(function() {
var startingTime = new Date().getTime();
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'dist_files/jquery.form.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 20);
}
};
// Start polling...
checkReady(function($) {
$(function() {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
window.alert("jQuery.form is loaded, after " + tookTime + " milliseconds!");
});
});
})();
if you would use this function to check if its correctly loaded, after then, if it loads, your next victim is your jQuery, this is because of compatibility issues, the jQuery.form.js version used requires a jQuery of 1.5.x or higher.
Secondly,you have to check that you don't have any conflict with your imports, if in your project you used a version like
Assuming you had used jQuery in your other functions before the profile thing came in, which in this case came with its imports.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
then definitely you'll not have jQuery functioning, meaning, jQuery will no work, and also, the same guy needs to call jQuery.form.js, now you see you'll come back to the same error. so harmonize your imports and delete any duplicates in .js imports and also .css files(although there is no css conflict currently but just for your info)
Once you clean the imports(I advise you use CDN if you are developing with good network connection) clear your browser caches and redo the upload with 'inspect element option in your browser' Do this:
Right click an empty space on browser
select 'inspect element'
switch in the inspector to 'Console' and you'll be able to see the errors if any.
your end result should work and get something of this sort:
I've a problem:
I make ajax query to the database and display information about a specific ID and displays it in HTML-formatted message return.
Here's the HTML code:
<!-- WINE -->
<div id="slides">
<div id="information_slide" class="slide">
<!-- container as a result of JS -->
</div>
</div>
<!-- WINE -->
<!-- LOADING -->
<div id="loading_slide" class="slide" style="display: none;">
Loading information about the wine ...<br/><br/><img src="images/ajax-loader.gif" />
</div>
<!-- LOADING -->
<!-- AJAX CALL BUTTON -->
<?php
echo '<div id="'.$id['id'].'" class="menuItem">Show wine when ID = '.$id['id'].'</div>';
?>
<!-- AJAX CALL BUTTON -->
Here's the JS code:
[JavaScript]
$('.menuItem').on('click', function() {
// ID Wine
var id = $(this).attr('id');
$.ajax({
url: 'function.php',
beforeSend: function () {
$('#slides #information_slide').fadeOut(200, function() {
$('#slides #loading_slide').fadeIn(200);
});
},
data: {
funkcja: 'show_wine',
id: id
},
type: 'post',
success: function(result) {
setTimeout(function() {
$('#slides #loading_slide').fadeOut(200, function() {
$('#slides #information_slide').html(result).fadeIn(400);
});
}, 500);
}
});
// alert(id);
});
[/JavaScript]
Here's the PHP code:
[php]
<?php
if(isset($_POST['funkcja']) && !empty($_POST['funkcja'])) {
switch($_POST['funkcja']) {
case 'show_wine':
show_wine($_POST['id']);
break;
}
}
// Callback wine function
function show_wine($id) {
$qwerty = "SELECT * FROM `wina` WHERE id='".$id."' LIMIT 1";
$sql = mysql_query($qwerty);
while($id = mysql_fetch_assoc($sql)) {
echo '
<div id="'.$id['id'].'" class="element">
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
<input type="hidden" name="my-item-id" value="'.$id['id'].'" />
<input type="hidden" name="my-item-name" value="'.stripslashes($id['nazwa']).'" />
<input type="hidden" name="my-item-price" value="'.stripslashes($cena_przecinek).'" />
<input type="hidden" name="my-item-url" value="" />
<input type="hidden" name="my-item-qty" value="1" size="3" class="item-sztuk" />
<input type="submit" name="my-add-button" value="to cart" class="item-button" />
</fieldset>
</form>
<!-- ... remaining HTML code... -->
</div>
';
}
}
?>
[/php]
I have a result as previously described.
The script shows me the information (records) a specific ID from the database - this part of the script is OK.
The problem I have at the moment when the PHP callback function (which is called Ajax) hosts a form uses also Ajax functions.
This part of HTML code in response from PHP function...
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
<input type="hidden" name="my-item-id" value="'.$id['id'].'" />
<input type="hidden" name="my-item-name" value="'.stripslashes($id['nazwa']).'" />
<input type="hidden" name="my-item-price" value="'.stripslashes($cena_przecinek).'" />
<input type="hidden" name="my-item-url" value="" />
<input type="hidden" name="my-item-qty" value="1" size="3" class="item-sztuk" />
<input type="submit" name="my-add-button" value="to cart" class="item-button" />
</fieldset>
</form>
... is form of my jCart script. Button (name=my-add-button) not work.
JS script is loaded from the very beginning on page:
[html]
<head>
<script type="text/javascript" language="javascript" src="files/jcart.js"></script>
</head>
[/html]
When i call a ajax function, load a result (html code) to the container and button with should add item to cart, page is reloading and item only is added to cart.
I've tried to add return false; in a PHP script, but if there happens to be absolutely nothing.
Here is the JS code file jcart -> www.starwines.com.pl/jcart/js/jcart.js
AND here is DEMO PAGE -> www.starwines.com.pl/test.php
Please try the following:
*1)* add an item by clicking the "Dodaj do koszyka" (yellow button)
2) select a different wine from the carousel, and then click "Dodaj do koszyka"
How to solve this problem?
Regards !
PS. Sorry for English language, I'm weak :)
Change your click event binding code from
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
to
$(document).on('submit', '.jcart', function(e) {
add($(this));
e.preventDefault();
});
will do the work.
jQuery on
My current working situation looks something like this:
<!-- collect user info -->
<form method="GET">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<!-- display image based on user info -->
<img src="color.php?param1=<?php echo $_GET['param1']; ?>param2=<?php echo $_GET['param2']; ?>" alt="" />
This is working perfectly. Now I would like only the image being updated by ajax, while the rest of the HTML remains unchanged. I tried this:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result"></div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$.ajax({
type: 'GET',
success: function () {
$('#result').html('<img src="color.php?' + frm.serialize() + '" />');
}
});
return false;
});
</script>
In fact this solution works more or less. However, I have some issues here:
Is this good jquery / ajax code or is it silly (yes, I am new to jquery)?
The field "result" does update only if one of the fields changes. Can I make it update whenever the submit button is being klicked?
I would like to display a spinning load.gif while the color.php calculates the picture. I tried it this way, without success:
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
$('#result').html(ajax_load).html('<img src="color.php?' + frm.serialize() + '" />');
Thank you!
To the jQuery ajax call add the parameter cache : false, to force to refresh the image. To use the loader, just play with the attributo src. Copy / paste the code:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result">
<img id="preview" src="img/load.gif" />
</div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$('#preview').attr('src', 'img/load.gif' );
$('#preview').attr('src', 'color.php?' + frm.serialize() + '&_' + new Date().getTime() );
return false;
});
</script>