Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Megatech's avatar

How to use Javascript to trigger php if(isset)

Hello, good day all. Please i need some help. I am trying to use javascript and sweetalert to send request to external if(isset()) php statement, but i don't know if i am doing it correctly, the form is not submitting. Here is my code

// Javascript function
function submitForm(form) {
         Swal.fire({
          title: 'Are you sure?',
          text: 'You want to perform this action!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, Send!'
        }).then((result) => {
          if (result.isConfirmed) {
            form.submit();
          }
        })
        return false
}

My form button that is being triggered (Please note that a form already sent them here, this is just a preview page to confirm their action)

 <form method="post" action="" onsubmit="return submitForm(this)">
            <div class="localpreview">
            
            <p>Receiver: <span><?php echo $_SESSION['receiver_last']." ".$_SESSION['receiver_first']?></span></p>
            <p>Account No: <span><?php echo $_SESSION['account_no']?></span></p>
            <p>Amount (Inc. Charges): <span><?php echo $symbol.number_format($_SESSION['debit'])?></span></p>
            <p>Naration: <span><?php echo $_SESSION['naration']?></span></p>
            <span class="transfer-btn">
                  <button type="submit" name="con_trans" id="con_trans">Send</button>
                 
                 </span>
            </div>
            </form>

And my php code i am sending to

if(isset($_POST['con_trans'])) {
  $timestamp = date('Y-m-d H:i:s');
  $token = random_str(7, 'abcdefghijklmnopqrstuvwxyz');
  $receiver_last = $_SESSION['receiver_last'];
  $receiver_first = $_SESSION['receiver_first'];
  $account_no = $_SESSION['account_no'];
  $amounty = $_SESSION['debit'];
  $naration = $_SESSION['naration'];

  prepared_insert($pdo, 'transfers', [
    'ref_id' => $token,
    'amount' => $amount,
    'naration' => $naration,
    'status' => $status,
    'created_at' => $timestamp,
    'updated_at' => $timestamp  
    
  ]);


}
0 likes
39 replies
Megatech's avatar

@Snapey you mean what my browser console is printing out? if yes i can't see any error, it just show my function javascript in the console like this and it is highlighted in red, no notice at the top to tell whats wrong.

submitForm(form) {
         Swal.fire({
          title: 'Are you sure?',
          text: 'You want to perform this transaction!',
          icon: 'warning',
          showCancelButton: true,
Sinnbeck's avatar

Try removing the return here

onsubmit="submitForm(this)" 
Megatech's avatar

@Sinnbeck I removed it as requested but the sweetalert just popup and immediately dissappear without allowing me to click on any response and then nothing happen after that.

Sinnbeck's avatar

@Megatech try passing the event and prevent it

onsubmit="submitForm(this, event)" 

// Javascript function
function submitForm(form, event ) {
         event.preventDefault()
         Swal.fire({
          title: 'Are you sure?',
          text: 'You want to perform this action!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, Send!'
        }).then((result) => {
          if (result.isConfirmed) {
            form.submit();
          }
        })
        return false
}
Megatech's avatar

@Sinnbeck Still did not send the form to the php. it just show the sweetalert, after clicking on the sweetalert response nothing else happen. i even edited my php code and then echo something just to see if its receiving any call

Sinnbeck's avatar

@Megatech ok so now it stays on screen? Then you can start debugging. Use console.log to check if you hit the inside of .then()

Example

console.log(result.isConfirmed) 
Sinnbeck's avatar

@Megatech like

onsubmit="submitForm(this, event)" 

// Javascript function
function submitForm(form, event ) {
         event.preventDefault()
         Swal.fire({
          title: 'Are you sure?',
          text: 'You want to perform this action!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, Send!'
        }).then((result) => {
          console.log(result) //this 
          if (result.isConfirmed) {
            form.submit();
          }
        })
        return false
}
 
Megatech's avatar

@Sinnbeck still on same page without any action, and there was no error in my browser console

Sinnbeck's avatar

@Megatech but do you click on the confirm button? I assume that's what is meant to trigger the then()

Megatech's avatar

@Sinnbeck absolutely. i click on it and then the page just return to its normal state. if there is any other way to achieve this i will really appreciate it, i just want to use sweetalert to confirm their action before actually sending to the php file

Sinnbeck's avatar

@Megatech then it sounds like it submits? At the top of the php file add

var_dump($_POST); exit;
Megatech's avatar

@Sinnbeck you mean like this ? If yes nothing happened still.....Can you also please check my form, i am not actually sending any data to the php file with input field, i collected what was saved in session already, hope this isn't a problem at first.

if(isset($_POST['con_trans'])) {
var_dump($_POST);
exit;

  $timestamp = date('Y-m-d H:i:s');
  $token = random_str(7, 'abcdefghijklmnopqrstuvwxyz');
  $receiver_last = $_SESSION['receiver_last'];
  $receiver_first = $_SESSION['receiver_first'];
  $account_no = $_SESSION['account_no'];
  $amounty = $_SESSION['debit'];
  $naration = $_SESSION['naration'];

  prepared_insert($pdo, 'transfers', [
    'ref_id' => $token,
    'amount' => $amount,
    'naration' => $naration,
    'status' => $status,
    'created_at' => $timestamp,
    'updated_at' => $timestamp  
    
  ]);


}
Sinnbeck's avatar

@Megatech no above that if check

If you don't send in any data, then that if is always false. A form needs inputs. That's what $_POST checks

Megatech's avatar

@Sinnbeck this is how it is now

my form

<form method="post" action="" onsubmit="submitForm(this, event)">
               <p> <?php echo $showError ?> </p>
            <div class="localpreview">
            <input type="text" <?php echo $_SESSION['receiver_last']." ".$_SESSION['receiver_first']?> style="display: none;"></input>
            <p>Receiver: <span><?php echo $_SESSION['receiver_last']." ".$_SESSION['receiver_first']?></span></p>
            <input type="text" value="<?php echo $symbol.number_format($_SESSION['debit'])?>" style="display: none;" ></input>
            <p>Amount (Inc. Charges): <span><?php echo $symbol.number_format($_SESSION['debit'])?></span></p>
            <input type="text" value="<span><?php echo $_SESSION['naration']?>" style="display: none;"></input>
            <p>Naration: <span><?php echo $_SESSION['naration']?></span></p>
            <span class="transfer-btn">
                  <button type="submit" name="con_trans" id="con_trans">Send</button>
                 
                 </span>
            </div>
            </form>

The javascript is now like this

function submitForm(form, event ) {
         event.preventDefault()
         Swal.fire({
          title: 'Are you sure?',
          text: 'You want to perform this action!',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, Send!'
        }).then((result) => {
          console.log(result) 
          if (result.isConfirmed) {
            form.submit();
          }
        })
        return false
}

Then the php

if(isset($_POST['con_trans'])) {
var_dump($_POST);
exit;

  $timestamp = date('Y-m-d H:i:s');
  $token = random_str(7, 'abcdefghijklmnopqrstuvwxyz');
  $receiver_last = $_SESSION['receiver_last'];
  $receiver_first = $_SESSION['receiver_first'];
  $account_no = $_SESSION['account_no'];
  $amounty = $_SESSION['debit'];
  $naration = $_SESSION['naration'];

  prepared_insert($pdo, 'transfers', [
    'ref_id' => $token,
    'amount' => $amount,
    'naration' => $naration,
    'status' => $status,
    'created_at' => $timestamp,
    'updated_at' => $timestamp  
    
  ]);


}
Sinnbeck's avatar

@Megatech I assume it's all just one php file as you are submitting to the same page?

Sinnbeck's avatar

And perhaps while you debug this you should comment out toast. Currently it's a simple form submission we are debugging and has nothing to do with toast or Javascript

Megatech's avatar

@Sinnbeck sorry i don't get this toast you said, you mean sweetalert? or the console.log? to your other question, my php is in another file not in the same place with the form, i just include it at the top. My php code works perfectly well, if i remove this javascript onsubmit="submitForm(this, event)" from the form my form submit successfully and my php code runs. But when i include the javascript it doesn't work

Sinnbeck's avatar

@Megatech yes sorry. Sweet alert

Then you need to check your network tab in the browser to see what happens

Megatech's avatar

@Sinnbeck if i comment out sweetalert that will make my code look like this

function submitForm(form ) {
         form.submit();
}

and that doesn't do anything. Checking my network tab everything seems to work fine

Megatech's avatar

@Sinnbeck no i mean my network tab shows that the page is running fine and it shows the time rate of the page load

Megatech's avatar

@Sinnbeck after commenting out the sweetalert, this is how our code is

function submitForm(form ) {
         form.submit();
}

And it successfully submitted, so it work this way but we haven't archieved our purpose throught this way because we want to show them the sweetalert prompt before submitting.

Sinnbeck's avatar

@Megatech then you know what to look for in network? This time add it back and comment out form.submit();. Add a console.log and see if that shows up

Megatech's avatar

@Sinnbeck in my console here is the log that came out

{isConfirmed: true, isDenied: false, isDismissed: false, value: true}
isConfirmed: true
isDenied: false
isDismissed: false
value: true
[[Prototype]]: Object
Sinnbeck's avatar

@Megatech then it seems it is triggered. Add the submit back in and see what happens in network. What's the difference from when it worked 2 answers ago?

Megatech's avatar

@Sinnbeck I put the submit back and the difference in the network is the size, the first was 15.7kb and the second is 16.1kb, and in this 2nd one there is nothing in the console, and the form did not submit to the php file

Sinnbeck's avatar

@Megatech how do you know it didn't submit? If there is no console.log, something must have happened (most likely a redirect)

Megatech's avatar

@Sinnbeck how i knew it didn't submit is, i echo a success notice at the begining of my php file like this

if(isset($_POST['con_trans'])) {
$erroShow = "Successfully sent"; // this errorShow variable was echo in my form

  $timestamp = date('Y-m-d H:i:s');
  $token = random_str(7, 'abcdefghijklmnopqrstuvwxyz');
  $receiver_last = $_SESSION['receiver_last'];
  $receiver_first = $_SESSION['receiver_first'];
  $account_no = $_SESSION['account_no'];
  $amounty = $_SESSION['debit'];
  $naration = $_SESSION['naration'];

  prepared_insert($pdo, 'transfers', [
    'ref_id' => $token,
    'amount' => $amount,
    'naration' => $naration,
    'status' => $status,
    'created_at' => $timestamp,
    'updated_at' => $timestamp  
    
  ]);


}

So when you asked me to removed everything and leave just the ''' form.submit() ``` , the success message echod that is how i knew it submitted, so now this message did not come up that is how i knew it didn't submit

Sinnbeck's avatar

@Megatech I cannot guess what is happening on your screen. It makes absolutely zero sense. Without trying it myself I throw in the towel for now

frankhosaka's avatar

I tried to run the code with this

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
<script id="_carbonads_projs" type="text/javascript" src="https://srv.carbonads.net/ads/CKYILKQJ.json?segment=placement:sweetalert2githubio&amp;callback=_carbonads_go"></script>
<script>

but i get many errors on navigator inspection box. I find this webpage: https://sweetalert2.github.io/

it's fantastic! when works, sure.

frankhosaka's avatar

This works!!!! teste.blade.php:

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
  title: 'Error!',
  text: 'Do you want to continue',
  icon: 'error',
  confirmButtonText: 'Cool' })
</script>
<form id=myfrm>
<p>Receiver: Receiver</p>
<p>Account No: 123</p>
<p>Amount (Inc. Charges):1000</p>
</form>
<button onclick="Swal.fire(myfrm)">Try me!</button>

 ´´´
frankhosaka's avatar

but i get the error sweetalert2@11:5

   Uncaught TypeError: Cannot read properties of null (reading 'querySelector')

and I lost myform!

It's very dangerous. The better is to use the old "alert".

Please or to participate in this conversation.