简体   繁体   中英

json object in php not being read

I want to pass username and password to a php script and check in the database. On the client side I use the following script to make a json object and post it to the php file.

var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();

var myjson = JSON.stringify(myobj);

$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
    alert( msg );
});

On the server side, when I see in firebug , the post is passed as

Parametersapplication/x-www-form-urlencodedDo not sort {"usrname":"XXXXXXX...
JSON

usrname "XX"

usrpass "justdoit" Source {"usrname":"XXX","usrpass":"justdoit"}

however when i run the php script to check the query the it returns an error

$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];

$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);

if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}

I have tried through all the posts but cannot get this to work.

Thanks in advance.

Regards,

Echo and die the statement in order for ajax to have a success event

Js File

 var myobj = {};

        myobj["usrname"] = 'myUsername';

        myobj["usrpass"] = 'myPassword';



        $.ajax({
            type: "post",
            url: "url",
            dataType: "json",
            data: {post_data: myobj},
            contentType: "application/x-www-form-urlencoded",
            success: function (responseData) {
                console.log(responseData);
            },
            error: function (errorThrown) {
                console.log(errorThrown);
            }
        });

PHP action File

           /** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
//    [post_data] => Array
//        (
//            [usrname] => myUsername
//            [usrpass] => myPassword
//        )
//
//)

if (isset($_Post['post_data'])) {
    $myPost = $_Post['post_data'];
    $usrname = $myPost['usrname'];
    $usrpass = $myPost['usrpass'];

    $sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
    $result = $conn->query($sql);
    $num_row = $result->num_rows;

    if ($num_row > 0) {
        $output = 'Success';
    } else {
        $output = 'fail';
    }
    echo json_encode($output);
    die();
}

Try This : in js file :

$(document).on("ready", function(){

            // Create an object using an object literal.
            var ourObj = {};

            // Create a string member called "data" and give it a string.
            // Also create an array of simple object literals for our object.
            ourObj.data = "Some Data Points";
            ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];


            var savedata = JSON.stringify(ourObj)
            $.ajax({
                type:"POST",
                url:"Users.php",
                data: {"points" : JSON.stringify(ourObj)},
               success: function(data) {
                    // Do something with data that came back. 
                    alert(data);
               }

            })
        }); 

In PHP File :

if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);


echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
}

Try this:

var myobj = '{
usrname:'+$( "#customer option:selected" ).text()+',
usrpass:'+$("#psw").val()+'
}';

or

var myobj = {};
myobj.usrname= $( "#customer option:selected" ).text();
myobj.usrpass= $("#psw").val();

Use Json2 library as follows,

var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();

var myjson = JSON2.stringify(myobj);

$.ajax({
 method: "POST",
 url: "checkpass.php",
 data: myjson
})
.done(function( msg ) {
  alert( msg );
});

Well actually you php code is invalid because you pass json day not name value pair so you cant get it from $_POST['username']. You need to get the whole post data and decode it like this.

$data = json_decode(file_get_contents('php://input'), true);

Now $data is dictionary array of username and password. Also sanitize your data before passing to query to avoid sql injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM