Store Ajax div content in a PHP variable - javascript

I have a problem with variables. I have a website using only Jquery which means that that I use #p1, #p02, ..., to navigate from one page to another.
I made an Ajax call which prints an id that I need in order to view my content. This id is printed in a div. The problem is that when I store the div in a variable like this:
$variable="<div class='something'></div>";
I can echo the variable but CAN'T use it in order to make queries. I know this is but programming but if I use sessions instead the identity didn't updated at all from page to page because of the using of #p01 instead of p1.php.
I also added the ajax.js file if this help you in order to advise me. The ajax.js file sends an identity to Ajax_page.php then I store this $_POST variable in a SESSION and then I echo this varible in Ajax_page.php. When i echo this variable it also printed in the div which is in the Show_content_page.php. I want the contents of that div. I want to use this div contents(identity) in order to make my php queries. Thats all.
Is there any way to make the $variable useful?
Here are the to sample files
Ajax_page.php
<?php
session_start();
if(!empty($_POST['show_an_anetoix']) ){
$_SESSION['anetoix_id']=$_POST['show_an_anetoix'];
}
echo $_SESSION['anetoix_id'];
?>
Show_content_page.php
<div id="p1" >
<?php
$variable="<div class='something'></div>";
echo $variable; //no problem
function_test($variable); //problem
?>
</div>
The ajax.js
/* Pass data with changePage */
$(document).on("pageinit", "#p1", function () {
$(document).on('click', '.anetoix_class', function(){
$.mobile.pageContainer.pagecontainer("change", "#p02", {
stuff: this.id,
transition: "flip"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "p02") {
var stuff = data.options.stuff;
var data = {"show_an_anetoix": stuff,};
$.ajax({
type: "POST",
url: "../show_an_anetoix.php",
data: data,
success: function(response)
{$(".show_an_anetoix").html(response);}
});
}
});

Not 100% sure what you mean. Are you asking, can you use a PHP variable in ajax? If so, I would do something like this:
<script>
$ajax_variable = "<?php echo $php_variable; ?>";
</script>

Related

Trying to post a javascript variable to a php file using the ajax method : POST but getting an undefined index in $POST array within php file

I have a php file with the directory "JqueryPHP/HighestBid.php". All I want to do is be able to post javascript variables from one file "views/AuctionPage.php" to another file "JqueryPHP/HighestBid.php".
I then want to echo a value from "JqueryPHP/HighestBid.php" into the span tags with the id "price" into "views/AuctionPage.php".
The problem is that when I load the page "views/AuctionPage.php" it shows me the alert with the returned value "hi" but where the text is supposed to be outputted between the span tags, it is telling me that the index within my $POST array is undefined.
//JS views/AuctionPage.php
<script>
$(document).ready(function() {
var auc = "hi";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': auc },
success: function (result) {
alert("result: " + result);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#price').load('JqueryPHP/HighestBid.php')
}, 333);
});
</script>
//HTML views/AuctionPage.php
<h4 class="price">Highest bid : <span id="price"></span></h4>
//PHP FILE "JqueryPHP/HighestBid.php"
<?php
$auctionid = $_POST['auctionid'];
echo $auctionid;
?>
When I get rid of the $POST array in "JqueryPHP/HighestBid.php" and just assign auctionid with a normal string.
<?php
$auctionid = "hi";
echo $auctionid;
?>
the text gets outputted between the span tags like it's supposed too so I am having a problem posting the variables to another page and I have no idea why. I have tried many ways to get this to work following examples on stack overflow but to no success.
This line:
$('#price').load('JqueryPHP/HighestBid.php')
loads the JqueryPHP/HighestBid.php script using GET, and that's another, completely independent request from your AJAX one, that's why the $_POST superglobal is empty. What you need to do is to change the span inside the success function of your AJAX call:
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': auc },
success: function (result) {
// alert("result: " + result);
$('#price').html(result);
}
});
That gives the result you need. Delete the whole setInterval code, you don't need it at all.

Update data through Ajax

I have the below code on href click I'm calling a javascript code in which an ajax is being called which returns the value of array $ss in json format . Now I want to know how can I update the value of $ss via ajax.
<div class="white" id="white" style="display:none">
<?php
foreach ($ss as $key => $value){
?>
<a href='javascript:void(0);' onclick='callAjax('<?php echo $key; ?>')'>
<?php
echo $value;
?>
</a>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({a: id }),
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
And ajax.php files return array values for $ss.
I understood how to update data of normal div through ajax but encountering problem to pass the data returned by ajax call to update array value.
1- Lets be clear javascript will not replace the content of a php variable. 2- Even if so you will not be able to regenerate the html you need this way.3- after you receive your variable you need to update the html instead.
PS: Surely you can update the variable on the server side when you receive that ajax call,that also needs some requirements(the variable is global and accessible inside the php file...),but from what I have understood you want to change it with javascript which is not possible.
Your ajax must like this...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
I think you can't.
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it.
$ss = 'ss value';
if exists($_POST['ss']) {
$ss = $_POST['ss'];
}

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".

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>

How to filter results based on session variable php

This has been giving me issues for quite some time. Any help would be most appreciated!
I have a php page that is responsible for displaying information I request from a database. I have a few buttons on the page that dictate what results will be displayed at what time. I have a forward arrow that gets the next record, I have a back arrow that gets the previous records and then I have a filter button that I am attempting to filter my results by.
Main PHP page
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">var mysess = <?php echo $_SESSION['verticalsess'] ?>;</script>
<script type="text/javascript" src="/getresults_ab_drastic_display.js"> </script>
<?php include("/connect.php"); ?>
</head>
<body>
//content
</body>
</html>
//getresults_ab_display.js
You'll notice this JS calls another PHP file which returns the results to the original PHP file. One function is forward results, one function is for previous results and the other is a to set a filter based on a drop down menu on the main php page.
$number = 1;
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/getNext.php",
data: {"count":$number, vertical: mysess},
success: function(results){
$('#results').html(results);
$number++;
}
});
});
});
$(function(){
$('#showLess').click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/getNext.php",
data: {"count":$number, vertical: mysess},
success: function(results){
$('#results').html(results);
$number--;
}
});
});
});
$(function(){
$('#Filter').click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/getNext.php",
data: {vertical: $('#vertical').val(), pagetype: $('#pagetype').val(), primarykpitype: $('#primarykpitype').val(), count:$number},
success: function(results){
$('#results').html(results);
}
});
});
});
//getnext.php
This getnext looks for information passed from the js file and sends the appropriate results back.
session_start();
$_SESSION['verticalsess'] = $_POST['vertical'];
$pstcnt = $_POST['count'];
if ((isset($_POST['count'])) && $_SESSION['verticalsess'] = "null")
{
$sql = "SELECT * FROM experiments LIMIT $pstcnt,1";
}
else{
$sql = "SELECT * FROM experiments WHERE vertical = '" . $_SESSION['verticalsess'] . "' LIMIT $pstcnt,1";
}
//my output
...
my problem
When I click on filter button it should send 'vertical' to my getnext php file and a) set the session variable to that value and b) return results that contain related to that vertical, HOWEVER the first time the filter button is clicked, it will pass the value for vertical and set the session variable equal to that value, however when I go to click on the get next record button, the value of the session is null...always. So for some odd reason after the session is set the first time and the results are displayed to the screen, when I want to show the next record, mysess is set to null.
what am I doing wrong here?
in //getnext.php
$_SESSION['verticalsess'] = "null" ??
I think it should be
$_SESSION['verticalsess'] == "null"
try that and see hwo it goes
First off, you have a giant security loophole in your SQL. You're not sanitizing anything you're passing to your database. Escape your data or use prepared statements.
Second, it's a bad idea to use $ in Javascript, especially with jQuery loaded. So change $number to number for readability.
Third... what is the initial value of mysess? If I visit this page for the first time you're setting it equal to a session variable that doesn't seem to be defined. I'd at least expect to see something like
session_start();
if(!isset($_SESSION['verticalsess'])) $_SESSION['verticalsess'] = 'somevalue';

Categories

Resources