Junaid Saleem
Junaid Saleem

Reputation: 175

jquery ajax datatype json is not working with php associative array

i am new to the stackflow and m having some problems while using jquery' json ajax encoded values from an associative array, the jquery script is doing nothing!

its a script that just does nothing but gives you back both username and password back to you via json encode...

here is my code of the index.html file:

<html>
<head>
    <title>test jquery</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

        $("#button").click(function() {

            var sendu = $("#username").val();
            var sendp = $("#password").val();

            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: "username="+sendu+"&password="+sendp,
                dataType: "json",
                success: function(msg,string,jqXHR){
                    $("#result").html(msg.name);
                }

            });         

        });

    });


    </script>

</head>
<body>

    Name: <input type="text" id="username" name=""username /> <br />
    Password: <input type="password" id="password" name="password" /><br />

    <input type="button" value="send" id="button" />
    <div id="result"></div></p>

</body>
</html>

and this is the php file:

<?php 

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

$a = array('name'=>$name, 'password'=>$password);

$c = json_encode($list);

echo $c;


 ?>

so when i removed the dataType: "json" and when i removed the associative array from the php file, all goes well, it worked!

here is the after removing json encode:

html:

<script type="text/javascript">
$(document).ready(function() {

    $("#button").click(function() {

        var sendu = $("#username").val();
        var sendp = $("#password").val();

        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: "username="+sendu+"&password="+sendp,

            success: function(msg,string,jqXHR){
                $("#result").html(msg);
            }

        });         

    });

});


</script>

and the php file:

<?php 

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


$c = "your name is ".$name."<br />and your password is ".$password;

echo $c;


 ?>

and one more thing that, i am not an english man so if you find any common grammer mistakes, please ignore!

Upvotes: 0

Views: 1668

Answers (1)

David Jones
David Jones

Reputation: 4305

One thing I noticed was this line in your AJAX call should be:

data: "username="+sendu+"&password="+sendp,

Should be:

data: {username: sendu, password: sendp}

That way you can access the variables when using dataType: JSON

Upvotes: 1

Related Questions