Home » Jquery » jquery – Pass parameters to ajax function that can be used in php?

jquery – Pass parameters to ajax function that can be used in php?

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have the following ajax/jquery snippet, and my goal is to send a request that has a ‘type’ parameter. I already have a username and password, which I can echo back no problems. However, if I attempt to add a
type:'login' to the data of the request, I can never access ‘type’ from the php.

$(document).ready(function(){
     $("#button").click(function(){
          $.ajax({
               url: 'login.php',
               type: 'POST',
               content-type: 'application/x-www-form-urlencoded',
               data: {type:'login',username:user,password:pass},//this is my issue, why can't I pass type?
               success: function(response){
                    //determine if login was successful
               }
     });
});

The login.php simply checks if POST is set and checks for parameter POST[“type”], but it does not get passed?

PHP

<?php


if (!isset($_POST))
{
    $msg = "NO POST MESSAGE SET, POLITELY **** OFF";
    echo json_encode($msg);
    exit(0);
}
$request = $_POST;
$response = "unsupported request type, politely **** OFF";
switch ($request["type"])
{
    case "login":
        $response = "login, yeah we can do that";
    break;
}
echo json_encode($response);
exit(0);

?>
How to&Answer:

Since you are using content-type: 'application/x-www-form-urlencoded', you need to use jQuery’s $.param to serialize the value. Check here: https://api.jquery.com/jQuery.param/