I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
Related
In the below code I have a dropdown (id-name) which populated from listplace.php'. Also made another ajax call which when the dropdown item is selected it lists the specific product fromdataprod.php`
Problem: when I click on the specific item from drop-down it does not trigger the Ajax event
I checked the dataprod.php it works correctly, but even after binding the change event with my dropdown box I m not getting the result. Please help..
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<script>
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
</script>
<?php } ?>
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You need to pass the selected value in the ajax call.
change this line from
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
to
var name1 = this.value;
$.ajax ({
data: {name1: name1},
type: 'POST',
HTML:
you can store the values in hidden field like:
<input type='hidden' name='name1' id='name1' value='<?= $_GET["name1"] ?>'>
Javascript:
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = $('#name1').val();
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'
I have an ajax popup box (pasted below) that works, but I don't know how to close it. I tried adding .dialog('close') to the success line like this - $('#dialog-ajax').html(data).dialog('close');
That didn't work. I also tried replacing that line with the following:
if (data.success) {
App.success(data.success);
$('#dialog-ajax').dialog('close');
}
Again, no go. Thanks for your help.
Here is the html code:
<?php if ($this->details['changeLink'] && !$this->header_part) { ?>
<label class="shipping">{{Tracking number}}:</label>
<input id="tracking" class="fleft small" type="text" value="<?php echo $this->details['purchase']->tracking ?>" />
<button id="change" class="small-button red-button fleft">{{Change}} </button>
<?php } ?>
Here is the javascript:
<script type="text/javascript">
$(document).ready(function() {
if ($.isFunction($.fn.selectbox)) {
$('select').selectbox();
}
<?php if ($this->details['changeLink']) { ?>
$('#change').click(function() {
$.ajax({
url: '<?php echo $this->details['changeLink'] ?>',
type: 'POST',
data: {
id: <?php echo $this->details['purchase']->id ?>,
status: $('#shipping-status').val(),
tracking: $('#tracking').val(),
company: $('#company').val()
},
beforeSend: function() {
loading.loadFancy($('#dialog-ajax'));
},
success: function(data) {
$('#dialog-ajax').html(data);
}
});
return false;
});
<?php if ($this->successfu_edite) { ?>
App.success('{{Purchase is successfully changed!}}');
<?php } ?>
<?php } ?>
});
</script>
well i'm not sure if it may work or not but logically it should
try this
if (data.success) {
/*when the user click outside the pop up*/
$("#dialog-ajax").dialog('destroy').remove();
}
Your ajax call has semantic errors. Add the dataType attribute and change method attribute and your $.ajax call to the following:
<script type="text/javascript">
$(document).ready(function() {
if ($.isFunction($.fn.selectbox)) {
$('select').selectbox();
}
<?php if ($this->details['changeLink']) { ?>
$('#change').click(function() {
$.ajax({
url: '<?php echo $this->details['changeLink'] ?>',
//change method and dataType to reflect the following
method: 'POST',
dataType: 'json',
data: {
id: <?php echo $this->details['purchase']->id ?>,
status: $('#shipping-status').val(),
tracking: $('#tracking').val(),
company: $('#company').val()
},
beforeSend: function() {
loading.loadFancy($('#dialog-ajax'));
},
success: function(data) {
if (data.success) {
$("#dialog-ajax").fadeOut(900,'swing',function(){
$(this).css("display","none");
});
}
}
});
return false;
});
<?php if ($this->successfu_edite) { ?>
App.success('{{Purchase is successfully changed!}}');
<?php } ?>
<?php } ?>
});
</script>
what should I do if i can't upload an image in a form it successfully created but the file is shows 0 not the upload file. please help me thanks in advance!
script in view where I can update and add a single form with upload
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#dataTable2').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('about/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add About US'); // Set Title to Bootstrap modal title
}
function edit_person(about_id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('about/ajax_edit/')?>/" + about_id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="about_id"]').val(data.about_id);
$('[name="about_details"]').val(data.about_details);
$('[name="images"]').val(data.image);
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('about/ajax_add')?>";
}
else
{
url = "<?php echo site_url('about/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#myModal').modal('hide');
reload_table();
if (empty($_FILES['image'])) {
return FALSE;
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_person(about_id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('about/ajax_delete')?>/"+about_id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
This is my form
<div class="modal-body form">
<form action="#" id="form">
<input type="hidden" value="" name="about_id"/>
<!-- <div class="form-group has-feedback ">
<label>Date</label>
<input type="date" id="date" class="form-control" input-sm placeholder="Date"/>
</div>-->
<div class="form-group has-feedback">
<label>About Details</label>
<input type="text" id="title" name="about_details" class="form-control" input-sm placeholder="About Details"/>
</div>
<!-- Description -->
<div class="form-group has-feedback">
<label>Image</label>
<?php $attrib = array('type'=>'text','name'=>'image','class'=>'form-control','id'=>'file'); ?>
<?php echo form_upload( $attrib,set_value('image')); ?>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-success" aria-hidden="true" onclick="save()">Save</button>
my controller for add and update
public function ajax_add()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$data = array(
'about_details' => $this->input->post('about_details'),
'image' => $this->upload->do_upload('image'),
);
$this->person->update(array('about_id' => $this->input->post('about_id')), $data);
echo json_encode(array("status" => TRUE));
}
What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:
$('#uploadimg').ajaxForm({
//uploadimg is my form id
dataType: 'json',
success: processJson
});
function processJson(data) {
if(data.msg=="success"){
alert('Upload is successful.');
}
else{
alert('Upload couldn't be completed.');
}
}
The form would be
<form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">
On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.
public function uploadImage(){
//$id = $this->session->userdata('uid');
$config[ 'upload_path' ] = UPLOAD_DIR.'/newsletter/0';
$config[ 'allowed_types' ] = 'gif|jpg|png';
$config[ 'max_size' ] = '1500';
$config[ 'max_width' ] = '1000';
$config[ 'max_height' ] = '1500';
$image_name = "files";
$this->load->library( 'upload', $config );
if ( $this->upload->do_upload( $image_name ) ) {
$upload_data = $this->upload->data();
if(!empty($upload_data)){
$arg = array(
'name' => $upload_data[ 'file_name' ]
);
$this->modelName->insert($arg );
$data['msg']="success";
}
else{
$data['errmsg']="Couldnot upload the file!";
}
}
else{
$data['errmsg'] =$this->upload->display_errors();
}
echo json_encode($data);
}
Now this will trigger the processJson function in the script. And the upload shows the result.
You can find the javascript file on jquery.form.js.
I hope it works out for you.
I am adding items into cart with ajax in codeigniter.
My problem is that the cart got updated when i refreshes page. I have ajaxify it to prevent page refresh. but its not happening. My code is right and there is no error. but still its not working.
my controller code is
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
}
my view code is
function insert()
{
var item_id=$("#item_id").val();
var item_name=$("#item_name").val();
var item_price=$("#item_price").val();
var dataString = "&item_id=" + item_id + "&item_name=" + item_name + "&item_price=" + item_price;
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function()
{
alert('hello');
}
});
}
<form id="form">
<input type="hidden" id="item_id" name="item_id" value={{data.id}}> <input type="hidden" id="item_name" name="item_name" value={{data.item_name}}> <input type="hidden" id="item_price" name="item_price" value={{data.price}}>
<p>Add to Cart</p>
</form>
the concept of the cart is to add the cart array in a session
so the php will not feel the changes until you reload the page
so you have to append the table with javascrip
// in controller
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
echo json_encode($data) ;
}
// in your javascript
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function(data)
{
// just replace YOUR-TABLE-ID with table id
//and complete the tr you want to append
var tr = "<tr><td>"+data.id+"</td><td>"+data.name+"</td></tr>";
$("#YOUR-TABLE-ID tr:last").after(tr);
}
});
What is happening when you try to use $item_id instead radnom number:
$data = array(
'id' => $item_id,
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);