Creating a button with ajax and making it run php

0

I have a button that every time I click my page it updates.

 $btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
 $btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
 $btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';

My cart.php is the entire system in my order cart. In my checkout.php is where I add or throw selected items. and I've inserted my function cart(); into it.

I wanted to use ajax to make my button not update my page.

My script of cart.php .

if(isset($_GET['plus'])){
$_SESSION['product_'.$_GET['plus']]+=1;
if($_SESSION['product_'.$_GET['plus']] < 1){
        header('Location: checkout.php');

}else{

    header('Location: checkout.php');
    }
}

if(isset($_GET['remove'])){
$_SESSION['product_'.$_GET['remove']]--;
if($_SESSION['product_'.$_GET['remove']] < 1){
        header('Location: checkout.php');

}else{

    header('Location: checkout.php');
    }

}

if(isset($_GET['delete'])){
    $_SESSION['product_'.$_GET['delete']] = '0';
    header('Location: checkout.php');
}

My buttons are inside a foreach loop of my function cart() ;

function cart(){
    global $conn;


    $fabric_options = '';
    $query2 = "SELECT * FROM almofadas";
    $result = mysqli_query($conn,$query2);
    while($rows = mysqli_fetch_assoc($result)){

    $tecido=$rows['tecido'];
    $id_price=$rows['id_price'];
    $fabric_options .= "<option value=''.$id_price.''>{$rows['tecido']}</option>";

    }

    $s50='50';
    $s45='45';
  if(isset($t50)){
   $_SESSION['selected']='selected';
  }

    foreach ($_SESSION as $name => $value) {
     if($value > 0){
      if(substr($name, 0, 8 ) == "product_"){
       $length = strlen($name) -8;
       $item_id = substr($name,8 , $length);
     $query = "SELECT * 
               FROM gallery2 
               WHERE gallery2.id =".escape_string($item_id). "";
      $run_item = mysqli_query($conn,$query);
       while($rows = mysqli_fetch_assoc($run_item)){ 
             $vari   = $rows['variante'];
             $num    = $rows['title'];
             $id     = $rows['id'];

             $btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
             $btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
             $btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';
              if($rows['variante'] < 1){
              $vari="";
              }else{
              $vari = "-".$rows['variante'];
              }
              $product = '
              <td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
              <td>'.$num.''.$vari.'</td>
              <td style="width:15%;">
              <select id="fabric" class="select form-control selectpicker" required="" onchange="saveChoice()" >

              '. $fabric_options . '  

              </select>
              </td>
              <td>
              <select  id="size" class="select form-control selectpicker" required style="width:80%;" onchange="saveChoice()" >
              <option value="'.$s50.'">50x50</option>
              <option value="'.$s45.'">45x45</option>
              </select>
              </td>
              <td>'.$value.'</td>
              <td>R$</td>
              <td>sub.total</td>
              <td> 
              '.$btn_add.' '.$btn_remove.' '.$btn_delete.'
               </td>
               </tr>';
               echo $product;
                } 
            }
        }
    }
}
    
asked by anonymous 26.09.2016 / 15:32

2 answers

0

I've tried to better organize the structure of your files so you can understand how ajax usage works.

cart.php

The first thing to do is to add some references to your action buttons in the loop of your cart function, such as the action type of the data_action button and the product_id :

$btn_add    ='<a class="btn btn-success actions" data_action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove ='<a class="btn btn-warning actions" data_action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
$btn_delete ='<a class="btn btn-default actions" data_action="delete" product_id="'.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';

checkout.php

Next, add the ajax script:

<script type="text/javascript">
 $('.actions').click(function(e){
    e.preventDefault();
    var action = $(this).attr('data_action'); //identifica a ação do botão
    var id = $(this).attr('product_id'); //id do produto
    $.ajax({
        url: 'cart_functions.php',
        type : 'GET', 
        data: {action:action,prod_id:id}, 
        dataType: 'json',
        success: function(data){
            //Quando a ação for PLUS 
            if(data.hasOwnProperty('plus')){
                if(data.plus == 'success'){
                    //em caso de sucesso
                } else {
                    //em caso de erro
                }
            }
            //Quando a ação for REMOVE 
            if(data.hasOwnProperty('remove')){
                if(data.remove == 'success'){
                    //em caso de sucesso
                } else {
                    //em caso de erro
                }
            }
            //Quando a ação for DELETE 
            if(data.hasOwnProperty('delete')){
                if(data.delete == 'success'){
                    //em caso de sucesso
                } else {
                    //em caso de erro
                }
            }
        }
    });
});
</script>

cart_functions.php

This php file will be responsible for receiving and processing the ajax request.

header('Content-Type: application/json');

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $prod   = $_GET['prod_id'];
    switch ($action) {
        case 'add':
            echo add_prod($prod);
        break;
        case 'plus':
            echo plus_prod($prod);
        break;
        case 'remove':
            echo remove_prod($prod);
        break;
        case 'delete':
            echo delete_prod($prod);
        break;
        default:
            echo json_encode(['error'=>'error']);
        break;
    }
}

function add_prod($item){
    //sua função para add
    return json_encode(['add'=>'success']);
}
function plus_prod($item){
    //sua função para plus
    return json_encode(['plus'=>'success']);
}
function remove_prod($item){
    //sua função para remove
    return json_encode(['remove'=>'success']);
}
function delete_prod($item){
    //sua função para delete
    return json_encode(['delete'=>'success']);
}

I hope I have helped.

    
26.09.2016 / 19:02
1

I do not know what your real need is, but if you just load a page into a DIV or SPAN, you can try something like this (where #main corresponds to the DIV or SPAN where you want to load):

<a class="ajax-link"" destino="cart.php" href="#"> 
  <i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i>
</a>
$('a.ajax-link').click(function (e){
  $("#principal").load($(this).attr('destino'));
});
    
26.09.2016 / 19:03