Creating a button with ajax and making it run php

Asked

Viewed 1,406 times

0

I have a boot that every time I click my page 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 This is the whole system of my shopping cart. In my checkout.php is where I add or take selected items. and I inserted my function cart(); in it.

I wanted to use ajax to make my boot 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 mine 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;
                } 
            }
        }
    }
}

2 answers

1

I don’t know what your real need is, but if it’s just loading a page in a DIV or SPAN, you can try something like this (where the #main corresponds to the DIV or SPAN where you want to click):

<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'));
});

0


I tried to better organize the structure of your files so you can understand exactly how the use of ajax works.

Cart.php

The first thing to do is to add some references to your action buttons in the loop of your function cart, as the action type of the button data_action and the product id 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>';

php checkout.

Soon after, 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’ve helped.

  • I did what you said but my buttons didn’t work...on my checkout page.php is so html and there I call Function Cart(); this Function is in Cart.php where there is only php. every time I clicked on some button on the checkout page.php ran my code in Cart.php so it was always returning to header('Location: checkout.php');

  • on the page checkout.php I have already inserted <script src="../../js/jquery.min.js" type="text/javascript"></script>

  • but nothing is working

  • I made a correction in javascript code, try to execute now. Remember that JSON return is essential.

  • I took the edited code and it still doesn’t work look here my checkout.php-> https://codeshare.io/G4Jlu and my Cart.php-> https://codeshare.io/NntjJ

  • da para edit the code sent by the browser

  • Your code is a little disorganized, I edited my answer and put together a simple structure where you can better organize with the functions.

  • i added an Alert alert('funciona'); in the ajax to do Function plus I received the msg, but this not increasing my $value of my session, my $value is my amount of certain id / "product"

  • when vc mentions for example: "//your function to add" in cart_functions.php you only decrypted what that function does or is for me to add my code to add by ex: function plus_prod($item){&#xA; &#xA; //sua função para plus&#xA; $_SESSION['product_'.$_GET['plus']]+=1;&#xA; return json_encode(['plus'=>'success']);&#xA;}

  • Would that be it?

  • You add your code

  • It worked I just had to change $_SESSION['product_'.$_GET['plus']]+=1; for $_SESSION['product_'.$_GET['prod_id']]+=1;

  • All I needed was mine $value update automatico, pq it only updates qnd dou F5...but I will seek to find out how.... thank you very much!

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.