Matrix
Matrix

Reputation: 21

Why is my jQuery ajax function not firing success after PHP returns json data?

I have a jQuery ajax function which runs a php file to just return all the rows of data from a MySQL table. I can see in dev tools that my PHP file is echoing the data as json but my ajax function always runs the error function and not the success function. Am I missing something really obvious? Any help would be appreciated.

JS

$("#RUN").click(function() {
        $.ajax({
            url: 'api.php',
            data: '',
            dataType: 'json', 
            success: function(data){
                alert('Success');
            },
            error: function(){
                alert('error');
            }
        })
    });

PHP

<?php 
  $databaseName = "workingwithmysql";
  $tableName = "users";
  $connection = mysql_connect("localhost","root",""); 
  $dbs = mysql_select_db($databaseName, $connection);
  $result = mysql_query("SELECT * FROM $tableName");    
  $array = mysql_fetch_row($result);                             
?>

Upvotes: 0

Views: 137

Answers (2)

T&#39;lash
T&#39;lash

Reputation: 573

Try that :

<?php
    ob_start();
    $databaseName = "workingwithmysql";
    $tableName = "users";
    $connection = mysql_connect("localhost","root",""); 
    $dbs = mysql_select_db($databaseName, $connection);
    $result = mysql_query("SELECT * FROM $tableName");    
    $array = mysql_fetch_row($result);
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode($array);
?>

But you really should consider using PDO for your queries to databases.

Upvotes: 0

Brad Kent
Brad Kent

Reputation: 5098

Is that PHP code snippet complete??

add these two lines:

header('Content-Type: application/json');
echo json_encode($array);

Edit: also.. open the developer tools of your browser... there's probably a "network" tab... use it to view the server's ajax response.

Upvotes: 2

Related Questions