Unable to update database with ajax in codeigniter - javascript

I have passed an array tree from controller to view and I am using a helper for recurssion to display it in the form of unordered lists. I have a button with each list item to move one step up. My view div is like this:
<div id="div">
<?php
$ordering = count($trees[$grp->id]);
?>
<a href="javascript:Swapit('swapper-first','swap')" onClick="showIFrame('<?php echo site_url('service_group_services/edit/0_' . $ordering . '_' . $grp->id); ?>');">
<button type="button" class="btn btn-default btn-xs btn-label-left">
<i class="fa fa-plus"></i>
</button>
</a>
<?php
display_tree($trees[$grp->id], $grp->id);
?>
</div>
<?php endforeach; ?>
here, display_tree is a helper:
<?php function display_tree($array, $grp) {
foreach ($array as $value): {
$ordering = 0;
if (isset($value->childs[0])) {
$val = $value->childs;
$ordering = count($val);
}
echo "\n<ul>";
echo "\n<li>";
if($value->type != 'SERVICE') {
echo '<span> <i class="fa fa-plus"></i></span>';
}
if($value->ordering != 0) {
echo '<span> <i class="fa fa-sort-up"></i></span>';
}
echo '<span> <i class="fa fa-times"></i></span>'. $value->name .'</li>';
if (isset($value->childs[0])){
$val = $value->childs;
display_tree($val, $grp);
}
echo '</ul>';
}
endforeach;
}
?>`
controller function:
function move_up(){
$parent = $this->input->post('service_parent');
$ordering = $this->input->post('ordering');
$group = $this->input->post('service_group');
$service = $this->input->post('service');
$s_p = $this->session->userdata('service_provider');
$this->Mdl_service_group_services->up($s_p, $parent, $group, $ordering);
$this->Mdl_service_group_services->up1($s_p, $service, $parent, $group, $ordering);
}
n model is:
function up($s_p, $parent, $group, $ordering) {
$data = array(
'ordering' => $ordering
);
$this->db->where('service_provider =', $s_p);
$this->db->where('service_group =', $group);
$this->db->where('service_parent =', $parent);
$this->db->where('ordering =', --$ordering);
$this->db->set($data);
$this->db->update($this->_table_name);
}
function up1($s_p, $service, $parent, $group, $ordering) {
$var = array(
'ordering' => --$ordering
);
$this->db->where('service_provider =', $s_p);
$this->db->where('service_group =', $group);
$this->db->where('service_parent =', $parent);
$this->db->where('service =', $service);
$this->db->set($var);
$this->db->update($this->_table_name);
}
Now I am trying to update the ordering column of database table with ajax.
Ajax code is:
var controller = 'service_group_services';
var base_url = '<?php echo site_url(); //you have to load the "url_helper" to use this function ?>';
function load_data_ajax(parent, ordering, group, service){
$.ajax({
'url' : base_url + controller + '/move_up',
'type' : 'POST', //the way you want to send data to your URL
'data' : 'service_parent='+parent+'ordering='+ordering+'service_group='+group+'service='+service,
'success' : function(data){ //probably this request will return anything, it'll be put in var "data"
var div = $('#div'); //jquery selector (get element by id)
if(data){
div.html(data);
}
}
});
}
But when i click on up button, nothing is happening. Please help me.

There is an problem in your AJAX request. You forgot to add &seprator between each parameters of the data you want to send :
function load_data_ajax(parent, ordering, group, service){
$.ajax({
...
'data' : 'service_parent='+parent+'&ordering='+ordering+'&service_group='+group+'&service='+service,
...
});
}

Related

Ajax : response value is not the same as in the php file

I am currently working on a Wordpress project and I have a issue during an ajax request:
On my view, I have this button for displaying more articles on my page :
<input type="hidden" name="nbPages" value="<?php echo $nb_pages;?>">
<input type="hidden" name="pageActive" value="1">
<input type="hidden" name="termSlug" value="<?php echo $term_query->slug;?>">
.
.
.
<div class="product-bottom">
<img src="<?php echo get_template_directory_uri();?>/img/ajax-loader.gif" alt="" id="ajax-loader" style="display:none;">
<button class="btn btn-site-1" id="loadmore_bt">See more</button>
</div>
On my js file, I have this part that is called when the button is used
add_action('wp_ajax_ajax_loadmore', 'ajax_loadmore');
$(function () {
'use strict';
//AJAX LOAD MORE PRODUCTS
jQuery('body').on('click', '#loadmore_bt', function (e) {
e.preventDefault();
$('#ajax-loader').fadeIn(500);
var nbPages = jQuery('input[name="nbPages"]').val();
var activePage = jQuery('input[name="pageActive"]').val();
var termSlug = jQuery('input[name="termSlug"]').val();
jQuery.ajax({
type: 'POST',
dataType: "JSON",
data: {
'action': 'ajax_loadmore',
'nbPages': nbPages,
'activePage': activePage,
'termSlug': termSlug
},
url : ajaxurl,
success : function(response){
console.log('cool!');
console.log(response.newPageToDisplay);
}
})
In function.php , I have this function which is called :
function ajax_loadmore(){
.
.
// set query arg as $args_products
.
.
$products = new WP_Query($args_products);
$rendering = '';
if ($products->have_posts()) {
foreach ($products->posts as $key => $prod) {
$rendering .= "
<div>
<h2 class="card-title main-title-2">' . $prod->post_title . '</h2>
<p class="card-subtitle">' . get_field('reference', $prod->ID) . '</p>
</div>
<div class="card-txt">' . get_field('desriptif_court', $prod->ID) . '</div>
<button class="btn btn-site-1">More info</button>
</div>";
}
$json = array(
'reponse' => 'success',
'newPageToDisplay' => $rendering,
'pageloaded' => $pageToLoad,
'activePage' => $activePage,
);
echo json_encode($json);
}else{
echo "error";
echo json_encode(array(
'reponse' => $reponse
));
}
die();
}
My issue is: $rendering has not the same value than in the js response (as response.newPageToDisplay).
For exemple, on the first element of $rendering is $prod->post_title = 'PA80MP' , while the first element of response.newPageToDisplay is 'PA95'. Both are indeed existing values in my database.
TLDR : Ajax doesn't have the same value of variables as in the php file function that it calls.
Hope I explain well my problem ...thank you for helping!

Pass variable to wordpress function and refresh it using ajax

I'm building a shopping page that list all the stores. I've created a sidebar with all the categories and a list with pagination. This list is generated by a wordpress function in my theme-functions.php, but when I click in any category, I'm redirected to another page (to http://<domain>/store from http://<domain>/category). So I created a JavaScript function to prevent the link action using preventDefault and get his href value and set it as variable to pass it to the function via Ajax.
My question is: there is a way to pass this variable and refresh the wordpress function on the same page to show this list?
Code below:
Wordpress theme-function.php
function storeSingle() {
$catUrl = $_POST['catUrl'];
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'lojas' ,
'posts_per_page' => 5,
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'category_name' => $catUrl
);
/* Added $paged variable */
$exec = new WP_Query($args);
if($exec->have_posts()):
echo '<ul class="single-store">';
while($exec->have_posts()):
$exec->the_post();
$categories = get_the_category($post->ID);
echo "<li class='store-box'>";
echo '<a href=" '. get_the_permalink() .' ">';
echo '<h1>';
echo the_title();
echo '</h1>';
echo "</a>";
echo '<div class="store-info-box">';
echo '<span>';
echo '<i class="fa fa-map-marker" aria-hidden="true"></i>';
echo the_field('localizacao');
echo '</span>';
echo '<span>';
echo $categories[0]->name;
echo '</span>';
echo '</div>';
echo "</li>";
endwhile;
echo '</ul>';
if (function_exists(custom_pagination)) {
custom_pagination($exec->max_num_pages,"",$paged);
}
endif;
}
add_action('wp_ajax_catUrl', 'catUrl');
add_action('wp_ajax_nopriv_catUrl', 'catUrl');
JavaScript function
$('.cat-item').on('click', 'a', function(e){
e.preventDefault();
var catUrl = this.href;
catUrl = catUrl.split('/');
$.ajax({
type: "POST",
url: 'http://localhost/asv/shopping/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
action: catUrl,
catUrl: catUrl[5]
},
success: function(data){
response(data),
console.log('test' + data);
}
});
});
I've searched this a lot but I didn't find out how to use ajax in wordpress properly.
if you are getting results in you console.log('test' + data); seems like you just need to display this results back in your HTML container by replacing the current content with your ajax response.

Moving data from PHP then HTML then jQuery then back to PHP

working around with this code, but can not find what is wrong.
the following code is as follows:
$_POST from php filling attributes
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>
<a>Buy Now</a>
</button>
after that i am calling final-buy-now-btn which i expect to be making the error, but i couldnt find it:
$('.final-buy-now-btn').click(function(event){
var book = $(this).attr("book");
var productId = $(this).attr("productId");
if( book === "christmas" ){
var country = $(this).attr("country");
var city = $(this).attr("city");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: { 'action' : 'add_item_meta_data_to_cart_item',
'book' : book, 'productId' : productId,
'country' : country,'city' : city},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
if(book === "birthday"){
var month = $(this).attr("month");
var bday = $(this).attr("bday");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: {
'action' : 'add_item_meta_data_to_cart_item',
'book' : book,'productId' : productId,
'month' : month,'bday' : bday},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
});
then finally from the action that is called, which is my php function,
for birthday the values are getting returned but for christmas nothing is getting returned.
function add_item_meta_data_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
$item_meta_data = filter_input( INPUT_POST, 'item_meta_data' );
$item_meta_data = json_decode($item_meta_data);
echo "<pre>";
print_r($item_meta_data);
echo "</pre>";
The short answer is that you have typo:
if( book === "chritmas" ){
You forgot letter s in JavaScript code
Other things
You should:
Using input type hidden instead of attributes or replace attributes to data-city, data-book
Remove attribute <a> in button
looking at your code, it doesn't appear that you are closing the button tag. try this snippet with the extra > after the month property.
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>>
<a>Buy Now</a>
</button>
if its still not working, run the page through https://validator.w3.org/ to look at the html output and see if they are any other syntax errors.
as rafael mentioned: data-field is the best practice for naming properties in tags.

How to use ajax add to cart for related products magento

I'm trying to use ajax add to the cart in related products but I don't know how to get link to the each related products?
I would like to use ajax and not be redirected to the cart page when I click add to the cart. For the main product this is working well. But for related is adding the main product or adding related product but redirect me to the cart.
<?php endif; ?>
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(350); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"/>
</a>
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
Can I use
productAddToCartForm.submit(this)
But what to pass inside submit?
This is the add to cart code
<script type="text/javascript">
//<![CDATA[
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
if (!url) {
url = jQuery('#product_addtocart_form').attr('action');
}
url = url.replace("checkout/cart","ajaxcart/index"); // New Code
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
jQuery('#loading-mask').show();
try {
jQuery.ajax({
url : url,
dataType : 'json',
type : 'post',
data : data,
success : function(data) {
jQuery('#loading-mask').hide();
if(data.status == 'ERROR'){
alert(data.message);
}else{
if(jQuery('.top-links .right-links')){
jQuery('.top-links .right-links').replaceWith(data.toplink);
}
jQuery('#after-loading-success-message').show();
}
}
});
} catch (e) {
}
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(productAddToCartForm);
//]]>
</script>
You can serialize the data from product form and send it to server via AJAX request (
via Prototype | via jQuery | via plain JS).

Ajax in codeigniter for changing only div in view

Hello, I want to be able to change only part of the div in my view i
have tried to write the codes but they are not working perfectly. how
it works is when i click the button it suppose to sent the value to a
js then using js to sent data to the controller.
SCRIPT:
function getValue(datas){
alert(datas) ;
var mydiv = datas;
$.Ajax({
type:"post",
url:<?php echo base_url('/mama/load_view/');?>
data:{"mydiv":mydiv},
success:function(data){
$('#mang_server').html(data);
}
});
}
PHP:
foreach($student_prof as $row){
$gen = "GeneralInformation";
echo '<input type="submit" value="GeneralInformation" class="btn btn-primary active" name="general" id="submit" onclick="getValue("'.$gen.'")">';
echo '</div>';
}
The Controller code
public function load_view(){
$data1 = $this->input->post('mydiv');
if($data1 == "GeneralInformation"){
$this->load->view('student/profile_view');
}
else {
$this->load->view('student/profile_view');
}
}
use jquery load function.
function getValue(datas){
var mydiv = datas;
url = "<?php echo base_url('/mama/load_view');?>/" + mydiv;
$('#mang_server').load(url);
}
Controller
public function load_view($data1){
if($data1 == "GeneralInformation"){
$this->load->view('student/profile_view');
}
else {
$this->load->view('student/profile_view');
}
}
to load your view in div using ajax use echo
echo $this->load->view('student/profile_view', $data1, TRUE);
public function load_view(){
$data1 = $this->input->post('mydiv');
if($data1 == "GeneralInformation"){
echo $this->load->view('student/profile_view', $data1, TRUE);
}
else {
echo $this->load->view('student/profile_view', $data1, TRUE);
}
}
change you php code to this
foreach($student_prof as $row){
$gen = "GeneralInformation";
$output .='<div>';
$output .= '<input type="submit" value="GeneralInformation" class="btn btn-primary active" name="general" id="submit" onclick="getValue("'.$gen.'")">';
$output .= '</div>';
}
echo $output;

Categories