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,
);
Related
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);
}
});
});
I currently have some code which retrieves all pages submitted by the currently logged in author using the get_pages function. I am then passing the result to Javascript via Ajax. Everything works as expected, and I'm retrieving the pages that I should be.
My issue is, the object does not have any data for the tags, other custom taxonomies and attachments on this page.
Is there a way to attach this data to the returned object?
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxpages = get_pages($args);
echo json_encode($ajaxpages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
}
});
At this point, each entry will return something like:
ID: 100
comment_count: "0"
comment_status: "open"
filter: "raw"
guid: "https://example.com/?page_id=100"
menu_order: 0
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: "This is the post content"
post_content_filtered: ""
post_date: "2021-06-18 10:00:00"
post_date_gmt: "0000-00-00 00:00:00"
post_excerpt: "This is the excerpt"
post_mime_type: ""
post_modified: "2021-06-18 10:00:00"
post_modified_gmt: "0000-00-00 00:00:00"
post_name: ""
post_parent: 19
post_password: ""
post_status: "pending"
post_title: "Example page"
post_type: "page"
to_ping: ""
I would like it to also include data along the lines of:
tags: "example, test"
myCustomTaxonomy: "extra information, more data"
attachments: "https://example.com/wp-content/uploads/2021/06/myImage.png"
Is this possible?
In case it's useful, this is the solution I came up with. It certainly may not be efficient but it appears to suit my purposes at least.
What I ended up doing was populating a select list with each of the pages found in the first AJAX call. Selecting a page in this list then calls the second function which gets the various extra metadata for that page.
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxPages = get_pages($args);
echo json_encode($ajaxPages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
function get_ajax_meta()
{
$editId = $_POST['editId'];
$meta = [];
$editTags = get_the_tags($editId);
$editCustomTaxonomy1 = get_the_terms($editId, 'CustomTaxonomy1');
$editCustomTaxonomy2 = get_the_terms($editId, 'CustomTaxonomy2');
$media = get_attached_media('', $editId);
array_push($meta, (object)[
'tags' => $editTags,
'customTaxonomy1' => $customTaxonomy1,
'customTaxonomy1' => $customTaxonomy2,
'media' => $media
]);
echo json_encode($meta);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_meta', 'get_ajax_meta');
add_action('wp_ajax_nopriv_get_ajax_meta', 'get_ajax_meta');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
// populate the dropdown with the pages
if (pageList.length > 0) {
for (var i = 0; i < pageList.length; i++) {
$("select[name=edit-page]").append("<option value='" + pageList[i].ID + "'>" + pageList[i].post_title + "</option>");
}
}
}
});
$("body").on("change", "select[name=edit-page]", function () {
editId = $(this).val();
// get the meta information of the selected page (tags, custom taxonomies, attached files)
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { "editId": editId, action: "get_ajax_meta" },
success: function (response) {
pageMeta = response;
// get the tags
console.log(pageMeta[0].tags[i].name)
// get custom taxonomy 1 data
console.log(pageMeta[0].customTaxonomy1[i].name)
// get custom taxonomy 2 data
console.log(pageMeta[0].customTaxonomy2[i].name)
// get attached file data
if (Object.keys(pageMeta[0].media).length > 0) {
for (var i = 0; i < Object.keys(pageMeta[0].media).length; i++) {
console.log(pageMeta[0].media[Object.keys(pageMeta[i].media)[0]]);
}
}
}
});
});
I am trying to build a small program on a webpage that shows a drop-down list input type with the makes of cars (Ford and BMW in this case). Once a selection is made, the user clicks the submit button and below the form, a list of models specific to the make will appear in the results div.
I was provided with 4 files:
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="js/main.js"></script>
data.php:
<? php
function data() {
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
}
ajax.php:
<?php
require_once( 'data.php' );
$data = data();
$json_data = array();
And main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
},
});
}
$('#submit').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
How do I access the data in data.php from main.js? I'd appreciate a thorough explanation of possible. Thank you in advance.
Every thing is done seeing your provided code you have to just connect them but first you need to change the data.php file to the following
<?php
function data() {
return array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);}
then your ajax.php file to the following
<?php
require_once( 'data.php' );
$data = data();
$make = $_POST['make'];
// print_r($data);exit;
foreach($data as $car){
if(in_array($make,$car)){
$filtered[]=$car;
}
}
echo json_encode($filtered);
then change your main.js function to the following
$(document).ready(() => {
var run_ajax = function () {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: $("form").serialize(),
dataType: 'json',
beforeSend: function () {},
success: function (response) {
for (var key in
response) {
$("#results").append(" <div > Make: " + response[key]['make'] +
", Model:" + response[key]['model'] + " </div>");
}
},
});
}
$('#form').on('submit', function (e) {
e.preventDefault();
run_ajax();
});
});
hope that sorts out
EDIT
Actually, we have to send the select dropdown's selected make and filter out the cars with the same make to be responsed back and shown in the lower div have to change a few more things inside the ajax.php file
Your data() function must first return an array:
function data(){
$data = array('key'=>'value');
return $data;
}
Then echo or print() the json_encoded array:
$data = data();
echo json_encode($data);
Firstly your you dont need to define a function in your data.php file, since it is included in the ajax.php file, any variable there would be accessible
data.php:
<? php
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
the ajax.php file reads the data from data.php file filters the array and put the models of the selected make into a new array and echo as json string
ajax.php:
<?php
require_once('data.php');
$filtered_make = [];
$make = $_POST['make'];
foreach ($data as $car) {
if (strtolower($make) == strtolower($car['make'])) $filtered_make[] = $car['model'];
}
echo json_encode($filtered_make);
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="http://www.izivote.com/res/js/jquery.min.js"></script>
<script src="js/main.js"></script>
onsuccess, in the main.js file, the returned list of models in the json object from ajax.php is put in a list and displayed in the result container
main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
var formData = $('#form').serialize();
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
var resultHTML = "<ul>";
for(var index in response){
resultHTML += "<li>" + response[index] + "</li>";
}
resultHTML += "</ul>";
results.html(resultHTML);
},
});
}
$('#form').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
I hope this helps
return the data() as an array.
then encode the $data to json.
<?php
require_once( 'data.php' );
$data = data();
$json_data = json_encode(array());
and ajax:
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function( response ) {
console.log(response); // check the return result
$.each(response, function(key, val){
$("#results").append("<div>Make:"+key+" , Model:"+val+"</div>");
});
},
error: function (msg) {
alert("Error: check console");
console.log(msg);
}
});
not tested but hope it helps
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 am trying to insert data into the database using the codeigniter framework, i tried many solutions i couldn't find a problem ., can somebody suggest me the proper answer after adding $this->model->('contact_model'); my page is blank
my controller pages.php
<?php
class pages extends CI_Controller{
function index{
$this->load->model('contact_model');
$this->load->view('pages/index');
}
}
?>
enter code here
my view index.php
<form id="submit" action="<?php echo site_url();?>/models/contact_model">
<input type="text" id="name" >
<input type="email" id="email" >
<textarea placeholder="Message" id="message"></textarea>
<button type="button" id="submit1">Send</button>
<a id="ack"></a>
</form>
my model contact_model.php
<?php
class contact_model extends CI_Model{
function insert_entry()
{
$data = array(
'name' => 'name' ,
'email' => 'email' ,
'message' => 'message');
$this->db->insert('contactus', $data);
}
}
?>
custom.js file
$("#submit1").click(function){
$.post($("#submit").attr("action"),
$("#submit :input").serializeArray(),
function(data)
{
$("div#ack").html(data);
});
$("#submit1").submit(function(){
return false;
// window.location.href="/application/models/";
});
});
try this :3
this is ajax to post data in page to models ...
$.ajax({
url : "<?php echo base_url();?>/pages/",
type : 'POST',
data :{
"name":$("#nametags").val(),
//more in here
},
success : function(data) {
});
in controler
class pages extent CI_Controller{
function index() {}
function insert_data(){
//call function insert data
$data = array(
'name' => 'name' ,
'email' => 'email' ,
'message' => 'message');
$this->db->insert('contactus', $data);
}
}
your url is: /insert_data
in action url first parameter won't be model it would be controller name
like follwoing <?php echo site_url();?>/controller_name/method_name
in your case use <?php echo site_url();?>/pages/
$.ajax({
url : "<?php echo site_url();?>/pages/insert_data",
type : 'POST',
data :{"name":$("#name").val(),"email":$("#email").val(),"message":$("#message").val()},
success : function(data) {
$("div#ack").html(data);
});
and create a function in controller
function insert_data()
{
$this->load->model('contact_model');
$this->contact_model->insert_entry();
}