Ajax form in response of ajax Call - php

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

Related

Remove an item from cart by destroying it's session

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 !

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

Using jquery ajax to update dynamically created image by GET

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>

How do I get an external page coupon/voucher form to work in OpenCart?

I have another page in my OpenCart environment, let say the about us page, which has these forms below, assuming the user has items in their cart, these forms should work but they do not:
Enter your coupon code here:
<form action="index.php?route=checkout/cart" method="post" enctype="multipart/form-data" id="basket">
<input type="text" value="" id="coupon" name="coupon"/>
<input type="hidden" value="coupon" name="next"/>
<input type="submit" class="button" value="Apply Coupon"/>
</form>
Enter your gift voucher code here:
<form action="index.php?route=checkout/cart" method="post" enctype="multipart/form-data" id="basket">
<input type="text" value="" name="voucher"/>
<input type="hidden" value="voucher" name="next"/>
<input type="submit" class="button" value="Apply Voucher"/>
</form>
This is for the voucher code system but it does not work (this code is default not edited):
/catalog/controller/checkout/cart.php
// VOUCHER
// IF THE USER HAS ENTERED A VOUCHER
if (isset($this->request->post['voucher']) && $this->request->post['voucher']) {
foreach ($this->request->post['voucher'] as $key) {
if (isset($this->session->data['vouchers'][$key])) {
unset($this->session->data['vouchers'][$key]);
}
}
}
Coupons/Vouchers/Shipping
These three system blocks are modules in OpenCart. They are looped together, you can edit the files, example make some blank or use an if/else statement to show only certain modules.
You cannot call the form itself in the cart.tpl, it must be:
<div class="right">
<!-- eVoucher System -->
<?php foreach ($modules as $module) { ?>
<?=$module?>
<?php } ?>
<!-- eVoucher System -->
</div>
File locations of Shipping/Voucher and Coupon modules
This will loop and show the module tpl files, shipping, coupon and voucher. They are strangely located
/catalog/view/theme/default/total/coupon.tpl
/catalog/view/theme/default/total/shipping.tpl
/catalog/view/theme/default/total/voucher.tpl
We do not use them all so we have blanked the voucher and shipping. Coupon form looks like:
<div>
<div class="cart-heading"><?php echo $heading_title; ?></div>
<div class="cart-content" id="coupon"><?php echo $entry_coupon; ?>
<input type="text" name="coupon" value="<?php echo $coupon; ?>" />
<a id="button-coupon" class="button"><span><?php echo $button_coupon; ?></span></a></div>
</div>
<script type="text/javascript">
<!--
//
// jQuery dependent based on .post so make sure
// your footer or header jQuery call is before this
//
$('#button-coupon').bind('click', function() {
$.ajax({
type: 'POST',
url: 'index.php?route=total/coupon/calculate',
data: $('#coupon :input'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning').remove();
$('#button-coupon').attr('disabled', true);
$('#button-coupon').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#button-coupon').attr('disabled', false);
$('.wait').remove();
},
success: function(json) {
if (json['error']) {
$('#basket').before('<div class="warning">' + json['error'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
}
if (json['redirect']) {
location = json['redirect'];
}
}
});
});
//-->
</script>
So that is how and where these files are, the total also has a controller and coupon and all the other modules are controller and standard MVC driven.
External Coupon Cart Form
So for usage on external pages as you wished, plucking for the tpl files and the $modules and $module loop, code should be:
(making sure "slash" index.php in case of SEO URI)
Sure, example, on your about us page:
<strong>Please enter your coupon:</strong>
<form action="/index.php?route=total/coupon/calculate" method="post" enctype="multipart/form-data" id="basket">
<input type="text" value="" id="coupon" name="coupon"/>
<input type="hidden" value="coupon" name="next"/>
<input type="submit" class="button" value="Apply Coupon"/>
</form>
I've tried putting those forms on a page and they are working for me. Entering a coupon/voucher code takes me to the checkout page with those codes already there for me.

php output display on a greybox

I have a form that calls a php script on submit to insert data into a MySQL database. I would like the output of the php script return to a greybox. I haven't been able to make it work so I appreciate any help you guys can provide.
I have the greybox call on the form definition see below but is not doing the trick.
Here is a subset of the code:
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJX_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<div id="content">
<form id="contact_us" name="contact_us" action="contact-greybox.php" method="POST" onSubmit="return GB_showCenter('Testing', this.action, 500, 500)">
<fieldset>
<label for="employee_id">Employee ID:</label>
<input id="employee_id" name="employee_id" type="number" size="10" /><P />
<label for="employee_name">Employee Name:<strong><br /> (as it should appear on
email) </strong></label>
<input id="employee_name" name="employee_name" type="text" /><P />
</fieldlist>
<p class="submit"><input type="image" name="submit" value="Submit Form" src="icons/ambas_submit.jpg" boder="0">
</form>
</div>
The php is a simple insert statement into MySQL.
Appreciate any help
greybox doesn't support POST submits, but the general pattern is to use ajax to submit the form- otherwise your page will refresh.
You need to set an onclick( $.submit ) to the form input then return false at the end of your ajax call:
$('#contact_us').submit(function(){
//get your inputs here
var e_id = $.('#employee_id').val();
//...etc....
$.post( ...
//set your data/input fields here:
data: { id: e_id },
success: function(response){
//display the response: this is what you get back from: contact-greybox.php
}
})
return false;
});
fancybox is an overlay box that supports being called with pure html as a parameter, so that you can just put this in your success function:
$.fancybox(response);
...or
$.fancybox(response.html)... etc.

Categories