AJAX and Codeigniter - Determining what button has been pressed to update - javascript

I have this shopping cart wherein I can add or subtract the quantity of a specific item. The problem is I don't know how to determine if the user has pressed the plus button or the minus button.
HTML code of the plus/minus
<td>
<div class="input-group" style="width: 100px !important;">
<span class="input-group-btn">
<button class="btn btn-danger btn-minus" type="button">-</button>
</span>
<input class="form-control table-shopping-qty" type="text" id = "<?php echo $cartrow['id']?>" value="<?php echo $cartrow['qty']?>" style="padding-left:5px;text-align: center;"/>
<span class="input-group-btn">
<button class="btn btn-success btn-plus" type="button">+</button>
</span>
</div><!-- /input-group -->
</td>
AJAX Function
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"listproductscontroller/editcart_item",
data: dataString,
cache: false,
success: function(){
swal('Success!', 'Cart updated!', 'success');
}, error: function(){
swal('Oops!', 'Something went wrong. Please try again later', 'error');
}
});
}
Controller
public function editcart_item(){
$id = $this->input->post('productid');
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $row){
if($row['id'] == $id){
$updated = array('id'=>$row['id'], 'qty'=>$row['qty'] - 1);
}else{
$updated = array('id'=>$row['id'], 'qty'=>$row['qty']);
}
}
$this->session->set_userdata('cartsession', $updated);
}
if($this->session->userdata('cartsession')!=NULL){
if($this->cartdata = $this->ProductModel->getProductToCart($this->session->userdata('cartsession'))){
$this->session->set_userdata('globalcart', $this->cartdata);
}
}
}

load url helper in controller.using $this->load->url('url');.Then
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url('listproductscontroller/editcart_item');?>",
data: dataString,
cache: false,
success: function(data){
alert("success");
}, error: function(){
alert("failed");
}
});
Don't forget to set
$_config['base_url'] ="your_domain_name";

Related

dynamic button(s) (generate by ajax ) not clickable

i try to create a shop cart using ajax (add working 100% )
but when i try to remove item(s) i found button not clickable
this is the code of delete :
$(document).on('click', '.delete', function() {
var product_id = $(this).attr("id");
var action = "remove";
console.log('something'); // show nothing
$.ajax({
url: "action.php",
method: "POST",
dataType: "json",
data: {
product_id: product_id,
action: action
},
success: function(data) {
$('#order_table').html(data.order_table);
$('#order_footer').html(data.order_footer);
$('.badge').text(data.cart_item);
}
});
})
Button code :
<button class="text-danger delete" id="<?php echo $values["product_id"]; ?>" >
<i data-feather="x"></i>
</button>

How do I detect submitted button with ajax and php?

I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});

$this->input->post() is always empty in codeigniter

I am trying to get a value from an AJAX post that always seems to be empty. I already tried printing the value before doing the post and it works fine but I cannot get the value via $this->input->post()
HTML
<?php if ($product_info->stock > '1'){?>
<button class="btn btn-lg btn-primary" product_id = "<?php echo $product_info->id;?>" id = "addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Javascript
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: productid,
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Controller
$productcart = array();
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $id=>$val){
$productcart[$id] = $val;
}
}
$productcart[$this->input->post('productid')] = 50; -->sample value
$this->session->set_userdata('cartsession', $productcart);
$cartsession = $this->session->userdata('cartsession');
data params have certian format for sending values to the server using ajax.
Try this ...
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: {productid : productid},
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
Instead having your own attribute 'product-id', use HTML5's data attribute like 'data-product_id', so the HTML code looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" id="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
Also, assign class name to the elements if you have more than one 'Add to Cart' buttons to group them, so it looks like:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" class="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
It's time to make use of the data attribute using jQuery:
var product_id = $(this).data('product_id');
Now, the whole code looks like
$(document).ready(function(){
$(".addtocart").click(function(){
var product_id = $(this).data('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: product_id,
cache: true,
success: function(response){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(response){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Oops! </strong>Something went wrong.</div>')
}
});
});
});
Hope it works.

Scroll to bottom of Div using jquery if Ajax returns success

I have this Div which includes the users messages where the newest message is right at the very bottom of the Div and initiates a scroll bar if the messages start to go lower than the div height:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// My messages
</div>
</div>
And I am using Jquery from my js folder to bring the scroll bar to the bottom of the messages on Page load to show the newest message:
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
This works well, unless a new message is added to the page, the scroll bar won't automatically scroll down again unless you refresh the page or unless you add a new message. So you have to manually scroll down everytime you get a new message.
I am using an automatic Div reload script to show new messages:
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
And I am using this Ajax script to add new replies:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Is there a way I can set up the Jquery to run on success of my Ajax so that the scroll bar will be sent to the bottom upon a new message, something like this, which I have tried and found it doesn't work:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Additional code included as requested:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
<?
$res6=mysqli_query($conn, "SELECT * FROM ap_messages WHERE conversation_id = '$conversation_id' ORDER BY time_sent ASC");
while($row6=mysqli_fetch_array($res6))
{
$me_message = $row6['message'];
$me_message_id = $row6['message_id'];
$me_sender_id = $row6['sender_id'];
$todaysdate = date('d/m/Y');
$me_time_sent_date = date('d/m/Y', strtotime($row6['time_sent']));
$me_time_sent_date_and_time = date('d/m/Y H:i:s', strtotime($row6['time_sent']));
$me_time_sent_time = date('H:i', strtotime($row6['time_sent']));
if($todaysdate == $me_time_sent_date){
$me_time = ''.$me_time_sent_time.'';
} else {
$me_time = ''.$me_time_sent_date.' '.$me_time_sent_time.'';
}
$me_time_read = $row6['time_read'];
$res7=mysqli_query($conn, "SELECT * FROM ap_users WHERE user_id = '$me_sender_id'");
while($row7=mysqli_fetch_array($res7))
{
$me_first_name = $row7['first_name'];
$me_last_name = $row7['last_name'];
$me_display_img = $row7['display_img'];
}
mysqli_query($conn, "UPDATE ap_messages SET time_read = NOW() WHERE message_id = '{$me_message_id}' AND time_read = '0000-00-00 00:00:00' AND conversation_id = '$co_conversation_id' AND sender_id != '$user_id'");
?>
<div class="media" style="max-width: <? echo $screenwidth; ?>px;">
<div class="media-left">
<a href="#">
<img src="userimg/<? echo $me_display_img; ?>" alt="user" width="64px" height="64px" hspace="10px" class="media-object" align="left">
</a>
</div>
<div class="media-body" style="position: relative !important;">
<div style="display:inline"><b><? echo ''.$me_first_name.' '.$me_last_name.''; ?></b></div> <div align="right" style="float:right; display:inline"> <? echo $me_time; ?> </div><br>
<? echo $me_message; ?>
</div>
</div>
<?
}
?>
</div>
</div>
<form action="" method="post" id="reply" name="reply" onsubmit="loadDoc()">
<div class="form-group">
<textarea class="form-control" rows="3" cols="80" id="message" name="message" placeholder="Send a reply..."></textarea>
<input type="hidden" id="conversation_id" name="conversation_id" value="<? echo $co_conversation_id; ?>">
<input type="hidden" id="sarssystem" name="sarssystem" value="<? echo $sarssystem; ?>">
<input type="hidden" id="user_id" name="user_id" value="<? echo $user_id; ?>">
</div>
<div class="form-group" align="right">
<div class="btn-group" align="left" style="float:left">
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Delete Conversation</li>
<li>Visit Profile</li>
<li>Report User</li>
<li role="separator" class="divider"></li>
<li>Change Display Photo</li>
</ul>
</div>
<button type="reset" class="btn btn-default btn-sm">Cancel</button>
<button type="submit" class="btn btn-primary btn-sm">Send Message</button>
</div>
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
</div>
When your script is done, you can use the following script:
$content[0].scrollTop = $content[0].scrollHeight;
Example:
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
Hope it helps.
Try like this:
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
}),
success: function(response) {
console.log(response);
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(response) {
console.log(response);
}
});
This is the one that how I approached. First access the parent div that you want to load the data. Then scroll down using jquery.
$.ajax({
type: "GET",
url: baseURL + "notification/get_load_notif_member_message",
data: "member_id=" + member_id + "&message_id=" + message_id,
contentType: 'html',
success: function (html) {
$('.msg_history').html(html);
$("input[name='text']").val('');
var $content = $(".msg_history");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function (html) {
$('.msg_history').html('Something went wrong. Please try again.');
}
});

Modal Pop Up not saving to db when button inside is clicked

I am new with jquery and ajax, so please be patient.
I have this link:
<a href="#message" style="text-decoration:none" class="common2 simple3" >Message</a>
that shows this pop up when clicked:
<div id="message" class="modalDialog">
<div>
<h3>Create A Message</h3>
<form id="msgForm" name="msgForm" action="#" method="post">
<textarea id = 'msgContent' cols="48" rows="10" ></textarea>
<br>
<div id="create_btn">
<a href='' id = 'send' class="common simple2" style='margin-left:50px;text-decoration: none;'>Send</a>
</div>
<div id="cancel_btn">
<a href="#close" class="common simple2" style='margin-left:40px;text-decoration: none;'>cancel</a>
</div>
</form>
</div>
</div>
when I entered text in the textarea and show its content by alert(msgContent) in the script below, it shows
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'message.php?message='+ msgContent,
type: 'GET',
dataType: 'json',
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
but when I try to pass it to a php page through ajax, it won't pass. What could be wrong?
this is message.php
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,$message)";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
You need to read the value from $_GET:
$message = $_GET['message'];
Or use the post method, with data attribute:
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'subscribe.php',
type: 'POST',
data: {message: msgContent},
//dataType: 'json', from your php I don't that that you are looking for json response...
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
Your JS should be this:
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
var msgContent = $("#msgContent").val();
$.ajax({
url: 'message.php',
type: 'POST',
dataType: 'json',
data: {message: msgContent},
context: this,
success: function(result) {
alert('Message has been sent');
}
});
});
});
And your PHP this:
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,'$message')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysqli_error($connection));
}

Categories