0

If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.

This is my ajax, which only works because I'm printing 'true' on the server:

$(document).on("click", "#btnEditarInstructor", function(event) {
  event.preventDefault();
  let rfc = $(this).attr("value");
  $.ajax({
    type: "POST",
    url: "../utils/ajax/ajax_consulta_instructor.php",
    data: {
      rfc: rfc,
    },
    dataType: "json",
    succes: function(response) {
      if (response == true) {
        // alert(response);
      }
    },
    error: function(request, status, error) {
      var val = request.responseText;
      alert("error" + val);
      alert(status);
      alert(error);
    },
  });
})

This is my PHP code:

$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
  echo "true";

  $datos['status'] = 'OK';
  $datos['nombre'] = $row['nombre'];
  $datos['apellidos'] = $row['apellidos'];
  $datos['email'] = $row['email'];
  $datos['tipo_promotor'] = $row['tipo_promotor'];
  echo json_encode($datos);

}

By the way, with that code, I get this error on the alert:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data

I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)

IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • You are echo-ing too many times inside the loop. This is json you suppose to echo once *after* the loop – IT goldman Jul 07 '22 at 21:28
  • ALso get rid of `echo "true";` – Barmar Jul 07 '22 at 21:29
  • 1
    You also have a typo: `succes:` should be `success:` – Barmar Jul 07 '22 at 21:30
  • `if I don't print anything else besides the JSON I need, stops working`...stops working how exactly? What response do you get from the server then, precisely? What status code? Any JavaScript console errors? Clearly the current version fails because you can't print "true" and then a separate JSON object - that isn't parseable as one coherent block of JSON, so jQuery will complain. But if you echo nothing except valid JSON there should be no issue (although you then can't use `if (response == true)` to test it, you'd have to look at a specific property).How many rows does your SQL query return? – ADyson Jul 07 '22 at 21:31
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jul 07 '22 at 21:32
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Jul 07 '22 at 21:32
  • If I don't do the echo 'true', I get the JSON as I expect, in Network->Answer, but success function still not working. I added the echo 'true' just for testing an answer from another question. I always get status code 200, as I said before, success function only works for me IF I print something else besides my JSON. – Luis Villegas Jul 07 '22 at 21:40
  • That doesn't make any sense, there must be more to it. Did you correct the typo "success" instead of "succes" and test again? – ADyson Jul 07 '22 at 21:41
  • Yes, I did and I was expecting to solve the problem with that simple typo that couldn't see, but still not working. – Luis Villegas Jul 07 '22 at 21:47

2 Answers2

2

If you're returning JSON, you can only echo the JSON once, not each time through the loop.

If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.

You also can't echo anything else, so the echo "true"; lines are breaking it.

And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.

$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];

if($row = mysqli_fetch_array($sql_run)){
    $datos['status'] = 'OK';
    $datos['nombre'] = $row['nombre'];
    $datos['apellidos'] = $row['apellidos'];
    $datos['email'] = $row['email'];
    $datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I added the echo 'true' for testing, because I wasn't making my success function to work without it, I tried your code but I'm getting 'Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data' when trying to console.log parsed JSON, if I do console.log(response) without the parse, I don't get anything in console. Alert only shows [object Object]. – Luis Villegas Jul 07 '22 at 21:45
  • Use the Network tab of the browser to see the full response that's being sent. You may be sending something before this loop. – Barmar Jul 07 '22 at 21:47
  • I copied and pasted the code from your answert to test it, in the Network tab I'm getting this as answer: [{"status":"OK","nombre":"asdasdasdas","apellidos":"asdasdasdasd","email":"asdasdasasdasdasdasdasdasdasdasdasdas","tipo_promotor":"Deportivo"}] how can I parse the data? JSON.parse not working. I'm not sending anything before the loop, all I have before those lines is the 'require' for the connection do DB file. – Luis Villegas Jul 07 '22 at 21:55
  • Thanks, I figured out how to access to the information, Is it really neccesarry to return an array with the object inside of it? How could I just return the object I need? What possible cons would that have? – Luis Villegas Jul 07 '22 at 22:21
  • 1
    You have a loop to process the query results, doesn't that mean there can be more than one row? How would you return that without putting it in an array? – Barmar Jul 07 '22 at 22:38
  • Actually, there is always only 1 row, rfc is the primary key, thats why I ask about returning only 1 object instead of an array of objects. – Luis Villegas Jul 08 '22 at 16:33
  • I've updated the answer to remove the loop and array. – Barmar Jul 08 '22 at 16:37
-2
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
  rfc: rfc,
},
dataType: "json",
success: function (response) {
  if (response == true) {
    // alert(response);
  }
},
error: function (request, status, error) {
  var val = request.responseText;
  alert("error" + val);
  alert(status);
  alert(error);
},
});