Sending data to the clicked url via AJAX/PHP - javascript

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

Related

Undefined index:usernames

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.

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
}

Jquery AJAX function with $.post not going through, can't find any syntax errors

<script type="text/javascript">
function swapContent(cv) {
$(".loading").html("loading-gif").show();
$.post( "one.php", {contentVar: "cv"},function(data) {
$(".loading").html(data).show();
alert('Info Sent!');
});
}
</script>
And "one.php"
<?php
$contentVar=$_POST['contentVar'];
if ($contentVar == "con1") {
$row_number = $published_posts;
echo "<script type='text/javascript'>alert('$message');</script>";
}
else if ($contentVar == "con2") {
}
?>
I put the alert in the $.post so I can tell where my script is failing. I recieved alerts at every stage in the script up until $.post ceased to display the alert. Meaning that is where the code is faulted. But from what I can tell there doesn't seem to be any syntax errors, what could be the reason this is not working?
Got it to work! Had to specify the exact location of the file I was trying to post to. Due to the files being within a wordpress theme, I had to specify their location with <?php echo get_template_directory_uri();?>
$.post( "<?php echo get_template_directory_uri();?>/one.php", {contentVar: "cv"},function(data)

Correct way to set cookie from jQuery and read from php

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.
When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)
I used both head tag and onload method to place the setCookie() function. But result was same.
I used this jQuery library to write cookie.
Here's code I used to read and write the cookie.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background: #666666;
}
</style>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript">/script>
<script>
setCookie();
function setCookie() {
console.log('on Load');
var data_spl = $(location).attr('href').split('#?camlist=')[1];
if (data_spl != undefined) {
var len = data_spl.split(',').length;
$.cookie("len", len);
console.log($.cookie("len"));
} else {
console.log('undefined');
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i < 100; $i++) {
echo "<script>console.log('START');</script>";
echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
echo $_COOKIE['len'];
echo "<script>console.log('END');</script>";
}
echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
?>
</body>
</html>
EDITED:
I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.
var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
if (retparams.has) {
console.log('sucessfuly sent the paramlen!');
} else {
alert("can't read camarauids for grid making");
}
}, 'retparams');
set_session.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
$_SESSION['urllen'] = $_POST['params'];
echo json_encode(array('retparams' => 'has'));
echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
echo json_encode(array('retparams' => 'error'));
}
?>
Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)
As already mentioned in the comment section your Cookie isn't present on first page Load because it isn't set yet. (If you set the Cookie directly in JS or via AJAX is essentially the same)
The only way to effectively get the Information is ether with a page reload or a redirect or via AJAX request (depends on what fits your needs). For Example you could redirect in JS after the Cookie got set with:
//set your cookie in JS
window.location = location.host;
more Information about JS redirects can be found here or you search your way thru Google.
You can also set your Cookie in PHP and redirect with the header() function:
header('Location: http://www.example.com/');
More Information for PHP redirects can be found here or on Google ;)
You could check this with ajax.
Here is a simple example:
<?php
if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
header("Content-Type: text/json");
die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
exit();
} else {
var_dump($_COOKIE);
}
?>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js.cookie.js"></script>
</head>
<body>
<script type="text/javascript">
function checkIfLoggedIn() {
console.log("checking...");
jQuery.post("?checkIfLoggedIn=1", function(data) {
if(data.isLoggedIn == true) {
alert("Logged im.");
} else {
alert("NOT logged in!");
}
});
}
</script>
Set logged in to true<br/>
Set logged in to false
</body>
</html>

Executing php file from another php file

Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help

Categories

Resources