2

Hello I tried to transfer variable from ajax to php, but php file keeps throwing me the following:

Undefined index: vals in /Applications/XAMPP/xamppfiles/htdocs/fang_sophie/project/sign in-out/bin/readall2.php

Ajax reads like this:

<script>
var var_data = "Hello World";

$.ajax({ url: 'bin/readall2.php',
 data: {'vals' : var_data},
 type: 'post',
 dataType:'json',
 success: function(output) {
              alert(output);
          },
  error: function(request, status, error){
    alert("Error: Could not delete");
  }
});
</script>

Php reads like this:

<?php
  session_start();
  $hello = '';
  $_SESSION['hello'] = $_POST['vals'];
  echo($hello);
?>

Why doesn't it work? Please help :)

  • do you open the php file directly or you see the response in browser? – Akam May 25 '16 at 21:59
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Jonnix May 25 '16 at 21:59
  • @JonStirling: I don't think there's any undefined variable here! – Julie Pelletier May 25 '16 at 22:01
  • @JonStirling How is this a duplicate of that? The AJAX code is clearly sending the POST variable that he tries to access. – Barmar May 25 '16 at 22:01
  • @Barmar Are you joking? – Jonnix May 25 '16 at 22:03
  • @JuliePelletier The link is about undefined variables AND undefined indexes. Please read to the end... – Jonnix May 25 '16 at 22:04
  • @JonStirling he might open the file directly... – Akam May 25 '16 at 22:04
  • @JonStirling No I'm not. I see people reflexively close any question with an undefined index or variable as a dupe of that, without checking whether there's something more complicated going on. – Barmar May 25 '16 at 22:05
  • Are you seeing the error from the `alert(output);` line? I'm not sure, but `type: 'post',` might need to be uppercase like `type: 'POST',`. Also, in the PHP, try doing a `var_dump($_POST);` to see what's actually getting to the script. – Anialation May 25 '16 at 22:06
  • @Barmar We'll have to agree to disagree. – Jonnix May 25 '16 at 22:10
  • @JonStirling I'm afraid Barmar's right on this one. Problem was the OP is trying to output JSON data where there's no JSON at all. They just used the wrong dataType, which should have been `text`. That, and maybe they're using the entire code in the same file. – Funk Forty Niner May 25 '16 at 23:21
  • @Fred-ii- I changed the dataType to text, and the problem still remains. – Shushu Fang May 25 '16 at 23:24

4 Answers4

1

One problem here is that you're trying to output JSON dataType:'json', where you don't have JSON to start with. Consult my footnotes also.

You need to use a text data type.

dataType:'text',

By the way, this won't echo anything at all (in the alert), since $hello is empty:

session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);

You (may) want to echo the session array taken from the POST array, which is the logical thing to do:

echo($_SESSION['hello']);

Reference:


Foonotes:

If by any chance you may be trying to access that (PHP) file directly, or your entire code is in the same file, then you need to use a conditional statement for it.

I.e.:

session_start();

if(!empty($_POST['vals'])){
    $hello = '';
    $_SESSION['hello'] = $_POST['vals'];
    echo($_SESSION['hello']);
}

That, and/or use two separate files.

In regards to JSON; if you really want/need to use it, then set it back to dataType:'json', but use json_encode() for it and replacing echo($_SESSION['hello']); with and assigning the $hello variable to the session array:

$hello = $_SESSION['hello'];
echo(json_encode($hello));
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Thanks. I have tried that, but the problem remains. It's still "Undefined index vals". – Shushu Fang May 25 '16 at 23:21
  • @ShushuFang Sorry, but I find that rather hard to believe. How are you using your code, in the same file or two separate files? If two, see my answer again, I've added a conditional statement. I've tested this with no issues and no undefined index notices. Read my answer again and in its entirety and make sure you uploaded the new files and there's no caching happening. – Funk Forty Niner May 25 '16 at 23:24
  • @ShushuFang Another thing; did you load the jQuery library? – Funk Forty Niner May 25 '16 at 23:28
  • @ShushuFang That's great and you're most welcome! *Cheers* – Funk Forty Niner May 25 '16 at 23:33
  • @ShushuFang It was a 2-part issue also. Glad to have been of help and welcome to Stack! *Yeah, you gotta love the magic* ;-) – Funk Forty Niner May 25 '16 at 23:34
0
<?php
//first start session
session_start();

//set header to json and UTF-8 encoding
header('Content-Type: application/json;charset=utf-8');


//check if $_POST['vals'] is set first using isset() to prevent notice
//undefined index

if(isset($_POST['vals'])){
  echo "value of vals is: ".$_POST['vals'];
}else{
  echo "vals not set";
}
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Akam
  • 1,089
  • 16
  • 24
  • 1
    But why wouldn't `$_POST['vals']` be set when it's in the `data:` option? This seems to be a band-aid over the root problem. – Barmar May 25 '16 at 22:06
  • This doesn't solve the root problem though. The value is not transferred successfully from php file to html file. – Shushu Fang May 25 '16 at 23:01
  • @ShushuFang: my answer solved your issue at first, I also asked u did u opened the file directly from browser?!!! u didn't answered, I corrected the logic for you here... Apply it and see if u got any error I will delete my answer. – Akam May 25 '16 at 23:55
  • Your answer didn't solve my issue though. I didn't open the file directly from the browser. sorry – Shushu Fang May 26 '16 at 00:27
  • @ShushuFang then what solved your issue please tell me because I want to learn? – Akam May 26 '16 at 00:32
  • @Akam I made two mistakes. First dataType should be text instead of Json. Second, it should be echo($_SESSION['hello']); instead of echo($hello); Thanks a lot for helping out Akam. – Shushu Fang May 26 '16 at 21:20
-2

The correct answer is you are reading the wrong variable:

$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);

It should be:

echo $_SESSION['hello'];

If you want the session data. For the undefined index, var_dump out your $_POST variable: var_dump($_POST);

If the $_POST variables do not match, or you get back an empty array, it was never transmitted to the server.


Original wrong answer:

When JQuery has "processData" flag set to false, it doesn't encode the data and requires the user reads it from the php://input stream.

Unencoded JSON is not sent into POST requests. For the quickest fix, try this:

parse_str(file_get_contents("php://input"), $vars);
// This will fill $vars with any data sent over to PHP.
var_dump($vars);

$vars should now be populated with the data you want. If $vars is empty, you are not transmitting the data.

Michael Ryan Soileau
  • 1,763
  • 17
  • 28
  • Where do you see him converting it to JSON? – Barmar May 25 '16 at 22:03
  • It doesn't say `data: JSON.stringify({ vals: var_data })` – Barmar May 25 '16 at 22:04
  • No it doesn't. `dataType` specifies how the **response** is interpreted, not how the parameters are sent. – Barmar May 25 '16 at 22:07
  • Read the [`$.ajax`](http://api.jquery.com/jquery.ajax/) documentation. If `data:` is an object, it's converted to a URL-encoded query string. – Barmar May 25 '16 at 22:09
  • You are right, sort of. The issue is whether you set processData to true. processData: false Will not encode the data, which is how I'm used to dealing with it in APIs. Since this wasn't set, my answer is wrong. My apologies. – Michael Ryan Soileau May 25 '16 at 22:14
  • Your answer doesn't explain why the notice is thrown to begin with. Regardless of what is returned, the notice is an entirely separate entity of its own. *Undefined index: vals in ...* means that `$_POST` does not contain an index of `vals`.. for whatever reason. – mferly May 25 '16 at 22:21
  • You're right, but initially I thought it was because the information was being sent over unencoded, which means the $_POST variable doesn't catch it, but @Barmar is right, JQuery will automatically encode the data and set the $_POST variable unless processData is flagged to false. – Michael Ryan Soileau May 25 '16 at 22:23
-2

In your ajax request, the format of return is expect to be JSON. and you are returning a string. You just need to add json_encode in your return line of php:

    session_start();
    $hello = '';
    $_SESSION['hello'] = $_POST['vals'];
    echo(json_encode($hello));