I know the my question is weird , but it is my situation. I am calling a javascript with
<script src="js/jscript.php"></script>
And in the other hand i am writing javascript inside jscript.php
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-Type: text/javascript");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
?>$(document).ready(function(){
....
....
....
alert('hello world!');//all my javascript stuff
<?php
echo $_SESSION['user_id']; //echo nothing
echo $_SESSION['user_email']; //echo nothing
?>
});
And then i tested with my browser , file calling and those call like alert('hello world!') have no problem but until i try to access session variable from jscript.php , its all empty ... I did set those variable correctly
I'm not sure that can work.
I think a better way would be making an ajax call to a PHP page, getting back the data in whatever form you want (json, or just echo $var ...) and then do something with it.
ex with jquery:
<script>
$.ajax({
url: 'mypage.php',
}).done(function(msg) {
// Do something with msg here
});
</script>
and mypage.php could be like :
<?php
$response = array();
$response['user_id'] = $_SESSION['user_id'];
$response['user_email'] = $_SESSION['user_email'];
echo json_encode($response);
?>
When the ajax call is made, the php page will create an array, fill it with the session variables you need and return it to your script in a json form with json_encode.
You get it as a var in .done method and do whatever you need with it.
Adding a session start a very start of jscript.php solved my problem
session_start();
hope its help others.
Related
I'm using JQuery and AJAX to call a slow function in a PHP file, but I don't get a response until the PHP function is complete. I can't figure out why, despite 2 days of searching. I've shrunk it down to two test files, that exhibit exactly the same behaviour. My php function is thus, in a file called "ajaxfuncs.php":
<?php
Class AjaxFuncs{
public function __construct() {
$this->testbuffer ();
}
function testbuffer(){
echo 'Starting Test Buffer Output. There should be a 2 second delay after this text displays.' . PHP_EOL;
echo " <br><br>";
echo '<div id="testdata" class="testdata">0</div>';
// The above should be returned immediately
flush();
// Delay before returning anything else
sleep(2);
for ($a = 0; $a < 3; $a++) {
echo '<script type="text/javascript">document.getElementById("testdata").innerHTML="' . (int)($a + 1) . '"</script>';
flush();
// Delay for 1 second before updating the value
sleep(1);
}
}
}
$AjaxFuncs = new AjaxFuncs();
?>
The above works if I open the "ajaxfuncs.php" file in the browser. It does exactly as I'd expect, and the output updates every second until complete. So I know I've buffering sorted on the server.
But when I call it using the following $.ajax it's not right. I've put everything except the php for the ajax function into another php file called "testindex.php" for convenience. This is it:
<?php
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-store, must-revalidate");
header ("Pragma: no-cache");
header("Expires: Mon, 24 Sep 2012 04:00:00 GMT");
?>
<body>
<a>Test Page. Wait for it...</a>
<div id="maincontent">
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
console.log ('Document Ready');
function callajax(){
var ajaxfilepath = "ajaxfuncs.php";
return $.ajax({
url: ajaxfilepath,
data: {action: 'testbuffer'},
type: 'get',
cache: false,
dataType: "text",
beforeSend: console.log('Starting Ajax Operation')
})
.done(function(result){
processajaxcalloutput(result);
})
.always(function(){
console.log(' Ajax Internal Complete Detected');
})
.fail(function( jqXHR, textStatus ) {
console.log( "Ajax Request failed: " + textStatus );
});
}
function processajaxcalloutput(result){
var message = 'Processing Ajax Response' ;
console.log(message);
$("#maincontent").append(result);
}
callajax();
});
Everything works without error. Console is clear - no errors (I'm testing with Chrome & Firefox). But I can't seem to get a response until the entire PHP function is done. I've tried everything I can find, in particular hundreds of different things to force caching off, but to no avail. Any help is much appreciated. Thanks.
Update:
So based on the feedback so far, it's clear the call is asynchronous and the code is fine, but asynchronous does not mean I'll get a continuous stream of output data from the php function as it executes. Instead the entire response will be returned at the end of the execution. Rather than divert this question into one about streaming, I'll leave it at this until I resolve the streaming issue.
Here is what I'm trying to do:
I use an Ajax call to select messages from my database, I echo the content in my PHP and i try to get the echoed html in the Ajax success. But it does not work. Here is the code.
JQUERY:
function SelectMessages()
{
console.log("Selecting messages");
console.log("Talk = " + talk);
$.ajax({
url: "select_messages.php",
type: "GET",
data: "talk=" + talk,
success: function (html) {
alert(html);
console.log("In success");
$("#message_box").prepend(html)
},
error: function (html) {
alert(html);
console.log("In error");
}
});//ajax()
}//SelectMessages()
PHP:
<?php
//SELECTING MESSAGES
require 'dbconnect.php';
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if ($_GET['talk'] != "") {
$request = $bdd->prepare('SELECT AUTHOR,CONTENT FROM MESSAGE WHERE TALK = :talk');
$request->execute(array("talk"=>$_GET['talk']));
while ($data = $request->fetch(PDO::FETCH_ASSOC)) {
echo' <p> '.$data['CONTENT'].'</p>';
}
}
?>
Using this code, I get "In error" displayed on the console and the code in the alert is "[object Object]". However, the status of my query is "OK" in my browser and the echoed result in the network window is the one expected with all the right values of messages.
I just don't understand why I get through the error instead of success.
Please do not mark this as a duplicate as I have already checked and tested the Ajax/PHP solutions and did not get any result.
In your php file you have set content type header as follows
header('Content-type: application/json');
but normally echoed the response as plain text/html. Either you have to send the response in json.
echo json_encode($data['CONTENT']);
Or remove content-type header as json.
I'm passing 2 variables with ajax to the same .php file. I see them in the console.log but I can't seem to echo them. I already tried several things I found in other questions but it doesn't seem to work. What do I need to add/change?
My code:
<script>
$(document).ready(function () {
$("#slider").bind("valuesChanged", function (e, data) {
$.ajax({
type : "POST",
url : "../wp-content/themes/twentytwelve/fields/test.php",
data : {
minValue : data.values.min,
maxValue : data.values.max
},
cache : true,
async : false,
success : function (data) {
console.log(data);
},
error : function (xhr) {
alert('fail')
}
});
});
});
</script>
and the php part:
<?php if ( $_POST ) {
echo $_POST['minValue'];
}
?>
Btw: it only passes the first value (minValue) and not the other one. How to pass them both? Thanks!
Maybe by printing both values?
<?php
if (!empty($_POST)) {
echo $_POST['minValue'];
echo $_POST['maxValue'];
}
?>
Can you see your request details in the Debug panels like Firebug in FF or (I don't know how it called) in Chromium-based browsers?
Are there all the passed data?
If no then the error in JS.
Also print out the whole POST data on server side to see the POST content.
To pass more values try something like this on php side:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
echo json_encode(array(
'a' => 1,
'b' => 2
));
i work with d3.js and CodeIgniter and i have a problem when i get json data with d3.json
when i run this code :
var url = "http://probe.dev/draw/windRose?station=vp2&sensors=wind&Since=2012-10-15T00:00:00&StepUnit=DAY&StepNbr=6;
d3.json(url, function(d) {
console.log(d); // print NULL in console
}
but it works with
$.getJSON(url, function(d) {
console.log(d); // print my data object correctly
}
my php code is :
<?php
#ob_end_clean();
header('Content-Type: "application/json"');
header('Content-Disposition: attachment; filename="data.json"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
exit($data);
I don't understand why d3.json do not work ?
I couldn't make it work with v2, I moved to d3js.v3 and it worked.
The callback function in v3 takes two params:
d3.json(url, function(error, json) {
if (error) return console.warn(error);
else ...;
}
I have a new problem which MUST affect practically every person who uses AJAX. I have a HTML/JavaScript page which (using a jQuery call) loads a .php into my page - but it seems to cache the results and often just returns the cached information rather than re-running the PHP script.
The code below is how I'm trying to overcome the problem (thanks bazmegakapa for the code - I've just tried to add the cache:flase bit - but it doesn't seem to work).
$(document).ready(function() {
cache: false
$('#selecthere').load('/temp/php_script.php', function () { //callback
$('select', this).change(function () { //catch onchange event of select
//call your function here, pass the selected value
initialize($(this).val());
});
});
});`
Your php_script.php file should send the correct headers to prevent caching.
<?php
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
Just add a random number to the end
var random = Math.random() * 10;
$('#selecthere').load('/temp/php_script.php?r=' + random, function () {
It looks like you are doing the cache: false wrong.
$(document).ready(function() {
$.ajax('/temp/php_script.php',
{
cache: false,
success: function(result) {
$('#selecthere').html(result);
}
}
);
});