0

I'm new using AJAX or jQuery and I'm trying to insert some data in a table whitout loading another page, I can't tho.

Here is my AJAX func: Edit:

function SumbitAction(act_id) {
$.ajax({
dataType: 'json',
type: "POST",
url: 'Accion.php',
data: {Action:act_id},
success: function (obj, textstatus) {
              if(obj.status==='FAIL') {
                   console.log(obj.message);
              }
              else {
                  console.log("ok");
              }
        }
});
}

And in my PHP I'm giving no arguments at the moment to test a full null insert query: Edit:

    $consultaAcciones= "INSERT INTO acciones VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$ejecAcciones = mysqli_query($conn, $consultaAcciones);
if($ejecAcciones===false){
    $response = [
'status' => 'FAIL',
        'message' => 'Accion no registrada correctamente'
    ];
}
else {
    $response = [
        'status' => 'OK',
        'message'=> 'Accion registrada'
    ];
}

header("Content-type: application/json");
echo json_encode($response);

I am getting "Error" in the console logs and I don't know what's wrong. Edit: No longer

Edit: Now it doesn't display any error, it's okay, but also doesn't show my console logs for when everything's okay, also am getting a warning message:"Cross-Origin Read Blocking (CORB) blocked cross-origin response" and a log: XHR finished loading: POST "http://url...". may it be is not correct to specify the callers of my function this way?

    function addListener(id,num)
{
  var target= document.getElementById(id);
  if(target){
    target.addEventListener("click",SumbitAction(num),false);

  }
  else{
    //console.log("Nel",id);
  }
}
  • 1
    Turn on error reporting in PHP - https://stackoverflow.com/a/21429652/296555. – waterloomatt Jul 16 '20 at 16:54
  • If you want to see anything occurred error in your PHP code, you can try this. ``. And you try `echo`. – Minwoo Kim Jul 16 '20 at 17:50
  • Also, by default, `Ajax` receives errors through a method called `error`. You can try this. `error: function (request, status, error) { alert('Code:' + request.status + '\n' + 'message:' + request.responseText + '\n' + 'error:' + error); }`. – Minwoo Kim Jul 16 '20 at 17:55
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Jul 18 '20 at 14:03

1 Answers1

1

There are 2 problems in the code.

First, if(('error')) { will always evaluate as true. 'error' is just a string, and that is truthy.

You probably meant to compare that string against something, maybe (also removing doubled parentheses):

if (textstatus === 'error') {

Next, textstatus is the status of the request, not of your code. It will be error when, for eg, there is a 404, or a 500 response from the server. If your INSERT fails, the http request will still be successful, and textstatus will not be error.

You might want to check textstatus in an error() callback, if you want to add one. But within the success() callback, you probably want to be checking what your code returned. In this case, that is obj.

But looking at the PHP, it does not return anything predictable that the JS can use. It returns nothing if the query works. If it fails, it returns a string that begins with Error but then shows a MySQL error, which we won't know ahead of time, so you can't test for it in JS.

It would be better to simply return some true/false, OK/fail type msg, for eg:

// ... rest of your code
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
    echo "FAIL";
} else {
    echo "OK";
}

And in your JS:

if (obj === 'FAIL') {
// ... etc

If you actually want to pass a message back from the PHP, you should have it echo out a JSON object, eg:

$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
    $response = [
        'status' => 'FAIL',
        // You shouldn't reveal internal details about errors
        // so don't return mysqli_error().  Maybe log it, and 
        // display something generic to your users.
        'message' => 'There was a problem'
    ];
} else {
    $response = [
        'status' => 'OK',
        'message'=> ''
    ];
}

header("Content-type: application/json");
echo json_encode($response);

In your JS:

$.ajax({
    // ...
    // specify we will get a JSON response
    dataType: 'json'
    // ...
    success: function (obj, textstatus) {
        if (obj.status === 'FAIL') {
            alert(obj.message);
        } else {
            // all ok ...
        }
});
Don't Panic
  • 13,965
  • 5
  • 32
  • 51