5

I'm trying to send an ajax POST to a php file, however the php file sends a notice of "undefined index", and the php file never seems to receive the value i'm trying to send it. I've been searching for the answer to why this isn't working correctly, so hopefully someone can give me some insight.

My javascript function receives a value from the html, and receives the correct value. (it's "1" in this case)

    function deleteMediaFromDatabase(val)
    {

  $.ajax({ url: 'deleteMediaFromDatabase.php',
         data: {vals : val},
         type: 'post',
         success: function(output) {
                      alert(output);
                  },
          error: function(request, status, error){
            alert("Error: Could not delete");
          }
  });
}

Here is part of my php file that should receive the post:

    <?php

 ini_set("display_errors", "On");
 error_reporting(E_ALL);

    $val = $_POST["vals"];

    // create connection
    $con = mysqli_connect(<stuff you don't care about>);

  error_log($val . ' is the value', 3, "./error.log");

?>

I am, however getting this error message from php:

Notice: Undefined index: vals in /xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9

And my javascript always outputs the alert in the error: "Error: Could not delete"

I know this question has been asked and answered many times, however unless I'm skipping over something small, my code, to me, looks correct. (but doesn't it always...)

ssrobbi
  • 496
  • 1
  • 5
  • 15
  • Have you used any developer tools to ensure the AJAX call is posting the right data? – Machavity Nov 22 '13 at 03:54
  • Yes, I have used the inspect element feature on google chrome (the network section) which has confirmed what is being sent is the correct data, however the status is listed as (cancelled). Is that what you may have been referring to? – ssrobbi Nov 22 '13 at 04:07
  • When I put in breakpoints and step through my code, it worked perfectly. However, when I take out the breakpoints and run it, it errors out. This is actually being executed inside of a form. when the submit button is being pressed , the form is submitting, which changes the database. Could the fact that this is inside of the form create a race condition? – ssrobbi Nov 22 '13 at 04:16
  • The error message is saying your POST value isn't set. So there is a disconnect somewhere. But you're triggering this with a form submit? – Machavity Nov 22 '13 at 04:20
  • I'm dynamically adding a table to my html that mimics the tables in the database, putting a delete button next to each row. The value of the delete button is the same as the id in the table. When the button is pressed, it invokes its "onclick='deleteMediaFromDatabase(this.value)'". The value is collected via jquery and sent to the php file via post, so that i can delete a row in the database according to that value, and also delete a file from a server (whose filepath is stored in the database). edited: correct onclick – ssrobbi Nov 22 '13 at 04:25

5 Answers5

2

There is error in syntax of jquery.. You missed out syntax of data. This should be like this-

function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
     data: {'vals' : val},
     type: 'post',
     dataType:'json',
     success: function(output) {
                  alert(output);
              },
      error: function(request, status, error){
        alert("Error: Could not delete");
      }
});
}
Vishwas
  • 6,967
  • 5
  • 42
  • 69
  • This did it! ( I didn't include the dataType: 'json', it didn't seem to like that). I have been banging my head against a wall about this for days. thanks for answering! – ssrobbi Nov 22 '13 at 04:53
  • that's the part I changed. I didn't put in your suggestion of "dataType: 'json',". I tried putting in that suggestion but it didn't work correctly for some reason. – ssrobbi Nov 22 '13 at 05:11
  • 1
    @ssrobbi dataType specifies the type of **response** jQuery is expecting back from the server, so only specify dataType as json if your PHP is **returning** json data :) – Leandri Sep 03 '14 at 12:09
1

The problem can come from the dataType not being specified or that the dataType specified does not match thus returned by the server.

Explicitely set the dataType, e.g. dataType:'json'

and make sure that your script returns data that is "encoded" in the data type that you chose, e.g. in PHP:

echo json_encode($something);

OuzoPower
  • 230
  • 2
  • 11
1

Instead of:

$val = $_POST["vals"];

use this:

if (isset($_POST['vals']) {
    $val = $_POST['vals'];
}
Tom
  • 4,257
  • 6
  • 33
  • 49
yomiros13
  • 11
  • 1
  • I don't see the difference. If `$_POST["vals"]` is not set, it will return null. If `$val` is not assigned it is also null. So whether you assign it with null, or don't assign it at all, the result will always be the same. – Ivar Mar 16 '17 at 10:30
  • @Ivar - If `$_POST["vals"]` is not set it won't return null, it will error with the above. See here for reference - http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef – Tom Mar 16 '17 at 10:40
  • @thebluefox Not an error, a notice. And the same notice will be shown if you try to access `$val` in this case, because it is is undefined. It's just moving the problem. – Ivar Mar 16 '17 at 10:43
  • Unless `$val` is declared previously. Doing this without the `isset()` check is poor coding practice, in my opinion. Fix both problems, don't just ignore the first. – Tom Mar 16 '17 at 10:45
  • I agree on that. But as it is stated here, it will not make any difference. In both cases it DOES return null if it is undefined, it only also prints a notice if you have that set to. Nevertheless will this not solve the question. The success handler of `$.ajax` should be triggered when the server returns a 200~299 status code. A notice will not change this. – Ivar Mar 16 '17 at 11:01
0

Change Ajax syntax...

$.ajax({
    type: "POST",
    url: 'deleteMediaFromDatabase.php',
    data: {'vals' : val},//Have u tried this
    success: function(output) {
        alert(output);
    }
    error: function(request, status, error){
            alert("Error: Could not delete");
    }
);
Nandakumar
  • 1,071
  • 2
  • 11
  • 30
  • 1
    Progress! Now it successfully sends the ajax post. it alerts the output to me as coded, however the output is "Notice: Undefined index: vals in /xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9" – ssrobbi Nov 22 '13 at 04:41
  • I'm not sure whether that would work, because you would just be sending a string, however not an array with a key and value, which is why I suspect it replied with undefined index. Thank you for answering though! – ssrobbi Nov 22 '13 at 04:54
0
$val = $_POST["vals"];

I got same problem , i tried declaring the variable as global , that solved my problem.

 global $val;
 $val = $_POST["vals"];

and always check isset($_POST["vals"])