2

The problem is in jQuery, jsondata.uname is not displaying any result. If I echo $myarray in PHP and use data in jQuery it will display the result in array form.

$(document).ready(function() {
    $('button#myloginbtn').on('click', function(e) {
        e.preventDefault();
        var username = $('input#myusername').val();
        var password = $('input#mypassword').val();
        $.post('home.php', {
            domylogin: 'domylogin',
            username: username, 
            password: password 
        }, function(data) {
            jsondata = JSON.parse(data);
            $('p#auser').text(jsondata.uname); // This is not working
        });
    });
});

home.php:

<?php 
    if (isset($_POST['domylogin'])){
        $myuname = $_POST['username'];
        $mypword = $_POST['password'];
        // temporary testing, later i will return some data from database related to these values
        $myarray = array(); 
        $myarray['uname'] = $myuname;
        $myarray['pword'] = $mypword;

        echo json_encode($myarray);
    }
?>
11
  • console.log(jsondata);. Hope you will get what is wrong. Commented Feb 10, 2016 at 9:07
  • console.log(data); and check in browser Commented Feb 10, 2016 at 9:07
  • 1
    jQuery will automatically parse the response to an object for you. Using JSON.parse() on that object again will cause an error. Remove the JSON.parse(data) line and use $('p#auser').text(data.uname) Commented Feb 10, 2016 at 9:08
  • try this {'domylogin':1, . . . }. Commented Feb 10, 2016 at 9:11
  • @VairaMuthu where to put console.log(data); Commented Feb 10, 2016 at 9:14

2 Answers 2

2

Thanks everyone for support, I had got the problem. I had some html code in my php file, on removing html code in 'home.php' everything works as supposed!

Sign up to request clarification or add additional context in comments.

Comments

1

In your PHP file:-

 $myarray = array(); 
    if (isset($_POST['domylogin'])){
            $myuname = $_POST['username'];
            $mypword = $_POST['password'];             

            $myarray['uname'] = $myuname;
            $myarray['pword'] = $mypword;    

        }

 echo json_encode($myarray);

Write your AJAX call as below:-

$.post('home.php', {
    domylogin: 'domylogin',
    username: username, 
    password: password 
}) 
.done(function( data ) {  // Use done function        
    jsondata = JSON.parse(data);
    if(jQuery.isEmptyObject(jsondata) == false) // check jsondata is empty or not
    console.log(data);
    $('p#auser').text(jsondata.uname); 
 });

Hope it will help you:-

2 Comments

Check my updated answer. Do you get data in done function?
did everything, still no luck!

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.