Cant update quantity using select option with the help of ajax - javascript

I am creating a simple add to cart function where when the user has successfully added their product to cart they can view their cart and update the quantity using the select option in the cart page, but it seems that i can only update the first product that has been added to cart,if i add a second product i cant update that second product
cart.php
<?php
if(isset($_COOKIE["shopping_cart"]))
{
$total = 0;
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
?>
<?php
foreach($cart_data as $keys => $values)
{
?>
<form id="myForm">
<input type="hidden" name="hidden_id" value="<?php echo $values["item_id"];?>">
<select name="qty" id="qty" class="form-control">
<option style="display:none;" selected><?php echo $values["item_quantity"];?></option>
<?php
for($i=1; $i<=$values["item_qty"]; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
</form>
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#qty").change(function(){
var url = "<?php echo URLROOT; ?>"
var form = $( '#myForm' ).serialize();
$.ajax({
type: "POST",
url: url + '/shops/cookiesave',
data: form,
beforeSend: function() {
//do something here like load a loading spinner etc.
},
})
.done(function() {
window.location.reload(true);
})
});
});
</script>
I have define the URLROOT as define('URLROOT', 'http://localhost/vlake');
cookiesave function
public function cookiesave(){
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
foreach($cart_data as $keys => $values)
{
if($cart_data[$keys]["item_id"] == $_POST["hidden_id"])
{
$cart_data[$keys]["item_quantity"] = $_POST["qty"];
}
}
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30) ,'/');
}

$("#qty") will only ever identify the first element with that ID. So it just doesn't handle events on any of the others. Having multiple elements with the same ID is invalid in HTML - after all, if an ID does not uniquely identify something, then by definition it's not an ID! So JavaScript / jQuery will simply ignore any duplicates after the first one. You'll have the same problem with $( '#myForm' ) as well.
You need to use a class to identify the <select>, and then traverse the DOM to find the parent form:
<form>
<input type="hidden" name="hidden_id" value="<?php echo $values["item_id"];?>">
<select name="qty" class="qty" class="form-control">
<option style="display:none;" selected><?php echo $values["item_quantity"];?></option>
<?php
for($i=1; $i<=$values["item_qty"]; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
</form>
... and ...
$(".qty").change(function(){
var url = "<?php echo URLROOT; ?>"
var form = $(this).closest("form").serialize();
$.ajax({
type: "POST",
url: url + '/shops/cookiesave',
data: form,
beforeSend: function() {
//do something here like load a loading spinner etc.
},
})
.done(function() {
window.location.reload(true);
})
});
N.B. Just as a design point...I note that you reload the page as soon as AJAX has completed. The whole point of AJAX is to allow you to stay on the same page without re-loading. To avoid this unnecessary duplication of HTTP requests, you could either
a) forget about using AJAX for this, and just do a normal postback to update the quantity, or
b) when the AJAX completes, use a little bit of JavaScript just to update the cookie client-side instead.

Related

Jquery is not spotting that a form select has changed

I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`

How to view data from DB with AJAX immediately after script counts it?

I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);

Ajax sends data but php doesn't recieve it

I am using ajax to send data to a php function. The end goal is to display rows of data based on $tweetdate. Here is my ajax script:
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
Here is my php function (add_action is for WordPress usage):
<?php
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets');
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();
?>
fullCalendar is a jQuery event calendar. When the user clicks on a day (dayClick) that day is saved to date. That date is what I am trying to save to "tweetdate" in my ajax.
In chrome, when I use the network tab on the inspector I can see the ajax result and the date clicked on is set to "tweetdate". That isn't getting picked up by my php function. In my php "tweetdate" is not getting a value assigned to it.
Now, if I go into my php function and set "tweetdate" to an actual date instead of $_POST["tweetdate"]; e.g. 2016-06-15 than everything works perfectly.
I'm not quite sure what is going on.
To make it work, you need one more essential thing:
add_action('wp_enqueue_scripts', 'my_custom_scripts');
my_custom_scripts(){
// Here you register your script for example located in a subfolder `js` of your active theme
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
// Here you are going to make the bridge between php and js
wp_localize_script( 'ajax-script', 'my_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
See that 'ajax-script' is in both functions wp_enqueue_script() and wp_localize_script()…
Then you will retrieve 'ajaxurl' and 'my_ajax' in your js combined in url:my_ajax.ajaxurl,:
jQuery(document).ready(function($) {
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: my_ajax.ajaxurl,// Here 'my_ajax' & 'ajaxurl' from wp_localize_script()
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
});
Now you can get the $_POST["tweetdate"];in your php!!!
Update: May be you need to add to your php function (for front end):
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets');
And to and die();at the end inside your function. so you will have:
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets'); // backend
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets'); // fronted
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
die(); // very important to get it working
}
Update 2: important! — It should work this time!
I have made a little typing error:
It's add_action('wp_ajax_nopriv_ … instead of add_action('wp_ajax_no_priv_ …
These php codes needs to be on the function.php file of your active theme (or child theme).
Then you will call your function somewhere else or you can hook it with some add_action() hooks.
show_scheduled_tweets();
References:
Wordpress passing ajax value to a specific page using Wordpress
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

Single Div refresh with jquery Ajax and PHP

Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}

Categories