How can I assign session id of php in a jQuery file? - php

I have a main file
index.php
in which I include four other files like
header_get_started.php,
content_main.php,
right_sec_home.php,
footer.php.
Here is my code
"index.php"
<script src="js/ajax.js"></script>
<?php include_once('header_getstarted.php'); ?>
<?php include_once('content_main.php'); ?>
<?php include_once('right_sect_home.php'); ?>
<?php include_once('footer.php'); ?>
"header_getstarted.php"
<span class="select_input">
<?php
$sqlCmd = "some query";
echo combo('cmb_command','custom-class1 custom-class2','cmd_name','cmd_id','0',$sqlCmd,'sendpostmtu()' $width="style='width:250px;cursor:pointer;'")
?>
<input type="submit" name="" class="sub_bg" value="" onclick="get_request_by_command($('#cmb_command').val());">
</span>
In header_get_started.php
When select any command from select box, I want to assign it's id to $_SESSION['id'].
Onclick of selection box I have an ajax request which can refresh the main content (content_main.php). Also I want that selected id in another page in right_sec_home.php to refresh it's content.
How can I assign the php session id in JS file for 2nd page?
My JS file is
function get_request_by_command (commandId) {
var cmdTitle=$('#cmb_command :selected').text();
if(cmdTitle=="") {
cmdTitle='ABC';
}
$("#main_wrap").hide();
if(cmdTitle=='--Select--'){
$("#cmdTitle").html("");
}else{
$("#cmdTitle").html(cmdTitle);
}
$("#cmbs_cmd").val(commandId);
document.getElementById('request_list').innerHTML='<img src="images/loader.gif" />';
var strURL="request_by_command_tbl.php?id="+commandId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var ret = req.responseText;
$("#requestTitle").html("<span id='cmdTitle'>"+cmdTitle+"</span>);
$('#request_list').html('');
$('#request_list').html(ret);
$('#main').show();
$("#searchDiv").show();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
With using this jQuery function, I have created an ajax request, and send the id to the "request_by_command_tbl.php" file.
In "request_by_command_tbl.php" file i assigned,
$_SESSION['id'] = $_REQUEST['id'];
Also I want this $_SESSION['id'] in right_sec_home.php at same instant.
So is their any way to assign php $_SESSION['id'] in the jQuery script file before sending ajax request.
My other files
"content_main.php"
<div id="request_list"> </div>
<div> </div>
<div id="add_space"></div>
Right section home file in which i need session id
"right_sec_home.php"
<?php
function getRequestByMonth($month, $year, $id){
$que ="SELECT distinct(MS.date) FROM commands AS MC , ranks AS MR ,steady_tours AS MST, preferred_tours AS MPT, registration AS MMS where date_format(rm_date, '%c-%Y') = '".$month."-".$year."'
AND MMS.cmd_id ='".$_SESSION['id']."'
order by MMS.date";
$res = mysql_query($que);
while($rows[]=mysql_fetch_array($res)){}
foreach ($rows as $res):
if($res['date'] == "") continue;
$dt = date("Y-n-j", strtotime($res['date']));
$return[getDateB($dt)] = $res['date'];
endforeach;
return $return;
}
I hope that this is clear enough.
Any ideas?
Please help.

there is no way for you to access the session information with jquery ..
explanation
sessions are files stored on the server --> where is java script is only a client side language ..
there is always a work around .. but i guess you should explain more about what exactly you want to achieve

<?php $sessionId = session_id(); ?>
<input id="session_id" name="session_id" type="hidden" value="<?php echo $sessionId; ?>" />
Get the value of the hidden field using jquery.

You can use some hidden fields or script variables inside the php file.
example :
<script>
var id = <?php echo $_SESSION['id']; ?>;
</script>
varible id can be accessible using the javascript or jquery

Related

Problem of XMLHttprequest, reponseText still empty

I create articles on an administration and on each article i have a button to like it, at the onclick, the javascript call the php code in an other file to fill the database, and the database should resend the number of like, but the echo on the processing file doesn't fill the reponseText of the XMLHttprequest and I don't know why and that's I'am trying to solve and understand.
I succeeded to do it but I don't want to refresh the page at each like, so i use XMLHttpRequest to display correctly the likes whithout refreshing.
I followed serevals tutoriels, but that doesn't work well.I had to miss something.
First I have a file : index.php with my javascript and php code:
<ul class="ulp">
<li class="lip">
<button class="likebutton" onclick="like('<?= $ipclient ?>','<?= $event->getID()?>')" style="color:#5B5A57">
<i id="coeur<?= $event->getID()?>" class="<?= $classlike ?>">
<span id="nblike<?= $event->getID()?>">
<?= $tableLikes->countLike($event->getID()) ?>
</span>
</i>
</button>
</li>
</ul>
<script>
function like(ipclient,eventid)
{
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("nblike" +eventid).innerHTML = this.responseText;
};
xhttp.open("GET","event/" + ipclient + "-" + eventid, true);
xhttp.send();
}
</script>
When I am cliking on this button that send correctly the request.
I have a second file that processes the data:
<?php
use App\Model\Likes;
use App\Table\LikesTable;
use App\Connection;
$pdo = Connection::getPDO();
$like = new Likes();
$tableLike = new LikesTable($pdo);
$ip = $params['ip'];
$id_event = $params['id'];
if($tableLike->likeIp($ip,$id_event) === true){
$like->setId_article($id_event);
$like->setIp($ip);
$tableLike->newLike($like);
}else if($tableLike->likeIp($ip,$id_event) === false){
$tableLike->dislike($ip,$id_event);
}
echo $tableLike->countLike($id_event);
I would like to have the content of the last echo in the reponseText of my object XMLHttpRequest.
How can I do ?
Thanks you in advance .

Display Mysql Data in Cordova Using PHP and JSON

I need to know what can done to display data from mysql database in cordova app.
I made a php file placed it on the server.
then i made the html with json code to fetch data from mysql database.
The data from mysql database should be displayed in the div with id="demo".
I have done this till now.
My Php file looks like this:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
include "../../webConfig/web.config.php";
$conn = connect();
$q = $conn->query("SELECT name FROM 'online_' ORDER BY DESC");
$rows=$conn->query($cb);
$rows=$conn->query($cb);
foreach($rows as $row){
echo $row["ID"];
echo $row["first_name"];
echo $row["middle_name"];
echo $row["last_name"];
}
echo json_encode($rows);
?>
My HTML file Looks like this.
<div data-role="content">
<div class="container-fluid">
Online Application
<p id="demo">
.....
</p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"online", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "http://localhost/admin/notify/test.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</div>
</div>
I have been trying to do this using json But my html file dosen't show anything apart from those dots.
I tried placing the php file on the web server as well, but still it did not show anyhing.

How to submit form without moving to next page in PHP

The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.

PHP In ajax responseText take all the html cose instead of ONLY the echo passed trought PHP

Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>

Getting variable value from PHP with jQuery

So how do i get variable value from php file with jquery...?
the jquery code is in other file (tpl)
for example i have register.php and register.tpl (template file for register.php)
register.php
...some includes here...
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string(trim($_POST['username']));
$email = mysql_real_escape_string(trim($_POST['email']));
$check = $mysql->query("SELECT username FROM ".TBL_USERS." WHERE username = '".$username."' OR email = '".$email."'");
$rows_check = mysql_num_rows($check);
if($rows_check > 0) {
echo 1;
} else {
$password = mysql_real_escape_string($_POST['password']);
$salt = generate_salt($email);
$hash = hash_password($password, $salt);
$q = $mysql->query("INSERT INTO ".TBL_USERS." (username, password, email, salt) VALUES ('".$username."', '".$hash."', '".$email."', '".$salt."')");
if($q) {
header("Location: index.php");
} else {
die(mysql_error());
}
}
} else {
.. calling parse template function ...
}
register.tpl
..jquery library included..
<form id="register" action="register.php" method="post">
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" class="register" style="width: 200px;" />
</td>
email
...other inputs...
$("#username").blur(function()
{
var email_v = $("#email").val();
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("register.php",{ username:$(this).val(), email: email_v, submit: true } ,function(data)
{
if(data=="1")
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
</script>
when i changed the whole register.php for testing purposes to
or
the script worked...however with the original version it shows always that username is available...
Best bet is to output the PHP variable as a hidden field or a JavaScript variable:
<input type="hidden" id="my_var" name="my_var" value="<?php echo($my_var); ?>" />
// access it like this:
alert($('#my_var').val());
or
<script type="text/javascript">
var my_var = <?php echo($my_var); ?>;
</script>
// access it like this
alert(my_var);
That should do it :-)
Either you make a Jquery Ajax Request that will request a php page which will return whatever you want or you echo a javascript variable with php
<?php
echo '<script> var javascript_variable = "whatever"; </script>';
?>
It will work if you do
echo "1";
and then
if(result == "1") {
If it doesn't (but I've checked on a code of mine without the quotes, it didn't work, with, it was ok), check the response from Firebug console.
In situations where my company's application needs to call Jquery on a dynamic element and we have the Jquery call IN the php file we'll directly call php in the Jquery call.
For example:
alert($('#').val());
Not for all situations, certainly. If you have to call a variable where you don't have PHP access to the file (possibly such as a .tpl file, depending on your setup) you might resort to setting a hidden input as detailed above.

Categories