How to refresh content of page after adding item with AJAX - javascript

I have some url which i add some item to another page (cart page) but by refreshing page and it works fine, now i tried to do it with Ajax, so i created an ajax function to call this URL it works and it adds my item.
Now the problem is i have to reload the other page (cart page) to see the product. So how to do to refresh this page after adding the item, i mean after calling this URL.
The Url : <?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>
cart.phtml
...
<div class="row">
<div class="col-md-6">
<div class="product-qty">
<div class="custom-qty">
<div class="btn-plus">
<button type="button" class="reduced items" onclick="minusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-minus"></i>
</button>
<input name="qty" id="qty-<?php echo $_product->getId()?>" maxlength="12" value="1" title="Qté" class="input-text qty" type="text">
<button type="button" class="increase items" onclick="plusQty('<?php echo $_product->getId() ?>')">
<i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<?php $params = array('qty'=>2) // the input value ?>
<div class="col-md-6">
<button type="button" title="<?php echo $this->__('Add') ?>" class="button btn-cart pull-left-none" onclick="addToCartAjax('<?php echo Mage::helper('checkout/cart')->getAddUrl($_product, $params); ?>')" >
<span><span><?php echo $this->__('Add') ?></span></span>
</button>
</div>
</div>
//JS PART
<script type="text/javascript">
function addToCartAjax(addUrl) {
jQuery.ajax ({
url: addUrl,
type : 'GET',
})
}
</script>
EDIT:
Content of cart.phtml
<div class="row">
<div class="col-main col-lg-12">
<div class="cart">
<fieldset>
...
<tbody>
<tr class="first odd"><td>Item1</td></tr>
<tr class="last even"><td>Item2</td></tr>
</tbody>
...
</fieldset>
</div>
</div>
</div>
EDIT2:
Action controller
public function addAction()
{
if (!$this->_validateFormKey()) {
$this->_goBack();
return;
}
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$this->_goBack();
return;
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()) {
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}

I assume when you add an item to the cart you get some kind of response from your server about current items of the cart, if not you have to implement that on the server side first
add this to your function :
function addToCartAjax(addUrl){
$.ajax({
url: addUrl,
type: 'GET',
})
.done(function(response ) {
//response - this is the response from the server
});
}
I don't know exactly what your server returns if it is html than in .done closure do this :
.done(function(response ) {
// response - this is the response from the server
$('.YourCartContainer').html(response);
});
so if your server returns an html snippet that contains your cart items than you should insert in as html into your cart div container , but if the server returns a Json response with items than you have to loop through them with jquery and format appropriately here an example , however again I don't know what your server returns so just apply the technique :
.done(function(response ) {
// response - this is the response from the server
var htmlResult = '';
$.each(response, function( item ) {
htmlResult += '<p>'+ item.name + '</p><br>'
});
$('.YourCartContainer').html(htmlResult);
});
So here I looped through the json and created some simple html where you get all the item names that are inside the cart, hope this helped ! if You need more info regarding your case specifically than please post what your server response looks like !!

Related

How to pass the id from url in php function without refreshing the page?

I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})

jquery ajax getting variable from one function to another php

So basically to give a brief before exploring in to the code I give below.
Basically what I'm trying to do is, I have a modal in one of my php page as below. I'm trying to show the model from a php function "fetch_assignment_history" given below. There is a button in which we can add users to the assignment, and the button onclick event(onClick="assign(this.dataset.id)") call function passing the id from the php function to JS function.
So when the user click the button the JS function shows the modal as well as get the assignment id in the function. This assignment id is set (through JS) to data attribute of multiple select dropdown in the modal.
Now the point where I'm stuck is, a setinterval constantly fetch the assigned users. This basically collect from mysql database of users who were added to the assignment (comma delimitted id's).
When the modal is opened I want the previously assigned users to be selected in the multiple select (as per data in mysql) as default. For this I want to get the id passed from the onclick event
My HTML part (modal)
<div id="assignee" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Assignment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
<label style="color:#333D79FF; font-size:15px;">Add Users <span class="text-danger">*</span></label>
<div>
<select class="select2_multiple form-control" multiple="multiple" id="userslist" name="userslist[]" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>
<?php
My PHP CODE TO PULL OUT DATA FROM MYSQL DB
?>
<option value="<?php echo $id; ?>" data-useravatar="<?php echo $avatar; ?>" data-usertitle="<?php echo $firstname;echo " ";echo $lastname; ?>" data-role="<?php echo $role; ?>" data-assignment=""><?php echo $firstname;echo " ";echo $lastname; ?></option>
<?php } ?>
</select>
</div>
<div id="usersfetch"></div>
</div>
</div>
</div>
</div>
</div>
My PHP
1. function to fetch assignment history.
Below button onclick goes to JS and shows modal. and also pass id
function fetch_assignment_history($connect)
{
$query = "
SELECT * FROM assignment
WHERE id = '".$_SESSION['id']."'
ORDER BY id ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
$user_name = '';
$dynamic_background = '';
$message = '';
$assignmentname = $row["assignmentname"];
$name = $row["name"];
$id = $row['id'];
$output .= '
<div class="x_panel" style=" font-size:14px;">
<span class="controlbuttons">
<button class="btn btn-round" data-id="'.$id.'" onClick="assign(this.dataset.id)"><i class="material-icons" title="Assign">person_add</i></button>
</span>
</div>
';
}
$output .= '</ul>';
return $output;
}
function to assigned user history
function fetch_assigned_user_history($connect)
{
some php queries
}
My JS
I want the assignid from function assign(assignid) to be called from function fetch_assigned_user_history(). How do I accomplish this??????
setInterval(function(){
fetch_assigned_user_history();
}, 1000);
function assign(assignid)
{
var assignid = assignid;
$("#assignee").modal("show");
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
var getid = ;// I need to get the ID from the previous function from onclick event function assign(assignid)
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
Hope I'm clear with my question. Appreciate for an advise to fix.
To summarise, the basic question is how to call variable of one JS function in to another (in this example id's) so that i can get the list of users in that assignment? Also how to get it selected by default the Multiple select with database values.
You already stored 'assignid' in data-* attribute, you can just retrieve it when you need it
function assign(assignid) {
var assignid = assignid;
$("#assignee").modal("show");
// You already store your assignid at here
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
// Now you just need to retrieve it
var getid = $('#userslist').data("assignment");
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}

How to create repeatable fields in wordpress in my plugin setting page

This is my HTML code where I'm creating a simple HTML form in my plugin settings page:
<?php
/**
* Adds a submenu page under a custom post type parent.
*/
function books_register_ref_page()
{
add_submenu_page('edit.php?post_type=fscf_contact', __('Setting', 'fscf') , __('Settings', 'fscf') , 'manage_options', 'setting-fscf-contacts', 'fscf_contact_page_callback');
// call register settings function
add_action('admin_init', 'register_my_fscf_contact_settings');
}
function register_my_fscf_contact_settings()
{
// register our settings
register_setting('fscf-plugin-settings-group', 'fscf_field_1');
}
/**
* Display callback for the submenu page.
*/
function fscf_contact_page_callback()
{
?>
<div class="wrap">
<h1><?php
_e('Contact Form Setting', 'textdomain'); ?></h1> <hr>
<div class="wrap">
<form method="post" action="" id="myform">
<?php
settings_fields('fscf-plugin-settings-group'); ?>
<?php
do_settings_sections('fscf-plugin-settings-group'); ?>
<table class="form-table" id="p_scents">
<tr valign="top">
<th scope="row">New Option Name</th>
<td> <p>
<label for="p_scnts">
<input type="text" name="fscf_field_1" id="fscf_field_1" value="<?php
echo esc_attr(get_option('fscf_field_1')); ?>" /> <input type="button" id="addScnt" name="" value="+">
</label>
</p> </td>
</tr>
</table>
<?php
$other_attributes = array(
'id' => 'submit_repeatable_fields'
);
submit_button("Submit", "submit", "submit", false, $other_attributes); ?>
<span id="fscf_error"></span>
</form>
</div>
</div>
<?php
}
add_action('init', 'books_register_ref_page');
This is my .js code where I'm repeating <tr> in HTML form:
jQuery(document).ready(function() {
var scntDiv = jQuery('#p_scents');
var i = jQuery('#p_scents p').size() + 1;
jQuery('#addScnt').live('click', function() {
jQuery('<tr valign="top"><th scope="row">New Option Name</th><td> <p><label for="p_scnts"><input type="text" name="fscf_field_' + i +'" id="fscf_field_' + i +'" value="" /> Remove</p> </td></tr>').appendTo(scntDiv);
i++;
return false;
});
jQuery('#remScnt').live('click', function() {
if( i > 2 ) {
jQuery(this).parents('#p_scents tr').remove();
i--;
}
return false;
});
// Making Ajax Request for settings
jQuery("#myform").submit(function(e) {
e.preventDefault();
var formdata = jQuery("#myform input[type='text']").serializeArray();
var numberflds = jQuery("#myform input[type='text']").size();
var data = {
'action' : 'fscf_create_repeatable_fields',
'fullform':jQuery("#myform input[type='text']").serializeArray(),
'fields': numberflds,
//nonce : security
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_obj.ajax_url, data, function(response) {
console.log(response);
jQuery("#fscf_error").html(response);
});
});
});
Here is my php code where I want to save fields which I had repeated in .js file but I'm unable to save data:
function fscf_create_repeatable_fields(){
$mydata = $_POST['fullform'];
$fields = $_POST['fields'];
//$i=0;
foreach ($_POST['fullform'] as $form) {
register_setting( 'fscf-plugin-settings-group', $form['name']);
//$i++;
}
echo "Field Created.";
wp_die();
}
add_action( 'wp_ajax_nopriv_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
add_action( 'wp_ajax_fscf_create_repeatable_fields', 'fscf_create_repeatable_fields' );
So, the problem is I can't save repeatable fields in my plugin page. What mistake I'm doing?

inserting an ajax response into div

First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>

Codeigniter: Retrieving data on button click with Ajax

I have a simple webpage which generates a random quote from my database upon refreshing the page. I wish to implement some AJAX and JQuery in order to generate quotes via the button rather than having to refresh the page. I have done some research but I am not sure how to implement this in Codeigniter. My current code is below...
Page controller:
public function index() {
$this->load->model('quote_model', '', TRUE);
$data['quotes'] = $this->quote_model->getRandom();
$this->load->view('home', $data);
}
The view:
<?php include ('layout/header.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 quote-holder">
<img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
<br>
<blockquote class="text-center">
<p><?php echo $quotes[0]['quote']; ?></p>
<footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
</blockquote>
<button type="button" class="btn btn-default center-block">Generate quote</button>
</div>
</div>
<?php include ('layout/footer.php'); ?>
Here is the function in the model I am retrieving the data from:
function getRandom() {
$query = $this->db->query("
SELECT * FROM quotes, characters, series
WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
ORDER BY rand()
LIMIT 1
");
return $query->result_array();
}
Should I simply be using something like this?
$("button").click(function(){
$.get( "Page/index", function( data ) {
//output data to page element...
}
});
getI would do something like: controller:
public function callme()
{
$this->load->model('quote_model);
$data['quotes'] = $this->quote_model->getRandom();
}
Then in my footer:
condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
url: url
})
But meh, im bad at programming and even worse at jquery :D
Make hidden input for offset
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>
Now Your Ajax Call
function showmore(){
$.ajax({
url:my_controller/showmore,
data:{
offset :$('#offset').val()
},
type:json,
success :function(data){
$('#show-more').prepand(data.view)
$('#offset').val(data.offset)
}
})
}
Your Controller
function showmore(){
$limit = '10';
$offset = $this->input->get('offset');
$result = $this->yourmodel->getdata($offset,$limit);
$data['view'] = $result;
$data['offset'] =$offset +10;
echo json_encode($data);
}
Your Model
$query = $this->db->get('your_table', $limit, $offset);
$data=$query->result_array();
return $data;

Categories