Home > OS >  Get return value from php to ajax
Get return value from php to ajax

Time:09-29

I am using SweetAlert for confirmation and I am having trouble getting the return data from my php to ajax

Here's what I am doing

my backend php

//Add A voucher
public function AddVoucher ($voucher_name, $quantity, $discount) 
{
    try
    {
            $stmt2 = $this->db->prepare("SELECT * FROM vouchers WHERE voucher_name=:voucher_name");
            $stmt2->bindParam(":voucher_name", $voucher_name,PDO::PARAM_STR);
            $stmt2->execute();
            $stmt2->fetchAll(PDO::FETCH_ASSOC);

            if($stmt2->rowCount())
            {
                return "Failed";
            }
            else
            {
            $discount /= 100;
            //name doesn't exist so proceed to registration
            $stmt = $this->db->prepare("INSERT INTO vouchers (voucher_name,quantity,discount) 
            VALUES(:voucher_name, :quantity, :discount)");
            $stmt->bindParam(":voucher_name", $voucher_name,PDO::PARAM_STR);
            $stmt->bindParam(":quantity", $quantity,PDO::PARAM_STR);
            $stmt->bindParam(":discount", $discount,PDO::PARAM_INT);
            $stmt->execute();
    
            return $stmt;
        }
    }
    catch(PDOException $ex)
    {
        echo $ex->getMessage();
    }
}

my model php

<?php
require_once '../database/database.php';

$voucher_name = $_POST['voucher_name'];
$quantity = $_POST['quantity'];
$discount = $_POST['discount'];

$result =  $user->AddVoucher($voucher_name,$quantity,$discount);

if($result == "Failed"):
    return false;
else:
    return true;
endif

?>

and now my frontend where my ajax exists

function SwalConfirm()
{
  
  Swal.fire({
    title: 'Are you sure?',
        text: "You will an a voucher . Do you wish to proceed",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Proceed',
        cancelButtonText: 'No, cancel!',
        confirmButtonClass: 'btn bg-gradient-primary w-30',
        cancelButtonClass: 'btn bg-gradient-secondary w-30',
        buttonsStyling: false,
        preConfirm: function()
        {
            return new Promise(function(resolve){
                $.ajax({
                    url: '../model/voucher_add.php',
                    type: 'POST',
                    data:
                    {
                        voucher_name: $('#a_voucher_name').val(),
                        quantity: $('#a_quantity').val(),
                        discount: $('#a_discount').val()
                        
                    },
                    success: function(data)
                    {
                      if(!data)
                      {
                        Swal.fire('Opps!', 'Voucher Name Already Exists. Please Edit the current voucher instead','warning').then(function(){
                          location.reload();
                        });
                      }
                      else
                      {
                        Swal.fire('Success!', 'You have successfully added a voucher.','success').then(function(){
                            location.reload();
                        });
                      }
                    }
                })
                // .done(function(response)
                // {
                      // Swal.fire('Opps!', 'Voucher Name Already Exists. Please Edit the current voucher instead','warning').then(function(){
                      //     location.reload();
                      // });
                // })
                .fail(function(){
                    Swal.fire('Oppss!', 'There was something wrong declining this request.','success')
                })
            });
        }
  });
}

What I am trying to do here is that if the current voucher already exists then don't proceed and show an error using sweetalert instead of successful message

CodePudding user response:

For those who might encounter like this problem the solution for this is just this


if($stmt2->rowCount())
{
    echo "0";
}

then catch it to you ajax like this

if(data == 0)
{
    Swal.fire('Opps!', 'Voucher Name Already Exists. Please Edit the current voucher instead','warning').then(function(){
        location.reload();
     });
}

just something like that . But also follow what lawrence said regarding on catching the null

CodePudding user response:

Model php:

<?php

require_once '../database/database.php';

$voucher_name = $_POST['voucher_name'];
$quantity = $_POST['quantity'];
$discount = $_POST['discount'];

$result =  $user->AddVoucher($voucher_name,$quantity,$discount);

if($result == "Failed"):
    return json_encode(false);
else:
    return json_encode(true);
endif

?>

It will return json_encoded result to ajax

  • Related