[php] jQuery $.ajax request of dataType json will not retrieve data from PHP script

I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get_member_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ā€¯application/json; charset=utf-8". Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr.

My javascript/jQuery function is as follows:

function get_member_info()
   {

   var url = "contents/php_scripts/admin_scripts.php"; 
   var id = $( "select[ name = member ] option:selected" ).val();

   $.ajax(
   {

      type: "POST",
      dataType: "json",
      url: url,
      data: { get_member: id },
      success: function( response ) 
      { 

          $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" );
          $( "input[ name = name ]" ).val( response.name );
          $( "input[ name = fname ]" ).val( response.fname );
          $( "input[ name = lname ]" ).val( response.lname );
          $( "input[ name = email ]" ).val( response.email );
          $( "input[ name = phone ]" ).val( response.phone );
          $( "input[ name = website ]" ).val( response.website );
          $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image );

      },
      error: function( error )
      {

         alert( error );

      }

   } );

}

and the relevant code in "contents/php_scripts/admin_scripts.php" is as follows:

   if( isset( $_POST[ "get_member" ] ) )
   {

      $member_id = $_POST[ "get_member" ];
      $query = "select * from members where id = '$member_id'";

      $result = mysql_query( $query );

      $row = mysql_fetch_array( $result );

      $type = $row[ "type" ];
      $name = $row[ "name" ];
      $fname = $row[ "fname" ];
      $lname = $row[ "lname" ];
      $email = $row[ "email" ];
      $phone = $row[ "phone" ];
      $website = $row[ "website" ];
      $image = $row[ "image" ];

      $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

      echo json_encode( $json_arr );

   }

This question is related to php jquery ajax json

The answer is


  session_start();
include('connection.php');

/* function msg($subjectname,$coursename,$sem)
    {
    return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}';
    }*/ 
$title_id=$_POST['title_id'];
$result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error());
$qr=mysql_fetch_array($result);
$subject=$qr['subject'];
$course=$qr['course'];
$resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'");
$qqr=mysql_fetch_array($resultes);
$subjectname=$qqr['subjectname'];
$coursename=$qqr['coursename'];
$sem=$qqr['sem'];
$json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,);
header("Content-Type: application/json", true);
echo json_encode( $json_arr );


 $.ajax({type:"POST",    
                  dataType: "json",    
                   url:'select-title.php',
                   data:$('#studey-form').serialize(),
                   contentType: "application/json; charset=utf-8",
                   beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
                   success:function(response)
                  {
                    var response=$.parseJSON(response)
                    alert(response.subjectname);
                    $('#course').html("<option>"+response.coursename+"</option>"); 
                    $('#subject').html("<option>"+response.subjectname+"</option>");

                  },
                  error: function( error,x,y)
                  {

                  alert( x,y );

              }
                   });

I think I know this one...

Try sending your JSON as JSON by using PHP's header() function:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.

jQuery used to be fine without the header, but it was changed a few versions back.

ALSO

Be sure that your script is returning valid JSON. Use Firebug or Google Chrome's Developer Tools to check the request's response in the console.

UPDATE

You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.

if (isset($_POST['get_member'])) {

    $member_id = mysql_real_escape_string ($_POST["get_member"]);

    $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";

    if ($result = mysql_query( $query )) {

       $row = mysql_fetch_array($result);

       $type = $row['type'];
       $name = $row['name'];
       $fname = $row['fname'];
       $lname = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $website = $row['website'];
       $image = $row['image'];

       /* JSON Row */
       $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

    } else {

        /* Your Query Failed, use mysql_error to report why */
        $json = array('error' => 'MySQL Query Error');

    }

     /* Send as JSON */
     header("Content-Type: application/json", true);

    /* Return JSON */
    echo json_encode($json);

    /* Stop Execution */
    exit;

}

Try using jQuery.parseJSON when you get the data back.

type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) { 
    response = jQuery.parseJSON(data);
    $("input[ name = type ]:eq(" + response.type + " )")
        .attr("checked", "checked");
    $("input[ name = name ]").val( response.name);
    $("input[ name = fname ]").val( response.fname);
    $("input[ name = lname ]").val( response.lname);
    $("input[ name = email ]").val( response.email);
    $("input[ name = phone ]").val( response.phone);
    $("input[ name = website ]").val( response.website);
    $("#admin_member_img")
        .attr("src", "images/member_images/" + response.image);
},
error: function(error) {
    alert(error);
}

In addition to McHerbie's note, try json_encode( $json_arr, JSON_FORCE_OBJECT ); if you are on PHP 5.3...


Try this...  
  <script type="text/javascript">

    $(document).ready(function(){

    $("#find").click(function(){
        var username  = $("#username").val();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'includes/find.php',
            data: 'username='+username,
            success: function( data ) {
            //in data you result will be available...
            response = jQuery.parseJSON(data);
//further code..
            },

    error: function(xhr, status, error) {
        alert(status);
        },
    dataType: 'text'

    });
        });

    });



    </script>

    <form name="Find User" id="userform" class="invoform" method="post" />

    <div id ="userdiv">
      <p>Name (Lastname, firstname):</p>
      </label>
      <input type="text" name="username" id="username" class="inputfield" />
      <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
    </div>
    </form>
    <div id="userinfo"><b>info will be listed here.</b></div>

If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code

success=function(data){
  //something like this
  jQuery.parseJSON(data)
}

The $.ajax error function takes three arguments, not one:

error: function(xhr, status, thrown)

You need to dump the 2nd and 3rd parameters to find your cause, not the first one.


Well, it might help someone. I was stupid enough to put var_dump('testing'); in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected json response, and with dataType set to json defined, the request fails.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?