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...)

5
  • Have you used any developer tools to ensure the AJAX call is posting the right data? Commented Nov 22, 2013 at 3: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? Commented Nov 22, 2013 at 4: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? Commented Nov 22, 2013 at 4: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? Commented Nov 22, 2013 at 4: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 Commented Nov 22, 2013 at 4:25

5 Answers 5

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");
      }
});
}
Sign up to request clarification or add additional context in comments.

3 Comments

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!
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 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 :)
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);

2 Comments

data: {'vals' : val} or data {vals : val} Both are working. The issue does not come from here.
where do we set this
1

Instead of:

$val = $_POST["vals"];

use this:

if (isset($_POST['vals']) {
    $val = $_POST['vals'];
}

5 Comments

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 - If $_POST["vals"] is not set it won't return null, it will error with the above. See here for reference - stackoverflow.com/questions/4261133/…
@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.
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.
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.
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");
    }
);

2 Comments

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"
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!
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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.