Search code examples
phpjqueryjsonajaxjsonp

How to show jsonp response sent by php on a page


i have a script for jsonp as follows

<script>
$(document).ready(function(){

    $("#LoginForm").submit(function(){

    var data = $(this).serialize();
    //alert(data);
    $.ajax({
            type:"POST",
            dataType:"jsonp",
            url:"https://akshay.tk/api/login.php",
            data:data,

            success:function(data)
            {       

                /// WHAT TO WRITE HER TO GET PHP RESPONSE
                /// DIV WHERE DATA TO BE SHOWN, ID IS RESULT    
            }

            });
    return false;
    });

});
</script>

and my php code is

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];              

// login check for user
$result = mysqli_query($con,"SELECT * FROM `admin_login` WHERE `username`='$username' AND `password`='$password'"); 

if(mysqli_num_rows($result) > 0) 
{
    $user = mysqli_fetch_assoc($result);
    // user found           
    $response["success"] = 1;
    $response["uid"] = $user["id"];
    $response["username"] = $user["username"];
    $response["role"] = $user["role"];

    echo json_encode($response);
}

Everything is going good and when i used developers tool then i came to know it is giving proper response as well. Response by php :

{"success":1,"uid":"1","username":"admin","role":"admin"}

What code should i write in jQuery SUCCESS function so that i can get php response?


Solution

  • If you want to ouput the result thrown by php for your ajax result then

    Create a div like this

    <div id='yourDiv'></div>

    Then inside the success event

     success:function(data)
    {       
    ('#yourDiv').html(data);
    }
    

    Note :

    If you prefer class then

    <div class='yourDiv'></div>

    replaced by

    ('.yourDiv').html(data);
    

    Additional Data :

    It's better to check the data in your success event like this

    As you getting like this as response

    {"success":1,"uid":"1","username":"admin","role":"admin"}

    success:function(data)
        {        
         if(data.success==1)
        {
        ('#yourDiv').html('Welcome'+data.username);  //You can append or do anything that you wish
        }
        else
        {
        ('#yourDiv').html.('Fail');
        }
        }