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.
Related
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>
With this code I want to insert and move a file into a folder but when I choose a file and upload it shows me an error in my console:
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
How can I solve this problem? Please help me. Thank You
<input type="file" id="multiFiles" name="files" />
<button id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
$("#upload_file_multiple").click(function(event) {
event.preventDefault();
var form_data = new FormData($("#multiFiles"));
var id = "<?php echo $this->uri->segment(3) ?>";
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
processData: false,
contentType: false,
success: function(response) {
$('#afx_khjk').html(response);
},
error: function(response) {
$('#afx_khjk').html(response);
}
});
});
public function UploadFile($id)
{
if (isset($_FILES['files']) && !empty($_FILES['files']))
{
$rename = 'file_no-'.time().$_FILES["files"]["name"];
move_uploaded_file($_FILES["files"]["tmp_name"], 'uploads/syllabus/' . $rename);
$data = array(
'pdf'=>$rename,
'subjectID'=>$id,
'unique_id'=>time()
);
$this->db->insert('sylabus_pdf',$data);
$insert_id = $this->db->insert_id();
echo 'File successfully uploaded : uploads/syllabus/' . $rename . ' ';
$this->commondata($id);
}
else
{
echo 'Please choose at least one file';
}
}
The error is because the FormData constructor expects an FormElement object, not a jQuery object containing an input.
To fix this create the FormData object with the empty constructor and use append() to add your file:
var input = document.querySelector('#multiFiles');
var form_data = new FormData();
for (var i = 0; i < input.files.length; i++) {
form_data.append('files[]', input.files[i]);
}
Alternatively you can make this more simple by providing the form to the constructor. That way the data in all form controls will be included for you automatically.
var form_data = new FormData($('#yourForm')[0]);
HTML
<form id="frm_upload_file">
<input type="file" id="multiFiles" name="files" />
<button type="submit" id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
</form>
Ajax
$("#frm_upload_file").submit(function (event) {
event.preventDefault();
var id = "<?php echo $this->uri->segment(3) ?>";
var form_data = new FormData(this);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
$('#afx_khjk').html(response);
},
error: function (response) {
$('#afx_khjk').html(response);
}
});
});
I have a form to add item to favorites, and also to delete it.
Let's say this is form for adding and deleting:
#if($checkIfFavIsAdded == 0)
{!! Form::open(['id' => 'ajax-form-add', 'style' => 'float:right']) !!}
...
<button class="fa fa-star-o fa-2x" tool-tip-toggle="tooltip-demo" id="addFavbutton" title="Add item to favorites" style="color:#fd8809"></button>
{!! Form::close() !!}
#else
{!! Form::open(['id' => 'ajax-form-delete', 'style' => 'float:right']) !!}
...
<button class="fa fa-star-o fa-2x" tool-tip-toggle="tooltip-demo" id="addFavbutton" title="Delete item from favorites" style="color:grey"></button>
{!! Form::close() !!}
#endif
Here, I am checking if the item is added to favorites, and if so, the appropriate form should be shown.
It works on page reload, but how can I do this in Ajax?
I've tried to hide and show but without success. It just hides the form and don't display another one.
<script type="text/javascript">
$("#ajax-form-add").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
$("#ajax-form-add").hide();
$("#ajax-form-delete").show();
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
</script>
<script type="text/javascript">
$("#ajax-form-delete").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('deleteFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
$("#ajax-form-delete").hide();
$("#ajax-form-show").show();
},
error: function(data){
swal("Error!", "Item is not available!", "error")
}
});
});
</script>
Blade templates are rendered server side, what you're trying to do is client side.
If you have that conditional in your blade template, the markup that gets rendered and sent to the browser will not include the other form.
You'll need to return the markup you want to display (IE the new form) in the ajax response.
For the second ajax you have written:
$("#ajax-form-show").show();
No, id with ajax-form-show is present. It should be:
$("#ajax-form-add").show();
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";
In my page I have the following code, that each add-to-favor- is followed by a unique hash to distinguish my multiple results.
<a class="btn btn-default btn-sm m-t-10 add-to-favor-'.$active[hash].'">
<i class="text-danger fa fa-heart"></i>
</a>
The problem is that I do not know how to have one universal solution for my problem. I want to pass the active[hash] to the ajax post.
Shall i use data-attributes? If yes, how ?
$(function(){
$('body').on('click', '.add-to-favor', function (){
$.ajax({
cache: false,
type: 'POST',
url: ,
data: ,
success: function(data) {
$('#show_the_favor').html(data);
}
});
});
});
Yes, you should use data-* attribute.
You specify data attribute as data-some-name="value". To get that value use .data('some-name')
<a data-hash="<?= $active['hash']; ?>" data-target="#show_the_favor" class="add-to-favor"></a>
$(document).ready(function () {
$(document).on('click', '.add-to-favor', function () {
var el = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'someUrl',
data: {hash: el.data('hash')},
success: function(data) {
$(el.data('target')).html(data);
}
});
});
});
Yes, use custom attributes. For your <a> elements, add the class add-to-favor but don't append the hash to that class. Then, add another attribute, data-hash="' . $active[hash] . '":
<a class="btn btn-default btn-sm m-t-10 add-to-favor" data-hash="' . $active[hash] . '">
<i class="text-danger fa fa-heart"></i>
</a>
JS:
$(function() {
$('body').on('click', '.add-to-favor', function() {
var hash = $(this).attr('data-hash');
$.ajax({
cache: false,
type: 'POST',
url: "script.php", // Enter the AJAX script URL
data: {
hash: hash
},
success: function(data) {
$('#show_the_favor').html(data);
// If you want to show the hash inside #show_the_favor, replace `data` above with `hash`
}
});
});
});
You can use this:
$('body').on('click', '[class*="add-to-favor"]', function (){
var hash = $(this).attr('class').match(/add-to-favor-([^ ]+)/)[1];
$.ajax({
cache: false,
type: 'POST',
url: SomeUrl,
data: {hash:hash},
success: function(data) {
$('#show_the_favor').html(data);
}
});
});
or simply use data attribute:
<a class="btn btn-default btn-sm m-t-10" data-hash="'.$active[hash].'">
<i class="text-danger fa fa-heart"></i>
</a>
and get the hash using $(this).data('hash').
Why don't you simply make your own Javascript Function to do this?
HTML:
<a class="btn btn-default btn-sm m-t-10" onclick="add_to_favor('.$active[hash].');">
<i class="text-danger fa fa-heart"></i>
</a>
Javascript/JQuery:
<script type="text/javascript">
function add_to_favor(hash){
alert("pass it to your ajax: "+hash);
$.ajax({
cache: false,
type: 'POST',
url: ,
data: ,
success: function(data) {
$('#show_the_favor').html(data);
}
});
}
</script>