0

I've been trying to find an answer for this for hours but really struggling.

I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]} . There should be 3 entries in the array.

The PHP

<?php
 include_once('../../dbconnect.php');

$name = $_POST['uploadname'];

$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();

while ($row = $details->fetch_assoc()){
 $modules[] = $row['unit'];
}

$dataarray = array("modules"=>$modules);
 echo json_encode($dataarray);
?>

The jQuery

  var uploadname;

  $("#uploadname").blur(function(){
   uploadname = $(this).val();
   $.ajax({
            url: "uploadnames.php",
            type: "POST",
            data: {uploadname: uploadname},
            dataType: 'json',
            success: function(data){
            console.log(data);
             }
            });

         });
7
  • You're certain everything on the php side is in order, such as $row['unit'] and all of that? Commented Mar 13, 2013 at 19:38
  • 3
    Might have something to do with the echo json_encode($modules); in the while loop. Looks like that shouldn't really be there? Commented Mar 13, 2013 at 19:38
  • If you're returning json to jQuery, you should only have one echo on the page. I'm surprised you're not getting a parseerror Commented Mar 13, 2013 at 19:42
  • Oops, hadn't noticed that - I've changed it now but doesn't seem to have resolved the problem Commented Mar 13, 2013 at 19:53
  • Nice SQL injection hole. Enjoy having your server pwn3d. Commented Mar 13, 2013 at 19:54

1 Answer 1

1

you should use:

  var parsedData =  jQuery.parseJSON(data);

and then:

  console.log(parsedData)
Sign up to request clarification or add additional context in comments.

1 Comment

No, jQuery will parse the JSON automatically in this case. The console wouldn't show Object {modules: Array[0]} if it wasn't parsed.

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.