Search code examples
javascriptphpajaxsweetalertsweetalert2

How do I get the SweetAlert-Variable to php?


I am very very new to PHP/JavaScript. So this question will be most probably very simple for most of you guys :) (Hopefully).

I have this standard Sweetalert2 Textbox and it looks amazing and opens like a treat. Now... I don't know how I could get the Variable "text" into a PHP- Variable, I need it in PHP, so that I can add it to my Database .... I know that I need to use AJAX ( something along these lines)$.ajax({ type: "POST", url: "sweetalerttext.php", data: { 'text': text})

but I don't know where exactly I have to add this AJAX code to my SweetAlert Code, nor do I know how I could set up my PHP File.....

I googled the last couple of days and I can't find a foolproof tutorial anywhere.

Would be super grateful if someone could help me out. I added the JQuery to my header and the SweetAlert Files

Cheers

Moritz

//Sweet-Alert Code
$(document).ready(function () {
     $('#new-btn').click(function () {

       async function getText () {
          const {value: text} = await swal({
              input: 'textarea',
              inputPlaceholder: 'Type your message here...',
              showCancelButton: true
          });

          if (text) {
              swal(text)
          }

      };
   });
});

Solution

  • You need to place your AJAX call inside the if branch after the return from the await call. For example:

    if (text) {
        $.ajax({ type: "POST", url: "sweetalerttext.php", data: {'text': text}})
    }