0

In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.

DB table Students

+---------------------------+
| name | fathername | Email |
+---------------------------+

submit.php

$query=mysql_query("SELECT * from Students LIMIT 0,6");

   $row= array();
   $row=mysql_fetch_array($query);
   return json_encode($row);

index.php

<script>
    $(function(){
        $("#form1").submit(function(event){
            event.preventDefault();

            $.ajax({
                    url:'submit.php',
                    type:'GET',
                    data:$(this).serialize(),
                    success:function(result){
                $.each(result,function(){
                $('.StudentName').text(result["name"]);
                $('.FatherName').text(result["fathername"]);
                $('.Email').text(result["email"]);
                    });

                    }
            });
        });
    });
</script>

<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>

EDIT I tried to return only 1 result from php and it works i.e.

echo json_encode(mysql_fetch_array($query));

When I return all 6 records the jquery function dont execute i.e.

while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}
5
  • What is the return type for your data? JSON, HTML, XML? Your best bet would be to have the PHP create JSON (php.net/manual/en/function.json-encode.php) and then parse that JSON with your jQuery statement(api.jquery.com/jQuery.parseJSON). Commented Apr 11, 2014 at 13:09
  • I am returning JSON and revised my code as well Commented Apr 11, 2014 at 13:14
  • Add dataType: "json" to your AJAX function parameters. Commented Apr 11, 2014 at 13:15
  • added datatype as well but still not working Commented Apr 11, 2014 at 13:17
  • use echo json_encode($row); Commented Apr 11, 2014 at 13:19

4 Answers 4

2

There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.

This will convert your PHP array to JSON array, eg:

 array(3) {
  [0]=>
    string(3) "foo"
  [2]=>
   string(3) "baz"
  [3]=>
   string(5) "blong"
}

to

string(33) "{"0":"foo","2":"baz","3":"blong"}"

So try -

return json_encode($row);

and then when you catch the response, use parseJSON:

result = jQuery.parseJSON(result);
$.each(result,function(){
   $('.StudentName').text(result.name);
   $('.FatherName').text(result.fathername);
   $('.Email').text(result.email);
});

Edit:

Another thing, instead of return json_encode($row); write echo json_encode($row);

Edit 2

(to send all 6 records)

$final = array();
while($result=mysql_fetch_array($query))
{
    array_push($final,$result);
}
echo $final;
Sign up to request clarification or add additional context in comments.

18 Comments

Can you provide the OP with a more complete answer?
@SahilMittal return must be echo ?
@SahilMittal tried your code but still the same problem. It is not working
Can you see the result in console.log(result)? If yes, post that result here
I do not know this console.log tag
|
0
function success(result){
    $.each(result,function(){
        $('.StudentName').text(result["name"]);

looks problematic. There doesn't really seem to be a reason to loop over the result, as you assign all of its contents to the same elements in the page.

However, assuming that result is an array of objects (like SQL queries usually produce it), then it should be

function(result){
    $.each(result,function(obj) {
//    missing parameter!!! ^^^
        $('.StudentName').text(obj["name"]);
//           access that here: ^^^

Also do a console.log(result) or simply browse the request URL to check whether the PHP scripts yields the expected response.

Comments

0

Here is an example of parsing JSON that may help you - http://jsfiddle.net/Su6QR/

Given that example, change your AJAX function -

$.ajax({
    url:'submit.php',
    type:'GET',
    data:$(this).serialize(),
    success:function(result){
        var members = $.parseJSON(result);
        $.each(members, function() {
            var newStudent = '<span>' + this['name'] + '</span>';
            var newFather = '<span>' + this['father'] + '</span>';
            var newEmail = '<span>' + this['email'] + '</span>';
            $('.StudentName').append(newStudent);
            $('.FatherName').append(newFather);
            $('.Email').append(newEmail);
        });
    }
});

This should return all of the data and place them into the divs that you have created. The formatting will not be what you want, but you should be able to fix that pretty easily.

Comments

0

This might help you.

Your AJAX

        $("#form1").click( function(e){


            var Somename = { };

            $.each($('#form1').serializeArray(), function() {
                Somename [this.name] = this.value;
            });             

            e.preventDefault();
            $.ajax({
                type: "GET",
                url: "submit.php",
                data: { upddt_empID: upddt_empID, somevariable: "YES" },
                success: function(data) {
                    alert('Successfull');           
                }
            });

Your PHP

if(isset( $_REQUEST['somevariable'] ) )
{
   $selItem = YourFunctionName( $_REQUEST['Somename ']['here your textbox id'], $_REQUEST['Somename ']['here your textbox id'],'yourtablename');
}

Your Query

function YourFunctionName(tablename)
{
    $qry = "SELECT * FROM $tablename";

    $result = mysql_query($qry);

    return $result;
}

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.