Query works but PHP does not return the values

3

Hello, I am making a request to searchRand.php, in the php I make a query to obtain data. And I save it in the $ to_return variable. But when returning the value of $ to_return does not return anything. Being in the php command print the variable $ to_return before returning it and if it contains values but the ajax does not receive anything. Please help, I do not know what's happening.

Ajax code:

$(document).ready(function() {
$.ajax({
        type: "POST",
        url: "access/searchRand.php",
        dataType: "json",
        success: function (response) {
            console.log(response)
        }
    });
 });

PHP code:

<?php
require 'dbconn.php';

if($qry = $conn -> query('SELECT * FROM producto')){
    while($row = $qry -> fetch_assoc()){
        $to_return[] = $row;
    }
    echo json_encode($to_return);
    $conn->close();
}else{
    $conn->close();
    return json_encode(array('status' => 'internal error'));
}
?>
    
asked by Samuel Viema 15.11.2018 в 10:42
source

2 answers

3

As found by @PHPMyguel, the identified error is the use of a basic array with json_encode ().

There are 3 points that I would recommend to understand better what is happening:

  • Error handling: Not everything will be perfect. Defining an error function in the ajax will let you know when something goes wrong.
  • Use a single point of exit / return in the PHP : This gives you more control of the flow of data in a function.
  • Declare the variables before using them : Declare $to_return in the field where it will be used, so the language allows it in another way.

Something like this:

ajax code:

$(document).ready(function() {
$.ajax({
        type: "POST",
        url: "access/searchRand.php",
        dataType: "json",
        success: function (response) {
            console.log(response)
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
 });

PHP Code:

<?php
require 'dbconn.php';

$ret_val="";
if($qry = $conn -> query('SELECT * FROM producto')){
    $to_return[] = "";
    while($row = $qry -> fetch_assoc()){
        $to_return[] = $row;
    }
    $ret_val = json_encode(array("data" => $to_return));
    $conn->close();
}else{
    $conn->close();
    $ret_val = json_encode(array('status' => 'internal error'));
}

echo $ret_val
?>

Simplified PHP code (suggested by @ A.Cedano):

<?php
require 'dbconn.php';

$ret_val=array();
if($qry = $conn -> query('SELECT * FROM producto')){
    $to_return[] = "";
    while($row = $qry -> fetch_assoc()){
        $ret_val[] = $row;
    }
    $ret_val = json_encode(array("data" => $to_return));
}else{
    $ret_val["status"] = 'internal error';
}

$conn->close();
echo json_encode($ret_val)
?>
    
answered by 15.11.2018 в 11:32
1

You are specifying that the file returns a JSON, when in your code (if the connection does not work), it does not return anything.

Why?

You are trying to directly capture the result of searchRand.php via ajax, when searchRand.php does not return any results if the connection fails. If I execute your function via php, it will return the result correctly (because you perform a return), since php understands your code, however, a browser (or other access interfaces that do not use php) does not.

How do I solve it?

In your code, simply change the return by echo:

<?php
require 'dbconn.php';

if($qry = $conn -> query('SELECT * FROM producto')){
    while($row = $qry -> fetch_assoc()){
        $to_return[] = $row;
    }
    $conn->close();
    echo json_encode($to_return);
}else{
    $conn->close();
    echo json_encode(array('status' => 'internal error'));
}
?>

Also trust that you are doing a POST without passing data , POST is used to send data, to only receive you have to use GET.

    
answered by 15.11.2018 в 13:31