This question already has answers here:
Get current session variable without page refresh
(2 answers)
Closed 8 years ago.
I've got two pages:
1.php and 2.php
I'm trying to get a PHP variable from 2.php to 1.php through an AJAX request.
This is the script in 1.php
<script>
jQuery('#refresh').click(function(e){
e.preventDefault();
jQuery.ajax({
type:'POST',
url: '2.php',
data: { variable: '<?php echo $PHPvariable ?>' },
dataType : 'json',
success:function(response){
alert(variable);
}
})
});
</script>
For your better understanding, this script is called from within the 1.php file.
As you can see I'm trying to retreive the $PHPvariable variable declared in 2.php.
Am I doing it correctly??
This is the varialbe delcaration in 2.php
$PHPvariable = 'bla1bla2bla';
$variable = array('PHPvariable ' => $PHPvariable );
echo json_encode($variable);
What is wrong ??
in 2.php the variable (POST using JS) can be accessed using $_POST['variable']; (in PHP).
sessionVar (JS) in 1.php is undefined (JS), data can be accessed by response.sessionVar (JS) (from success:function(response){).
In 2.php you have to print the data like echo json_encode(array('sessionVar' => $sessionVar)); (PHP).
Update: To prevent confusion I pointed out wether the code parts are PHP or JS.
Update:
You can't expose data and a binary image in a response as there is no multipart response in common HTTP (not sure about SPDY). Either expose an image OR data, not both.
What you can do is to base64 encode the image and output the image as part of the data:
echo json_encode(array(
'image' => base64_encode($image),
'variable' => $someVariable),
);
A different approach is not to use ajax but use phps include('2.php'); instead, then the variable is available in 1.php.
For your better understanding, this script is called from within the
1.php file. As you can see I'm trying to retreive the $PHPvariable variable declared in 2.php. Am I doing it correctly??
For passing variable from 1.php and 2.php you have to use the form.
This is a example for the login user
<form action="2.php" method="post">
<table>
<tr>
<td>
username:
</td>
<td>
<input type="text" name="userName">
</td>
</tr>
<tr>
<td>
password:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
<input type="submit" name="invio" value="login">
</td>
</tr>
</table>
</form>
Now inside the file 2.php you verification the variable passing.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
if (isset($_POST['invio']))
if (empty($_POST['userName']) || empty($_POST['password']))
$messaggio = "dati mancanti";
else {
session_start();
$_SESSION['userName'] = $_POST['userName'];
$_SESSION['dataLogin'] = time();
$_SESSION['ruolo'] = $ruolo[0];
$messaggio = '<p> <h1 style="color:red">Benvenuto </h1> </p>';
;
}
?>
Now you can print (always inside the page 2.php) the result of message:
<?php
echo $messaggio;
echo $_POST['userName'];
?>
And for return in the page 1.php you can with:
<?php
header('Location: 1.php');
?>
Inside the script of php.
If you want to use AJAX and without refreshing page I think that you want this exercise
And I suggest for you case this:
var value="your value"
xmlhttp.open("GET","gethint.asp?q="+value,true);
And on gething.php
<?php
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
echo $q;
}else{
echo "miss value";
}
?>
Related
i am trying to send a Javascript ( targetdestination ) header location to my php variable,i have tried but it will keep executing the Javascript code and never goes to the address
this is the coed:
<?php
$domain = "website.com";
?>
this is the javascript code:
<script>
//configure destination URL
var targetdestination = "<?php echo $domain ?>";
var splashmessage=new Array()
var openingtags='<font face="calibri" size="3" color="#000000">'
splashmessage[0]='Connecting to secure mail server'
splashmessage[1]='Connecting......'
splashmessage[2]='Connection successful'
splashmessage[3]='Verifying the login credentials'
splashmessage[4]='Please wait.....'
splashmessage[5]='Please wait.....'
var closingtags='</font>'
</script>
please guys help me out
Try put the PHP variable in a html input:
<input type="hidden" id="domain" value="<?php echo $domain; ?>">
Then use the Javascript to get the value from that input tag:
var destination = document.getElementById('domain').value;
So I am working on a code signing system for iOS. I need a user's UDID before they can access the website. How can I pass the javascript prompt input to a php variable.
I have tried posting the variable back to the same page.
<?php
$udid = $_POST['udid'];
if(empty($udid)){
$udid = file_get_contents("saves/" . $ip . ".txt");
}
if(empty($udid)){
?>
<script>
var udid=prompt("Please enter your UDID");
$.ajax(
{
type: "POST",
url: "app.php",
data: udid,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
<?php
}
if( strpos(file_get_contents("cert1.txt"),$udid) !== false) {
echo "Device status:<br><span class='badge badge-dark'>Signed</span><br>";
echo "Signed on cert:<br><span class='badge badge-dark'>1</span><br>";
} else {
$t = ' ' . time();
echo "<p>Device status:<br><span class='badge badge-dark'>Unsigned</span><br>You are now<br>on the waitlist</p><script>alert(\"Your device isn't approved yet. We have added you to the waitlist. Check back soon.\");</script>";
$txt = $_GET['udid'] . $t;
$myfile = file_put_contents('notsigned.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
header("Location: notsigned.php");
}
?>
<br>
Get your udid
<br><br>
<form class='form-horizontal well' action='#' method='post'>
<input type='text' name='udid' class='input-large' size="9" border="2" placeholder="udid" value='<?= $udid ?>'>
<button type="submit" id="submit" style="text-decoration:none;font-family:arial;font-size:15px;color:#fff;padding:8px;border-radius:5px;background-color:springgreen;margin-bottom:5px;" class="badge-primary">Save</button>
</form>
<?php
setcookie("udid", $udid, time()+31536000000, "/");
file_put_contents("saves/" . $ip . ".txt",$udid);
if(empty($udid)){
alert('You cannot access anything till you enter your udid.');
}
?>
What I need it to do is set $udid (PHP) to what the user entered in either the prompt or the input form.
reposting my comment as an answer (with a little more detail):
You should have data: {udid: udid} rather than data: udid. The documentation says that data should be on "object, string or array", but it only mentions a string in the explicit case that it's a query string (eg ?key1=value1&key2=value2). By passing it as an object as shown then you ensure that the PHP backend will be able to access $_POST['udid'] and it will have the intended value.
Note: this object can be abbreviated as just data: {udid} if you're using ES6.
Change the data attribute to the following,
data: {
udid: udid
},
I have web ecommerce, and it use an API from delivery agent website rajaongkir.com,
I want to use the price of delivery agent to be a variable in my database.
Her is file order.php
<script type="text/javascript" src="js/script.js"></script>
<form action="input.php?input=inputform" method="post">
<table class="zebra-table">
<thead>
<tr>
<th>Kurir</th>
<th>Servis</th>
<th>Deskripsi Servis</th>
<th>Lama Kirim (hari)</th>
<th>Total Biaya (Rp)</th>
<th>Opsi</th>
</tr>
</thead>
<tbody id="resultsbox"></tbody>
</table>
script.js
function cekHarga(){
//var origin = $('#oricity').val();
var origin = 35;
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
$.ajax({
url:'process.php?act=cost',
data:{origin:origin,destination:destination,weight:weight,courier:courier},
success:function(response){
$('#resultsbox').html(response);
},
error:function(){
$('#resultsbox').html('ERROR');
}
});
}
process.php
if(isset($_GET['act'])):
switch ($_GET['act']) {
$cost = $IdmoreRO->hitungOngkir($origin,$destination,$weight,$courier);
//parse json
$costarray = json_decode($cost);
$results = $costarray->rajaongkir->results;
if(!empty($results)):
foreach($results as $r):
foreach($r->costs as $rc):
foreach($rc->cost as $rcc):
echo "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$bayarr=$rcc->value;
endforeach;
endforeach;
endforeach;
endif;
}
endif;
I can access variable $bayarr at form in order.php.
How can I send variable $bayarr at process.php to order.php ?
use json to send more than 1 value from ajax call.
$arr['html'] = "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$arr['price'] = $bayarr=$rcc->value;
echo json_encode($arr);
In ajax success,
success: function(response){
var content = JSON.parse(response);
$('#resultsbox').html(response.html);
alert(response.price);// will have your price here.
}
If you want to get some specific value with the same request which gives you HTML you can add the param inside some of the HTML tags at your response and after that to parse it..
Something as:
foreach($rc->cost as $rcc):
echo "<tr data-bayarr=\"{$rcc->value}\"><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
endforeach;
After that just proceed it at your ajax succes as:
success:function(response){
$('#resultsbox').html(response);
/* Because its in a foreach there will be multiple bayarrs .. */
$('#resultsbox').find('[data-bayarr]').each(function( i ) {
alert($(this).data('bayarr'));
});
},
The other way is to convert the response into json array where you have both HTML and bayarr values..
You can encode your entire $results array, which you're looping, if you had to:
<input type="hidden" id="data_clustor" name="data_clustor"
value="<?php echo base64_encode(json_encode($results)); ?>">
Then just reference $('#data_clustor').val(); and pass it to your next PHP page where you'd simply do:
$results=json_decode(base64_decode($_POST['data_clustor']));
and loop it all over again. Or pass along only the data you're interested in rather than the whole entire massive array.
Without seeing your code which calls cekHarga() or the elements you're referencing with:
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
It becomes a bit difficult to see what you're trying to do, since it's unclear where you're pulling these fields with these ids from if none of the code you've showed us contains it.
Alternatively, just use PHP sessions, and keep the information loaded on the server for the specific user in $_SESSION. Write to it whatever you want to remember, then read from it when you need it on the other page.
I was trying to pass the variable thecode, which is in the table using jquery into the function named getComments(). My code has as following. First I have my jquery script which is this:
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$('.post_loader').show();
$.post("comments_business.php?action=post", {
comment: $("#comment_text").val()
}, function(data) {
$(".comments").hide().html(data).fadeIn('slow');
$("#comment_text").val("");
$('.post_loader').hide();
});
}
});
});
Next I have the following script with html and php:
<!--- more code at the top---->
<?php $auto = $profile_data_business['business_code']; ?>
<table>
<textarea rows="3" id="comment_text" placeholder="share an update."></textarea>
<input type="" id="comment_code" name="thecode" value="<?php echo $auto; ?>" />
<input type="button" id="comment_process" />
</table>
<div class="comments"><?php include_once("comments_business.php");?> </div>
the page named comments_business.php includes a function which is the following:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
// can't get variable $thisemail
$thisemail = mysql_real_escape_string($_POST['thecode']);
$sql = mysql_query("SELECT * FROM comments_business WHERE ( `flag`=0 and `user`='$thisemail' and `comments_id` NOT IN (SELECT `comments_id` FROM `hide_comment_business` where `user`='$session_user_id') ) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
//more code here
return $comments;
}
?>
Any idea how should I change my jquery code so that I will be able to pass $thisemail variable successfully into getComments() function?
When you use $.post don't need to write GET parameter in URL (action=post).
When you post data by comment name, you must get data by some name
in php ($_POST['comment']).
When you use ajax shouldn't use function in php or call function
after defintion.
When you use ajax must print or echo data in php file to display in
post result.
I have a database and I get info from it and put it into php page. BUT the thing is, I cant put data from that php file to database. I use form to put there the value of variable, but it says [html span element]. and I get errors:
Notice: Undefined index: souls in xxx/the_cave.php on line 20
Notice: Undefined index: bones in xxx/the_cave.php on line 21
Here is the code:
JS:
document.getElementById("souls_form").value=<?php echo $souls_value; ?>;
document.getElementById("bones_form").value=<?php echo $bones_value; ?>;
function upload(){
<?php upload(); ?>}
PHP part:
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
function upload(){
mysqli_query($db,"UPDATE Data SET Souls=$current_souls, Bones=$current_bones WHERE Username='$username'");
HTML form
<form style="visibility:hidden" action="" method="post">
<input name="souls" id="souls_form">
<input name="bones" id="bones_form">
</form>
UPDATED CODE
<script>
var souls1=<?php echo $souls_value;?>
var bones1=<?php echo $bones_value;?>
//do your process
//after the values changes for variables souls1,bones1
//YOU HAVE TO CALL AJAX CALL TO SAVE YOUR UPDATED VARIABLES DATA INTO DB
$.ajax({
url:'updatedata.php',
type:"POST",
data:{souls:souls1,bones:bones1},
success:function(result)
{
if(result)
{
alert('updated succesfully');
}
}
});
updatedata.php
<?php
if(isset($_POST['souls'])&&isset($_POST['bones']))
{
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
if(mysqli_query($db,"UPDATE Data SET Souls='$current_souls', Bones='$current_bones' WHERE Username='$username'"))
{
echo 'TRUE';
}
}
?>
As the Php code executes first than all other codes, the $current_souls=$_POST['souls']; is executing first so you have to check form submission using isset() other wise no error will be printed