Undefined index:usernames - javascript

I’m trying to pass php variable to another class using ajax to another class known as post.php. It keep saying in another class post.php that “undefined index:usernames” when I try to print it in another class as $echo $nameOfUser can anyone reckon what am I doing wrong? Thanks
index.php
<?php
session_start();
?>
<html>
<head>
<script src=“ https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js ”</script>
</head>
<body>
<?php
global $username;
$nameOfUser = $_SESSION['name'];
?>
<script>
var username = '<?php echo $nameOfUser ?>';
console.log(username); //it prints the right username here
$.ajax({
type:'POST',
url: 'post.php',
data: {function : 'testing', usernames: username},
success: function() {
alert('success');
}
});
</script>
post.php
<?php
session_start();
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
?>
<html>
<head>
</head>
<body>
<hr>
<?php
$username = $_POST['usernames'];
echo $username; // it says here undefined index usernames
if ($functionname == 0){
testing($username);
}
function testing($username) {
echo 'my name is: '; //it prints that
echo $username;
}
?>
</body>
</html>

$_POST[...] reads data from the request.
When you make a POST request to the URL, the data in that request will be available to the PHP handling that URL.
When you make another, separate request, to the URL (or another URL that uses some of the same code) then it will have access to that second request.
It won't have access to the data from the first request.
If you want to persist that data between requests then you need to store it somewhere (such as a session or a database) and retrieve it when you want to use it.

Your ajax request type is 'POST' and you should use $_POST instead of $_GET.
Or you can use $_REQUEST variable that containt $_GET, $_POST and $_COOKIE.

Related

Passing PHP variable via AJAX to PHP variable in another DIV

I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX. I want my website to display the results of Python script. I can do that.
The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes. Usually the user has to keep reloading the page to get a current status. I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.
The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.
If possible, one PHP file (index.php). Here is the skeleton of what I'm looking to do. My get_status function works, but I'm at a loss on the rest of it.
Thank you.
EDIT: Code updated with minor tweaks spotted by the commenters.
<html>
<body>
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
var java_status = <?php echo json_encode(get_status) ?>;
// I have no idea how to pass a variable from PHP thru javascript to PHP on the
// same page. Trying to pass on results of get_status function every 5 seconds.
setInterval(function(){
$.ajax({
url: "index.php"
type: "POST"
dataType: "json"
data: ({status: java_status}),
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
<div id="status_div">
<?php
$new_status = json_decode(data);
?>
// I have no idea how to get that status variable here.
The Garage Door Status is: <?php
echo $new_status;
?>
</div>
</body>
</html>
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:
PHP Script - php_python.php
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
get_status(); // execute the function
?>
HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)
You also need to separate <script> tags, using one to load the jQuery library and another to describe your JavaScript functions.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){ // you need a document ready handler if you put the script at the top of the page
setInterval(function(){
$.ajax({
url: "php_python.php",
type: "POST",
dataType: "text",
success: function(data){
$("#status_div").html('The Garage Door Status is: ' + data);
}
})
}, 5000);
});
</script>
</head>
<body>
<div id="status_div"></div>
</body>
</html>
If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.
Create a page and named it status.php
status.php include these code:
$status = shell_exec('python /path/to/garage_door/myq-garage.py status');
echo $status;
Make another page index.php and include-
<div id="status_div">
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
url: "status.php",
dataType: "html",
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
Hope this will help you
If you are using ajax, you can make your life very easy:
function_status.php:
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
return $status; //avoid echo in such functions, try to not produce side effects
}
ajax_server.php:
<?php
require_once("function_status.php");
echo get_status();
index.php:
<?php
require_once("function_status.php");
?>
<html>
<body>
<div id="status">
<?php echo get_status(); ?>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript">
( //run function immediatly
function($){ //in this anonymous function, $ is always jQuery
function updateStatus(){
$.ajax({
url: "ajax_server.php"
type: "POST"
dataType: "json"
data: ({status: 1}),
success: function(data){
$("#status").html(data);
}
});
}
//first call it onload
$(function(e){
updateStatus();
}
//and then every 5 seconds
setInterval(updateStatus, 5000);
);
}
)//run function immediatly
(jQuery); //pass parameter jQuery to immediate execution of anonymous function
</script>
</body>
</html>
it is not a very clean way, and i used the <?php echo get_status(); ?> only, because your python script takes 4 seconds, so you would have no status for the first 4 seconds.
else you could change it to index.html and have a nicely seperated html and php, if you anyway want to populate the html with ajax.
if you really want to hack it into one file, you need an
if(isset($_POST['status'])){
echo get_status();
}else{
//output the html around the whole thing
}

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
$answerPoint = intval($_GET['radiobtn']);
$qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$lastid = $connect->insert_id;
if($lastid>0) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}
}
?>
I think that the problem may lie in the row where: if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) { ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function goBack() {
window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
if($('.radiobtn').is(':checked')) {
var radiobtn = $('.radiobtn:checked').val();
var qid = $('#qid').val();
var answer = $('input[name=answer1]:radio').val();
$.ajax(
{
type: "GET",
url: 'test.php',
dataType: "json",
data: "radiobtn="+radiobtn+"&qid="+qid,
success: function (response) {
if(response.status == true){
alert('points added');
}
else{
alert('points not added');
}
}
});
return false;
}
});
});
</script>
</body>
The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?
First, your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),
Second, I'd suggest using POST instead of GET:
type: "POST",
which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;
Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
console.log('here');
UPDATE:
Fourth: You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",
After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];
That should return the correct last insert id, if that was where your error was occurring.
mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id, because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.
if($connect->query($sql2)) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}

How to create AJAX response into sessions in PHP?

I want to create my AJAX response into sessions in PHP. Here is my code, when I click this button:
<input type="button" id="callfunction" value="submit">
I am calling this jQuery:
$(document).ready(function(){
$("#callfunction").click(function(){
$.ajax({
url:"ajax.php",
type:"POST",
data:"first_variable="+first_variable+"&second_variable="+second_variable,
success:function(resp)
{
// can I create my resp into session here....?
}
});
});
});
In ajax.php page I have some this values $first_variable and $second_variable:
ajax.php
$first_variable = $_POST['first_variable'];
$second_variable = $_POST['second_variable'];
echo $first_variable;
echo $second_variable;
Now in alert resp I vl get an alert message of first_variable and second_variable
Now my question I want to convert this two variables into session so that I can use this in that page with out passing it as hidden variables, is there any way we can convert it to sessions in the response function or I am going some where wrong?
In ajax.php you have to initialize session_start(); if you do not initialize your session will not work. Read on php.net session_start()
session_start();
$first_variable = $_POST['first_variable'];
$second_variable = $_POST['second_variable'];
$_SESSION['first_variable'] = $first_variable;
$_SESSION['second_variable'] = $second_variable;
Create session in ajax.php itself
ajax.php
$first_variable = $_POST['first_variable'];
$second_variable = $_POST['second_variable'];
echo $first_variable;
echo $second_variable;
$_SESSION["first_var"] = $first_variable;
$_SESSION["sec_var"] = $second_variable;
Creating session after getting response doesn't make any sense,
So create the sessions before generating the response,
In ajax.php
<?php
start_session(); // Since we are using sessions;
$first_variable = $_POST['first_variable'];
$second_variable = $_POST['second_variable'];
$_SESSION[first_variable] = $first_variable;
$_SESSION[second_variable] = $second_variable;
echo $first_variable;
echo $second_variable;
?>

How can I attach the POST variable values to a new SESSION variable in AJAX and call it from other script?

I checked the accepted answer of this question it but didn't help
I'm trying to make an AJAX Post Request to sumbit my signup form, the ajax.php file will check the entered information, example passwords match or not, and then attach the $_POST variable to a $_SESSION variable so that I can call the submitted data from any other page later.
Ajax.php
...
if ($everythingValid) {
// add this user to db
$_SESSION["signup_details"] = $_POST;
echo "SUCCESS#".$core->signupPaymentUrl($package); // tried without this line but didn't work
exit(); // tried without this line but didn't work
} else {
foreach ($errors as $e) print "<br>".$e;
exit();
}
...
The jquery code that I'm using to call the file is the below:
var form = $('#signup');
$("#submit").click(function() {
$.ajax( {
type: "POST",
dataType: 'html',
crossDomain: true,
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
if ("SUCCESS" === $.trim(response.split('#')[0])) {
// user created, redirect to payment page
var paymentUrl = $.trim(response.split('#')[1]);
window.location.href = paymentUrl;
} else {
$("b#signupErr").hide();
$("b#signupErr").html(response);
$("b#signupErr").fadeIn();
}
}
} );
});
After submitting the form, I successfully get redirected to the payment Url, however, after accessing the page where I want to use my session, I cannot figure out how to retrieve my session although I'm pretty sure that I have included session_start in both of ajax.php and completeOrder.php and no blank spaces before the opening php tag.
here is the line that I included in both files :
if(!session_id()) session_start();
I tried to var_dump the $_SESSION variable on ajax.php and It looks okay. However when I var_dump the session variable on completeOrder.php it shows me NULL
Finally here is the completeOrder.php content
if(!session_id()) session_start();
require_once("core.php");
$core = new coreOptions();
$email = $_SESSION["signup_details"]["email"];
$password = $_SESSION["signup_details"]["password"];
$package = $_SESSION["signup_details"]["pkg"];
$options = $core->attachOptions($package);
if ($core->registerUser($email,$password,$options,$package))
$core->redirect("registrationCompleted.php");
in the completeOrder.php file remove if(!session_id()) session_start();
and then only add session_start(); and it will do the trick!
session_id() will return an empty string in ajax.php if there was no call to session_start() before. So the in ajax.php session_start() will never be called and the content of $_SESSION won't be stored anywhere.
So just use:
session_start();
in both files.

Sending data to the clicked url via AJAX/PHP

I can't seem to send data to the link that I click on. All I'm getting is an undefined index in my php file.
Click me
('a').click(function(){
href = "output.php";
$.post( 'output.php', { output: "hello"},
function( data ) {
window.location = href;
}
);
return false;
});
The ajax successfully sends, but the page redirected to the output.php page with errors saying the index "output" doesn't exist.
<?php
$content = $_POST['output'];
echo $content;
?>
Help anyone? This is so confusing.
It's because output.php is being loaded twice: once on your Ajax request, and once when you change window.location.
The second time, there's nothing in $_POST, because the browser isn't making a post request at that point.
ADDED FOR CLARITY:
If you use Firebug, and take out the window.location line, you should see the Ajax request go out and the response from the server.
Okay. I'm still not sure what you're trying to do, or how the code you posted relates to it. But if you want to send data to the server via Ajax, and then have the browser load output.php and display that data, you could do something like this:
In your PHP:
if(isset($_POST["output"])){
$output = $_POST["output"];
echo $output;
} elseif (isset($_GET["output"])){
$output = $_GET["output"];
echo $output;
}
In your success callback:
window.location = href + "?output="+data
try this :
Demo.php
<html>
<head>
<title>Demo</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(){
$.post( 'output.php', { output: "hello"},function( data ) {
$("div").append(data);
}
);
});
});
</script>
<body>
Click Me
<div></div>
</body>
</html>
output.php
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
exit;
?>

Categories

Resources