Roberth
Roberth

Reputation: 105

Submit a PHP form directly from JS (without HTML)

I'm trying to send a form through JS, without the need of HTML, I have a table with users info, and there's buttons being added automatically using JS, and I can't pass that info to HTML (the JS table overwrites the HTML table removing all forms), It's there a way I can submit a query to PHP using only JS?

This is the function ran when I click the button that JS creates

function banAccount(id, username){
    swal({
        title: "Do you really want to ban "+username+"?",
        text: "Enter amount of days, -1 equals to permanent ban.",
        input: 'number',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        showLoaderOnConfirm: true,
        preConfirm: function (duration) {
          return new Promise(function (resolve, reject) {
            setTimeout(function() {
              if (duration === '0') {
                reject('Please type -1 for permanent ban or a number greater than 1!')
              } else {
                resolve()
              }
            }, 2000)
          })
        },
    allowOutsideClick: false
    }).then(function(duration){
        action_id = id;
        action_type = "ban";
        action_params = duration;
        alert("id:"+action_id+", type:"+action_type+", params:"+action_params)
        // Here's where I need to send "action_id", "action_type" and "action_params" to PHP
    });
}

Upvotes: 1

Views: 104

Answers (2)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

You need to use ajax.

$.ajax ({
    url: "PHP-PAGE-TO-POST-TO.php",
    data: { action_id : action_id, 
            action_type : action_type, 
            action_params : action_params },
    success: function( result ) {
        alert("Hi, testing");
        alert( result );
        //the variable "result" holds any value the PHP script outputs
    }
});

Upvotes: 2

WonaBee
WonaBee

Reputation: 1

If the alert (in the 'then' portion of the swal (I'm guessing sweet-alert)) is outputting the correct data, why don't you just post the data to your PHP file?

$.post( "YOURFILE.php", { id: action_id, type: action_type, params: action_params } );

Upvotes: 0

Related Questions