0

I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer. This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one. My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?

HTML/Jquery of the Ajax with the error:

    function BekijkGegevens() {
        $.ajax({
            type: 'GET'
            , data: {}
            , dataType: 'json'
            , url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
            , success: function (rows) {
                $('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
                for (var i in rows) {
                    var row = rows[i];
                    var datum = row[1];
                    var stand = row[0];
                    $('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
                }
                $('#output').append("</table>");
            }
            , error: function (JQXHR, TextStatus, ErrorThrow) {
                console.log(JQXHR);
                console.log(TextStatus);
                console.log(ErrorThrow);
            }
        })
    }

PHP:

<?php 
include_once('confi.php');
error_reporting(E_ALL);


if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);


$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";

$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);



$data2=array();

while ($row = mysqli_fetch_row($result))
{
    $data2[]=$row;
}


echo "{data:" .json_encode($data2). "}" ; 
}
?>

Thanks for any help that you can provide.

EDIT: Forgot to put my browser network, here it is. http://puu.sh/uzI4f/a9ed1e0be5.png

EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files: This one is used to send the key from Jquery to PHP:

<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();


if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}

?>

This one is used to get the needed information:

<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();

if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;


$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);



$data2=array();

while ($row = $result-> fetch_row())
{
    $data2[]=$row;
}


echo json_encode($data2); 
}

?>
  • If you `console.log(rows)` in your success callback do you see the data? – Jay Blanchard Mar 08 '17 at 14:11
  • 1
    Sounds like your JSON is not valid. Look at the request in the network tab and see what you have. – epascarello Mar 08 '17 at 14:11
  • 1
    You're printing broken json. `{data:` is missing quotes. – tkausl Mar 08 '17 at 14:12
  • You should take a look to your *network* tab, in your browser's development console. Paste the HTTP traffic generated by all 3 AJAX calls in here. – Eduardo Escobar Mar 08 '17 at 14:12
  • 1
    AND your PHP code shows POST, but you are doing a GET – epascarello Mar 08 '17 at 14:14
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Mar 08 '17 at 14:14
  • And your responseText shows `""` so yes, you are not returning anything from the php code. – epascarello Mar 08 '17 at 14:16
  • @JayBlanchard the success callback is not executed. – Can Yazicioglu Mar 08 '17 at 14:17
  • @epascarello The POST in my PHP is used for getting the key in the 2nd Ajax call – Can Yazicioglu Mar 08 '17 at 14:18
  • 1
    Than why are you not showing the code for the Ajax call that fails? I am surprised that works since that is retuning invalid JSON. – epascarello Mar 08 '17 at 14:18
  • The code shown above is the Ajax call that fails. The second call uses $_POST['teller'] to retrieve the key, and use it in the select statement in order to get the correct data and send it using a 3rd Ajax call (the one shown above) which fails. – Can Yazicioglu Mar 08 '17 at 14:22
  • The whole PHP script runs each time it is called by AJAX, so your PHP will fail on the the third call because there is no POST data. Have you watched the AJAX request / response in the browser's developer tools? – Jay Blanchard Mar 08 '17 at 14:29
  • 1
    You said that the PHP Code is not for the call... Now you are saying it is???? The Ajax call here DOES NOT call the PHP code since the PHP code provided is looking for a POST. So how are these two linked???? Open up the network panel, look at the Ajax request that fails, look at what the server returns. What does it return? What ever it is, it is not JSON since the parser chokes and fails. Where is the code that is returned when the GET request is made? – epascarello Mar 08 '17 at 14:29
  • I said the POST variable is not for the call. The two calls are using the same file to function. May the error lie there? – Can Yazicioglu Mar 08 '17 at 14:35
  • Yes - that is *exactly* where it lies. You're not outputting any JSON because the PHP checks to see if teller is set. Since it isn't (based on the AJAX call) nothing gets returned. Since the AJAX call expects JSON and gets nothing, it throws the error. nothing gets preserved between each of your calls to this file so you may want to rethink your logic. – Jay Blanchard Mar 08 '17 at 14:57
  • @JayBlanchard So basically I need to split this PHP script into two separate ones. Is there any way I can pass the 'teller' variable and use it in another php file to execute the needed select statement with? – Can Yazicioglu Mar 08 '17 at 15:00
  • You could store it in a SESSION variable. – Jay Blanchard Mar 08 '17 at 15:06
  • @JayBlanchard I've edited my post with the new scripts and the session varable. I am still getting the same error. – Can Yazicioglu Mar 08 '17 at 15:54
  • The last script is still testing to see if `$_POST['teller']` is set. You should test for `$_SESSION['teller']` and then run your query with the SESSION variable, not the POST variable. – Jay Blanchard Mar 08 '17 at 16:04
  • I've put the same script twice by mistake, corrected the last script. – Can Yazicioglu Mar 08 '17 at 16:10
  • What error are you getting? – Jay Blanchard Mar 08 '17 at 16:18
  • @JayBlanchard Unexpected end of JSON input – Can Yazicioglu Mar 08 '17 at 16:26
  • Then the SESSION variable is not set or you have no data for that teller. – Jay Blanchard Mar 08 '17 at 16:28
  • Add `session_start()` to the page from which you make the AJAX requests. – Jay Blanchard Mar 08 '17 at 16:35

2 Answers2

0

First, some warnings (in accordance with this link):

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?

You should test against the session variable in your second script, which should look like this:

<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();


if (isset($_SESSION['teller']))
{
    $teller = $_SESSION['teller'];
    $sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
    $result = $conn -> query($sql2);

    $data2=array();

    while ($row = mysqli_fetch_row($result))
    {
        $data2[]=$row;
    }

    echo json_encode(['data'=> $data2]);
}

?>

Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
-1
  1. Dont try to glue data to string, like this:

    echo "{data:" .json_encode($data2). "}" ; 
    

Use simple

echo json_encode(['data'=> $data2]);

It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null

  1. Declare your $data2 in the begginng, before if statement:

    $data2 = [];
    if (isset($_POST['teller'])) {
        //do stuff and redefine $data2 or fill it;
    }
    
    //always echo valid json, event if no $POST["teller"] has arrived 
    echo json_encode(['data' => $data2]);
    
Denis Matafonov
  • 2,684
  • 23
  • 30
  • I've tried to change it, and now the Ajax TextStatus Error returns:"↵Parse error: syntax error, unexpected '[', expect…47/public_html/webservices/bekijk.php on line 26↵", status: 200, statusText: "parsererror"}" – Can Yazicioglu Mar 08 '17 at 14:25
  • 1
    "It should produce the same result" actually, it shouldn't, because it produces the _correct_ result, where `data` is quoted, as JSON requires keys to be quoted. – tkausl Mar 08 '17 at 14:25
  • See edits. You dont echo json if there is no teller in $_POST – Denis Matafonov Mar 08 '17 at 14:29