I'm using an AJAX call in my script to fetch some data from my php script.
The AJAX call properly executes, I've tested that so far. But unfortunately, the SESSION variable doesn't seem to be available.
I'm currently refactoring some code and this AJAX call goes to some code which before was inside the same file as the scriptcode. There, the respective php code still executes and the SESSION variable definitely is available there, otherwise the whole page would break (probably).
So I wonder whether I forgot to include something in my php file or something of this sort?
EDIT: I'll try to give minimal example of what code is behind the described behavior.
Code in Calling.php (yeah its javascript, but the author (not me) once decided to make a php file which contains both HTML, javascript and php...):
<?php session_start(); ?>
<script>
//Lots of Code
function Caller(){
$.ajax({
type:"POST",
url:'called.php',
success: function(data){
//debugging function taking data;
},
error: function(xhr, statusText, err){
//debugging function taking xhr.status
}
}
)
}
//Lots of Code
</script>
Code in called.php
<?php
$test = $_SESSION["loggedUser"];
echo $test;
?>
Ajax calls are not the same process as the original page being served, and require session_start being called again for each request.
You can do this safely (without an error or warning if it has already been called) like so:
if ( is_null($_SESSION) || !$_SESSION )
{
session_start();
}
This should live in your bootstrap or index file, and should always be called/included/required from all requests to php, before any request-based logic runs.
Related
I have this php file graph.php
$host = $_POST['hostname'];
echo $type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
and I trying to send data to this file using this ajax code
var type_char='fortigate_cpu';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: { hostname:hostname,type_char:type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
the result when I send data to that file is
fortigate_cpu as a value of type_char variable
when I opened error.log file in apache logs
I have this message
include(): Failed opening 'graphs/.inc.php' for inclusion (include_path='.:/usr/share/php')
as you see the value of fortigate not included in include function even if the char_type variable is send by ajax and printed in page
include file must be as this
include( 'graphs/fortigate_cpu.inc.php')
why type not included in the include session even if the variable is received from ajax
As was mentioned by other users in the comments, maybe your issue is that you are setting type to a different value after including rrdtools.inc.php .
Try randomizing ( changing the name), of the type variable:
$host = $_POST['hostname'];
echo $type123456=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type123456.'.inc.php');
It's the only thing I can think of, since both I (and others) have tested your code.
(both front-end and back-end).
PS: Include using post param is a bad practice.
This question might seem a duplicate and There are many posts on how to pass jquery variables to php. Tried all of them none worked for me.
Here is what all I did.
From Jquery:
$.ajax({
url: '/test.php',
data: {"name":name,"phone":phone},
type: 'post',
success:function(data){
console.log("Succses");
}
});
In test.php
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['phone']=$_POST['phone'];
There is nothing complex in this code. It is so simple and am seeing the "Success" message on the console. When am trying to echo this sssion variable in another page, this is shown empty.
Any help is greatly appreciated.
Please use session_start() on the first line of your PHP code to make the session works for you for that page.
You might have following problems
Might be missing session_start()
You might getting blank values on $_POST
Do the debug for ajax call and don't forget to check print_r($_POST) has values in success or not.
This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);
I use this simple javascript code to call a php function from javascript.
var a = new XMLHttpRequest();
a.open("GET","save.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
alert("Worked");
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
In this example I have a php function save() contained into save.php file.
I have some questions:
1) How can I call a php function that it is located into the same file where there is the javascript function? (I would to call a php method declared into the same file where there is the javascript caller)
2) Is possible to pass also an php array as parameter?
First: You are not "calling a function". You are making a request to a server. The request is "interpreted" in php, and php has a function defined that is called. Js never calls php directly (one is front side, one is back).
To answer your questions:
You need to make the request to the same page you are displaying, but your js will also be executed.
Yes, but I suggest a post not a get for this (use var_name[] for array, where var_name is the name of the array).
As side notes:
Having both php and js in the same file is usually a bad idea. Try to isolate the front-end from the back-end as much as possible (it may be hard at first, but it will save you from huuuge headaches).
The script you are using is fine for simple things, but lacks lots of things (what if destination was moved and you get a redirect state, what if is unreachable, what if you need a callback, etc.). You are also limited at GET, and for some thing you may prefer POST method. I suggest using js lib for your requests (like jQuery ajax, prototype ajax, etc.) that take care of this things. Or you can extend your script of course.
You have to use ajax call as described manner--
On javascript side on save.php page-
$.ajax({
type:"POST",
data:'demodata',
url:"save.php?action=php_function", // place your php function name here
dataType: "html",
success:function(response){
alert(response); // It will alert value returned by php function
},
failure:function(response){
alert("there is an error.");
},
});
On PHP side on save.php page-
<?php
if(function_exists($_GET['action']))
{
$_GET['action']();
}
else
{
echo 'There is some error.';
}
function php_function()
{
// some code
echo "result";
}
?>
In general, passing an array between PHP and Javascript is better done using a JSON document as interchange format.
You would have to detect the request was made via ajax so that you can run the save() function, or if not then output the page normally, with the JavaScript caller included.
There are a number of ways to detect ajax, one would be to set the X-Requested-With header, which you can check on the PHP side.
save.php
function save(){
// some PHP code here
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// request was made via ajax, call the function
save();
exit(); // exit so no page content is sent via ajax
}
// output the page content including JavaScript caller
JavaScript:
var a = new XMLHttpRequest();
a.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // set the header
// continue with your XHR code
The best way to send an array would be to JSON encode it before sending via POST, then JSON decode on the PHP side.
JavaScript:
a.open("POST","save.php");
a.send('json=' + encodeURIComponent(JSON.encode(myArray)));
PHP
function save(){
$myArray = json_decode($_POST['json']);
}
Edit: changed $.alert() to alert()
I've got a file, planner.php that uses JQuery to send an ajax request to the same page.
Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?
JQuery:
$(function()
{
$.post('planner.php', {"want": "keys"}, success_func, 'json');
});
function success_func(result)
{
//This is never called :(
alert("Worked");
}
PHP:
<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";
if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
$couch_dsn = "http://localhost:5984/";
$couch_db = "subjects";
$client = new couchClient($couch_dsn, $couch_db);
header('Content-type: application/json');
$response = $client->getView('subject_views', 'keys');
echo json_encode($response); //This all seems to work fine
}
?>
It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.
For knowing where the ajax call is done or faced a error
$(function()
{
$.post('planner.php', {"want": "keys"},function(){
alert( "success" );
})
.done(function(){
alert("second success");
})
.error(function(){
alert("error");
});
});
link : http://api.jquery.com/jquery.post/
This is probably be cause there is no such thing like $.alert(), use simple alert() instead.
Also your success_func is declared below the ajax call, move it up before $.post();
EDIT:
as the function is declared, there is no need to type it before executing.
you can use like that it may be your sucess function not calling
var data = 'want=keys';
$.post(
'planner.php',
data
).success(function(resp){
json = $.parseJSON(resp);
alert(json);
});
Credit to vivek for giving me a method to work out the problem.
Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight
The obvious solutions are:
Make a new page for the response
Put the php at the top of the
page.
I ended up going with option #2 for simplicity's sake.
Thanks everyone!