PDoria
PDoria

Reputation: 572

Passing an array from PhP to jQuery using JSON and $.ajax

First off, I apologise since this is my first time working with JSON.

My website has a client script that requests person data from the server. The server first queries the database (using mysql and mysqli) and then returns the data (names, ages, etc.) to the client side.

Specifically, I want to pass an associative array from the PhP side to the client side.

After doing some research, I decided to do this with AJAX JSON calls.

The client side call is done like this:

var person_id = $('#my_text_box').val();

$.ajax({
 url: 'php/upload/my_server_script.php',
 method: 'POST',                                 
 data: {id: person_id},
 dataType: 'json',
 cache: false,
 success: function(response_data)
 {
   alert(response_data['name']); //The server should return an associative array
   console.log(response_data);
 },
 error: function(jqXHR, textStatus, errorThrown) 
 {
  console.log(arguments);
  console.log(jqXHR.responseText);
  console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
 }
});

The server side calls a method that will query the database and give the details of the person with the requested ID.

$id = $_POST['id'];

function getPersonData($id) { $personData = array();

(1 - Connect and SELECT name FROM Persons WHERE id = {$id}
 2 - Fill the $personData array with result row 
 3 - Name will be saved in $personData['name'])

return json_encode($personData);

The AJAX call fails with the error 500 - Internal Server Error. When I check the contents of the server response on the browser (On Chrome, Network tab), it says there is no response (This request has no response data available).

The thing is, this code works perfect locally. But when I upload it to my cloud web server, the only AJAX calls in my website that fail are the ones that use JSON as the format for the data being transferred. The other ones work fine.

A couple of things I've tried:

None of these four worked. What could I be forgetting?

Note: The browser's log reads as follows:

Arguments[3]
0: Object
1: "error"
2: "Internal Server Error"
callee: function (jqXHR, textStatus, errorThrown)
length: 3
__proto__: Object
*(url of my script file)*

Error: Internal Server Error error [object Object] ^

Note #2: Full PhP code:

//Fetch persondata for a specific ID, and encode the data in an array in JSON format
function JSONSelectPersonDataFromID($ID)
{   
        $personData = array();  //Array or array with results

        //If querysuccess, commit. Else, rollback
        $querySuccess = True;

        //This method opens connection with root user
        $conn = OpenDBConn();

        $conn->autocommit(False);

        try
        {
         if($videoID > 0)
         {
           $sql = "SELECT name FROM Persons WHERE id={$id}";

                //Debugging
                //echo $sql . "<br>";

                $persons = mysqli_query($conn, $sql);

                if(mysqli_connect_errno($conn))
                {
                    $querySuccess = False;
                }


                if(isset($persons ) && (count($persons ) > 0))
                {
                    //Loop through every scene  
                    $personData = $persons ->fetch_array(MYSQLI_ASSOC);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                $querySuccess = False;
            }
        }
        catch(Exception $e)
        {
            $querySuccess = False;
        }

        if(!$querySuccess)
        {
         //Rollback
         $conn->rollback();
         die("Transaction failed");
        }
        else
        {
         //Commit
         $conn->commit();
        }

        //Close the connection
        DBClose($conn);

        return json_encode($personData );
}

Upvotes: 0

Views: 820

Answers (2)

aerojun
aerojun

Reputation: 1256

Does the PHP script that uses AJAX have permissions to read the other PHP Script?

Upvotes: 0

arieljuod
arieljuod

Reputation: 15838

"Internal server error" means the server crashed somewhere but for security reasons the client only get that 500 error. Check the server's error log file, there should be the real origin of the error (some real error, file and line number). You should start there.

Upvotes: 1

Related Questions