Display a session var without refresh the page - javascript

I set a session var in an ajax file like that :$_SESSION['id_essai']=$ligne[1];. The value of this var should change at each submit of the form.
Without recharge the page, I want to get the value of this var. So I echo it like that : echo $_SESSION['id_essai'];
My problem is, when I try to echo it, I get the previous value until I recharge the page. I want to refresh this var without recharge the page. How can I do that ?
EDIT :
I send a handsontable grid to my ajax file like that :
$(document).ready(function(){
$('#submit_button_essai').click(function(){
$.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json');
return session;
});
});
In this ajax file, I declare my session var with one value of this grid and I can return it like that :
array_unshift($tab_erreur,$_SESSION['id_essai']);
echo json_encode($tab_erreur);
So I send an array of errors AND the session var that I process like that in my callback function:
function insert_essai_callback(responseObject,ioArgs) //ajax renvoie les indices des cases erronnées et les messages correspondants.
{
var jsonobject = eval(responseObject);
console.log(jsonobject);
//alert(jsonobject[0]);
var session = jsonobject[0];
for(var item in jsonobject)
{
if((item % 2 ) == 0) //Si l'indice est pair, on affiche la couleur
{
$("td").eq(jsonobject[item-1]).after("<div class=\"message\">"+jsonobject[item]+"</div>");
}else //Si l'indice est impair, on affiche le message
{
$("td").eq(jsonobject[item]).css("background-color","red");
}
}
}
My session var is in jsonobject[0].
That's my code after trying to return the session var in ajax.

I think the problem is that every reuqest will start a new session on the server.
<?php
session_start();
// Restart the last session if a session-id is given
if (isset($_GET['session-id'])
session_id($_GET['session-id']);
/* ... your code here .. */
$response = array('session-id' => session_id());
/* ... add some more values/results to your response */
header('Content-Type: application/json');
die(json_encode($response));
?>

Set up a new PHP file. Then send the value you need to update to the session variable using ajax on a click event or change event or something. When it receives the value , PHP will update the session value. Then return that variable's value in JSON. Tada You got the updated value. I hope you understood..
example code look like this
in ajax (jquery ajax i am using here)
$.ajax({
url : 'session.php',
method : 'POST',
data : your value to update ,
dataType : json,
success : function(data){
alert(data.value);
}
})
In session.php file
<?php
session_start();
$value = $_POST['value'];
$_SESSION['value'] = $value;
$json = array('value' => $_SESSION['value'] );
print_r(json_encode($json));
?>
If you need to get value without refresh , call the ajax function on an event. Then update the returned data in to div or something. I hope this one helps ! :)

create a process.php file and post/get the form there.
<form method = 'post' action = 'process.php'>
<input type = 'hidden' value = 'some_Hidden_Value_that_You_Want' id = 'hidden_id'>
<!--Some other stuff (Grid may be) -->
<input type = 'button' value = 'Submit' id = 'submit_form'>
</form>
$("#hidden_id").click(function(){
var hidden_id = $('#hidden_id').val()
$.ajax({
url: 'process.php',
type: 'POST',
data:{
want_this: hidden_id
},
success: function(posted){
alert(posted);
}
});
});
This will post your stuff to process page.
and on process.php or in your case ajax_insert_essai.php
do this to view what you're getting
<?php
print_r($_POST);
?>
EDIT
in callback
obj = $.parseJSON(jsonobject[0]);
console.log(obj);
// this was to update the page without refreshing the page
// $this = $('#'+obj.ID).find('td');
// $this.eq(2).html(obj.username);
// $this.eq(3).html(obj.password);
//ignore these lines
/*You can access all your stuff then like that*/
condole.log('some id' + obj.id);
//and so on...

If the data that will become the new session variable is sent from the page just have it also use the data already on the page to update to page using JavaScript.
If the data you want to get returned is being sent from the page there is no need to re-get the data because it is already on the page.

Related

how to fetch data from sql server database in php without refreshing the page

I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".

Set session var with ajax

I want to create a session var. I have a web page with some tabs that don't recharge when I active one another. So, I don't know how to set my session var.
Indeed, my first tab will generate the session var when the user submit the form into this tab. I'm trying to do it with ajax. So in my ajax file, I have this to set my var :
if(pg_num_rows($res) == 1)
{
$flag=false;
$message = "L'identifiant de l'essai existe déjà dans la base";
array_push($tab_erreur,$cpt,$message);
}else {
$sessionIDEssai=$ligne[1]; //Here is my session var
}
After, I want to return that value with an other like this :
echo json_encode($tab_erreur),$sessionIDEssai;
First of all I don't know if it's correct, because I can't get it in my callback function.
function insert_essai_callback(responseObject,ioArgs) .
{
var jsonobject = eval(responseObject);
console.log(jsonobject);
}
I can get the first var $tab_erreur.
And after I don't know how to set my session var for all my tabs. I think that at the return of the ajax, I will get the value and I could set it and use it, but I'm not sure.
EDIT
I send an array in my ajax request like that :
$(document).ready(function(){
$('#submit_button_essai').click(function(){
$.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json');
});
});
Ajax
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: data,
success : function(data){},
error : function(){}
});
PHP
<?php
session_start();
$_SESSION['data']=$_POST['data'];
echo $_SESSION['data'];
?>
});
Data is what you send through a POST, now echo can return that data or a different amount of data to your Ajax request as a response.
Using, $.post():
$.post({
url: url,
data: data,
success: success,
dataType: dataType
});
However, $.ajax(), is much much better, since you have more control over the flow, and if success do this etc.

Unable to send jQuery variable with string content to PHP using jQuery AJAX function?

The code snippet for the jQuery function looks like:
function addMessage() {
if (textval != "") {
text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
alert(text_string);
$.ajax({
type:"POST",
url:"process.php",
data: {'text_string': text_string},
cache:false,
success:function(){
alert("submitted")
}
});
$("input[type=text]:last").val("");
}
enterButton = 0;
}
The process.php code looks like:
<body>
<?php
//$host = "localhost";
$text_string=$_POST['text_string'];
echo "string submitted is".$text_string;
?>
</body>
I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:
Undefined index: text_string
I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?
If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:
<?php
session_start();
// Store value in session if it is passed
if (isset($_POST['text_string'])){
$_SESSION['text_string'] = $_POST['text_string'];
}
// Read and echo value from session if it is set
else if (isset($_SESSION['text_string'])){
$text_string=$_SESSION['text_string'];
echo "string submitted is".$text_string;
}
?>
Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)
Hope this helps! Let me know if you have any questions.

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Ajax request in Codeigniter

I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript. I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.
So here are my questions:
Is it really possible to use PHP inside Javascript, or am I mistaken?
What's the right way to perform an Ajax request in Codeigniter? What I've tried is the following:
var param = {name : event_name, date : event_date, time : event_time};
$.ajax({
// As seen from the question here at stackoverflow.
url : "<?php echo base_url('event/new_event'); ?>",
type : 'POST',
data : param,
beforeSend : function(){ },
success : function(){
alert("Event created! Feel free to add as much details as you want.");
namebox.val("");
$("#new-event-modal").find(".close").trigger('click');
window.location.href = "<php echo base_url('user/dashboard'); ?>";
},
complete : function(){ },
error : function(){ }
});
I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!
the easiest way for you to accomplish this is by using some jquery:
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";
$.post(url, postdata, function(result){
...alert(result);
});
or call it straight from JS by caching it:
<script>
var test = "<?php echo base_url(); ?>"+"event/new_event";
alert(test);
</script>
Here is a dirty hack that I was going to use:
Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field.
Now when you want to make an ajax request, access that hidden field
and grab the base url and use it however you want.
The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.
This is your controller
<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {
public function ajax_echo()
{
// get the ajax input
$input = json_decode(file_get_contents('php://input'));
// $input can be accessed like an object
$password = $input->password;
$name = $input->name;
// you can encode data back to JSON
$output = json_encode($input);
// and the response goes back!
echo($output);
}
}
?>
This goes into your client
<script>
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
// create the request object
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "example_ctrl/ajax_echo", true);
// on success, alert the response
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200)
return;
alert("Success: " + xhr.responseText);
};
// encode in JSON and send the string
xhr.send(JSON.stringify(my_data));
</script>
There is no better way to do this .
Php codes can't be executed from external javascript files.
Try any of these :-
1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code
2) you can store the same base_url() in local storage , it will be available in your external JavaScript files
Hope it helps you :)

Categories

Resources