Undefined Index in php: transfering variables from Ajax to php - javascript

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

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:
http://api.jquery.com/jquery.ajax/
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));

<?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";
}
?>

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

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.

Related

how to send POST data with jquery ajax to PHP function

I want to send POST request with jquery AJAX to PHP function
but it don't give any respond.
JQuery
$.ajax({
url: 'ListProduk.php/SelectData',
type: 'POST',
success: function(data)
{
console.log(data);
}
});
PHP
<?php
include 'database.php';
function SelectData(){
$sql = "SELECT * FROM MsProduk";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
return json_encode($arr);
}
?>
Any ideas how to fix it?
When not using url rewriting (google mod_rewrite and pretty URL's), your parameters typically are going to be passed as a normal HTTP GET request. Here is an example of how your URL structure might look:
url: 'ListProduk.php?action=SelectData'
And then, in your PHP, you might handle it based on the action that is requested (Note: The action parameter is not something specific to web development, it's just an arbitrary name I assigned. It could be foo=SelectData as well)
if ($_POST['action'] == 'SelectData') {
// Run the code for selecting data
}
Finally, you wouldn't want to "return" the JSON data. You need to output it with the correct headers. It would look something like this:
header('Content-Type: application/json');
echo json_encode($data);

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

How can i parse php variable to my javascript function result?

I have a script, i have to parse javascript variable to PHP file, i've no problem with this function, in my console i can see that the username variable is sent, it's fine .
$.post("user_add-js.php", { username: username })
.done(function(data) {
alert("Data Loaded: " + data);
});
In my user_add-js.php file , i wrote the variable $data with a value but i can't return the value "test", the variable is empty . I guess i forgot to add something in my PHP code to parse the value from PHP to javascript .
<?php
$data = "test";
?>
you need to set the header
header('Content-type: application/json');
and also you have to encode the variable to json like this
echo json.encode($data);
once you get the result to javascript you should parse the json code
data = JSON.parse(data);
This solution helps you get you data from PHP in any format ( object, array, string ... )

PHP returning empty POST array

JavaScript jQuery post:
var animals = {
animalsArray: [],
tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
console.log(response);
}, "json");
PHP handler:
echo json_encode(print_r($_POST, true));
// Array
// (
// )
Why is the array empty? I'm posting data but the response returns an empty array.
You are encoding the data as JSON, which isn't a format PHP handles natively for form submissions.
Remove var sendMe = JSON.stringify(animals); and pass animals to $.post instead of sendMe. jQuery will encode it using one of the standard formats supported by HTML forms and PHP.
Alternatively see this question for how to get the raw request body.
Also:
echo json_encode(print_r($_POST, true));
json_encode and print_r are both functions that take a data structure and express it as a string. Use one or the other, not both.

Categories

Resources