3

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,

6
  • 1
    What is the error you are getting? Commented May 11, 2015 at 6:42
  • there are no values in $usrname and $usrpass. Hence, the mysqli query executes but without any result. Commented May 11, 2015 at 6:44
  • for the incorrect password also it returns a success output on execution of the script Commented May 11, 2015 at 6:47
  • please post the output of console.log(myjson); Commented May 11, 2015 at 6:50
  • <br /> <b>Warning</b>: log() expects parameter 1 to be double, string given in <b>/home/arjunmb/airtec-intl.com/checkpass.php</b> on line <b>5</b><br /> Success Commented May 11, 2015 at 6:58

5 Answers 5

2

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();
}
Sign up to request clarification or add additional context in comments.

6 Comments

did not work. although i enter the wrong password it still returns $output as success.
But $result, doesn't contain the actual number of count, if the query runs succesfull it wil return true, so $result=1 and is higher then 0, to get the count use mysql_num_rows
It will return success since when using $result we are checking if the query wa successfull if you want to count the returned number of rows check my edited answer
thanks. got that error. but still it persists as the json object is not being parsed for the correct inputs as well
are you passing the text field from a form, i edit my answer on how to pass the fields @ArjunBhandari
|
1

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;
}

Comments

0

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();

1 Comment

same problem, whether i use the correct or incorrect password. also i amended this to be $result = $result->num_rows and then checking if $result > 0
0

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 );
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.