Shushu Fang Shushu Fang - 6 months ago 35
PHP Question

Undefined Index in php: transfering variables from Ajax to php

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

Answer

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