Sweetalert2 Ajax - post input data

lzoesch picture lzoesch · Oct 20, 2017 · Viewed 18.4k times · Source

I have recently been working with SweetAlert2 on my project, and I would like to put together a "Add Note" feature.

User clicks on a button, gets directed to a page, and the following executes.

    <script>swal({
      title: "Add Note",
      input: "textarea",
      showCancelButton: true,
      confirmButtonColor: "#1FAB45",
      confirmButtonText: "Save",
      cancelButtonText: "Cancel",
      buttonsStyling: true
    }).then(function () {
      swal(
        "Sccess!",
        "Your note has been saved!",
        "success"
      )
    }, function (dismiss) {
      if (dismiss === "cancel") {
        swal(
          "Cancelled",
"Canceled Note",
          "error"
        )
      }
    })</script>

What I am trying to accomplish, and have a had a difficult time with is utilizing ajax to post the data from the inputfield "textarea".

I would also like to validate that a submission was successful or failed by using the following

'Success'

swal(
        "Sccess!",
        "Your note has been saved!",
        "success"
      )

"Failed"

swal(
          "Internal Error",
          "Oops, your note was not saved."
          "error"
        )

I also need to pass a PHP object to the ajax (a unique customer ID key), and allow ajax to save the data.

<?php $CustomerKey; ?>

Sweet Alert doesn't give much documentation as to how to utilize ajax, and have had a difficult time finding more information pertaining to my problem with stackoverflow, and online searches.

Any help would be greatly appreciated.

JSFiddle example;

https://jsfiddle.net/px0e3Lct/1/

Answer

Hayden Passmore picture Hayden Passmore · Oct 21, 2017

Hi what you need to do is make your ajax call in the sweetalert's then function and pass the customer key variable as a POST variable using ajax's data parameter.

var CustomerKey = 1234;//your customer key value.
swal({
    title: "Add Note",
    input: "textarea",
    showCancelButton: true,
    confirmButtonColor: "#1FAB45",
    confirmButtonText: "Save",
    cancelButtonText: "Cancel",
    buttonsStyling: true
}).then(function () {       
    $.ajax({
        type: "POST",
        url: "YourPhpFile.php",
        data: { 'CustomerKey': CustomerKey},
        cache: false,
        success: function(response) {
            swal(
            "Sccess!",
            "Your note has been saved!",
            "success"
            )
        },
        failure: function (response) {
            swal(
            "Internal Error",
            "Oops, your note was not saved.", // had a missing comma
            "error"
            )
        }
    });
}, 
function (dismiss) {
  if (dismiss === "cancel") {
    swal(
      "Cancelled",
        "Canceled Note",
      "error"
    )
  }
})

And to get the customerKey value in your php file in this example its(YourPhpFile.php) just include

$CustomerKey = $_POST['CustomerKey'];

Good luck