How can I pass a variable from PHP to javascript - php

I have a php page with
<?php echo $_SERVER['DOCUMENT_ROOT']?>
Then my javascript is
var data = "Not Set";
$.get("test.php",function(returnData,requestStatus,requestObject){
data = returnData;
alert(data);
});
If I navigate directly to the php page on the site, it displays the data that I need.
I just can't seem to get the data into my javascript.
Am I on the right track and if so where am I going wrong?
Or is there an easier way to get the full filepath when working with a server?
Currently if I run document.location.href in my javascript it returns .
http ://127.0.0.1/etc

The code below will work on ".php" file. NOT ON ".html" file.
You can use the php variable with echo in javascript. For example
alert('<?=$phpvariable?>');
or
alert('<?php echo $phpvariable ?>');

It seems you are overthinking this. There is hardly any need to use ajax, but of course you can and just append() the data from the ajax call to your $('body') and jquery will automatically execute things inside a <script> tag.
var serverRoot = '<?php echo $_SERVER['DOCUMENT_ROOT']?>';

Try following
Instead of GET send $.post request and file don't return any thing just write
$.post("Requestedfile.php",
{
data :data
},
function(data) {
if(data == false)
{
//do something
}
else
{
//do somthing
}
}
);

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

How to clear the session using a button and javascript

Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert to jquery format? Thank you.
js
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
$.post("clear.php",function(data){
});
});
});
php
<?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>
Is this one ok ?
make an ajax call to the server and let your server page kills/ends the session
HTML
<a href="#" id="aKill" > Kill Session</a>
Script
$(function(){
$("#aKill").click(function(){
$.post("serverpage.php",function(data){
// if you want you can show some message to user here
});
});
and in your serverpage.php, Execute the PHP script to terminate the session.
Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();
Now, make a simple request
$("#aKill").click(function(){
$.get("clearsession.php");
}
The below covers the basics more or less.
The Function:
function destroySession(){
var theForm = $("#yourForm");
//we don't need any ajax frame.
theForm.each(function(){ this.reset() });
$.ajax({
url: 'destroysession.php',
type: 'post',
data: 'sure=1', //send a value to make sure we want to destroy it.
success: function(data);
alert(data);
}
});
}
The PHP (destroysession.php):
<?php
//whatever logic is necessary
if(!empty($_POST['sure'])){
$sure = $_POST['sure'];
if($sure == 1){
//logic to destroy session
echo 'Session Destroyed!';
}else if($sure != 1){
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
}else{
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
?>
The HTML:
<input type='button' value='reset' onclick='destroySession()'>

How to call a specific function in a PHP script via Ajax?

Lets say I have a file called functions.php, and it has two separate functions inside:
One would get the time
And the other would get the date
How will I, using JQuery AJAX retrieve data from the function that retrieves the date. How do I specify in the JQuery code which function on the server to pick.
I hope I am making sense. Thanks.
You could include a selector in the ajax request data. For example:
$.ajax({
url: "functions.php",
data: "function=time", // or function=date if you want date
...
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['function'] == 'time') {
// do time stuff
} elseif($_GET['function'] == 'date') {
// do date stuff
}
}
You don't specify in jQuery what function to execute in PHP. What you do is request a document, possibly with a query string, and read the results. Your functions.php script is responsible for executing whatever is requested.
So, you might from jQuery request functions.php?fn=time in one place and functions.php?fn=date in another. Then, in functions.php, you would examine the query string and execute the appropriate function for what was requested, returning the results to jQuery.
$(document).ready(function()
{
$(".link").click(function()
{
var data['func'] = "time";
var url = functions.php
$.get(url, data, function(result)
{
$("#feedback").html(result);
});
});
});
then your php file would be,
if(isset($_GET['func']))
{
if($_GET['func'] == "time")
{
showTime();
}
else
{
showDate();
}
}
function showTime()
{
//show time
}
function showDate()
{
//show date
}
Code is untested but should be a good starting point for you.
you can add a parameter to the url:
example:
function.php?g=1
now, on the serverside check for the get parameter:
if($_GET['g']==1)
{
echo date();
}
else
{
echo time();
}
What is the response your are getting. You are getting the response in XML or some other format. If your response is XML try with this option.
$.ajax({
url:path,
data:{projectId:inpprojectId},
dataType:"xml",
success:function(data){
$(data).find("CheckAmount").each(function(){
total = $(this).find("TotalAmount").text();
usdAmt = $(this).find("PettyCashAmount").text();
validateBudget(total,inp);
});
}
});

How can we call Php functions based on the Java script If-else condition?

How can we call Php functions with in the JavaScript If-else condition.
For Example,
if (top == self) {
// not in any kind of frame
} else {
// in a frame
// calling php function
}
</script>
Here, PHP exit() function calling for both if and else conditions. I need to call that function for only in else part.
Please advise me.
Thanks.
Prabhu
Technically not possible. However you can make an AJAX call to a PHP page and get the values returned by it.
PHP (test.php):
<?php
$x = 10;
$y = 20;
$val = $y / $x;
echo $val;
?>
Javascript (jQuery):
$(document).ready(function() {
$.ajax({url: 'test.php',
type: 'POST',
success: function(data){
//takes the value returned by test.php and
//puts it directly into the element with
//id = someElement
$('#someElement').html(data);
}
});
As far as calling exit(); and making the page that holds the JavaScript stop processing, you just can't unless you control the logic on that same page in PHP and call exit(); from there.
Do not try to mix javascript with php.
If you want to stop the page from loading you could also redirect the page to an other (php) page where you simply put exit();
If this javascript is in a function just use : return; or return false;

Change page dynamically

<?php
$go = $_GET['go'];
if(!empty($go)) {
if(is_file("page/$go.html")) include "page/$go.html";
else echo "<h1>Error 404</h1><p>Strona nie odnaleziona</p><p>Warunek ?go jest niepoprawny</p>";
}
else include "page/start.html";
?>
<script>
$.get('go', function(change) {
$('#center').load('page/<?php echo $go ?>.html');
});
</script>
I have somethng like this but it doesn't work. I just want that the page which is loaded (?go=name) won't refresh whole page
Firstly, that's vulnerable to an LFI vulnerability (Local File Inclusion). Consider what happens when someone enters: http://site.com/file.php?go=../../../../../../../../etc/passwd%00
Also, you can't just echo your filename and expect it to print it out...if you want to include the contents of the page in $go and print out $go, then use:
$go = urldecode([$_GET['go']);
$go = str_replace("/", "", $go);
$go = "page/$go.html";
EDIT: Actually, if you use my above code, they could still access files in the local directory, such as .htpasswd and .htaccess, so just don't let your users include any local files. There are better ways to solve the problem you have.
As for the AJAX, follow jeroen's advice.
You are mixing two ajax functions, $.get and .load and you are missing an event handler.
You will need something like this:
$('#go').live('change', function() {
$('#center').load('page/' + $(this).val() + '.html');
});
I have used live instead of change in case the go button is located in the refreshed section of the page.
Note that I am guessing that you want to refresh a section of your page based on a selection, the question / code isnĀ“t exactly clear about that...
Is this what you want to achieve?
<script type="text/javascript">
$(document).ready(function() {
var getgo = '<?php echo $_GET['go']; ?>';
if(getgo.length) {
$('#center').load('page/'+getgo+'.html');
}
});
</script>
<div id="center"></div>
It will load the contents of page/[your go param].html into #center.

Categories