I have a php page which gets $page and $user using post method, I also have a button that i want, to open a URL in the same window using $page and $user variables when clicked, to use them with $_GET[] function.
i want my URL be like:
http://www.test.com/test.php?page=$page&user=$user
my code is like this:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
<html>
<head>
function openurl() {
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
}
</head>
<body>
<button onclick="openurl()" type="button">open url</button>
</body>
</html>
There is no need for scripting at all
If you want GET:
<?php
$page=$GET_['page']; // should be sanitized and you can use REQUEST for either
$user=$GET_['user'];
$parm = "page=".$page."&user=".$user;
?>
Open URL
If you need to post:
<form action="test.php" method="post">
<input type="hidden" name="page" value="<?php echo $page; ?>"/>
<input type="hidden" name="user" value="<?php echo $user; ?>"/>
<input type="submit" value="Open URL" />
</form>
Change these lines:
<?php
$page=$POST_['page'];
$user=$POST_['user'];
<?
....
var user=<?php echo "$user";?>;
var page=<?php echo "$page";?>;
open('www.test.com/test.php?page='+page'&user='+user,'_self');
to this:
<?php
$page=$_POST['page']; //incorrect $_POST declaration
$user=$_POST['user']; //incorrect $_POST declaration
?> //php tag incorrectly closed
....
var user=<?php echo $user;?>; //echoing a variable not string (no need for quotes)
var page=<?php echo $page;?>; // echoing a variable not string (no need for quotes)
open('www.test.com/test.php?page='+page+'&user='+user,'_self'); // link was broken, forget to put '+' after page variable in link.
You can create a form and via Javascript just run YOURFORMNAME.submit();
Use href in javaScript to move to another location:
location.href="www.test.com/test.php?page='+page'&user='+user"
Related
I have a php date created with the code:
$date = date("d-m-Y");
I can echo this date out with:
echo $date;
and that works fine. But I want to pass this to a javascript function onClick of a button on my page. So I have:
<input type="button" onClick="myFunction(<?php echo $date; ?>)" value="Today">
Pretty standard. But when I alert the function in javascript:
function myFunction(phpDate) {
alert(phpDate);
}
it then gives me:
-2018
in an alert box.
Full code
For anyone wondering, here is my full code:
<?php
$date = date(d-m-Y);
echo $date; // to test date is working (it is)
?>
<script type="text/javascript">
function myFunction(phpDate) {
alert(phpDate);
document.getElementByID("dateField").valueAsDate = phpDate;
// can someone please tell me if ^^^this^^^ line above is correct syntax wise.
// I'm particularly concerned with '.valueAsDate'.
}
</script>
<html>
<input type="date" id="dateField">
<input type="button" onClick="myFunction(<?php echo $date; ?>)" value="Today">
</html>
BTW I do have <!doctype html> and <head> and <body> tags in there. So my page works.
You are actually passing the date as Number (2 - 1 - 2019 = -2018 for example), not as a String. You will need to wrap the date value in single quotes
<input type="button" onClick="myFunction('<?php echo $date; ?>')" value="Today">
I have 2 page
the innerhtml onclick page (a.php)
the page that start session (b.php)
in a.php I write function onclick to change some text
and I add the session from b.php in this text, but nothing change in text
$(document).ready(function(){
$('.add-to-cart').on('click',function(){
document.getElementById('outside_cart_text').innerHTML =
"Qty type <?php echo $this->session->userdata('qty_type'); ?> amount <?php echo $this->session->userdata('qty_product');?>";
});
});
it change the original text to "Qty type amount". But session value not appear.
the question is how to make it appear instantly?
additional detail : My click is on the button sumbit to other page, but I have already use this trick. It work like ajax. so after click I still in the same page (and not reload)
<style>
.hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>
<iframe name="hiddenFrame" class="hide"></iframe>
<form action="receiver.pl" method="post" target="hiddenFrame">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
Maybe it would work if the variables are encoded in json format.
document.getElementById('outside_cart_text').innerHTML =
"Qty type
<?php echo json_encode($this->session->userdata('qty_type')); ?>
amount
<?php echo json_encode($this->session->userdata('qty_product'));?>";
});
$(document).ready(function(){
$('.add-to-cart').on('click',function(){
var qty_type = '<?php echo $this->session->userdata('qty_type'); ?>';
var amount = '<?php echo $this->session->userdata('qty_product'); ?>';
$("#outside_cart_text").html("Qty type "+qty_type+" amount "+amount);
});
});
I cant seem to find the answer for this one. I need to grab a PHP variable and insert it into javascript.
Here is an example of what I have in the body of a PHP page:
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php Print($info); ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<?php
$info="some info";
?>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
So the problem is that the alert pops up but doesn't echo the $info string. Obviously i'm missing the right way to grab a PHP variable. Please help.
If the php variable is visible inside the inner HTML, you could do something like this to grab the variable:
HTML:
<span class="variable-content"><?php echo $variable; ?></span>
jQuery:
var php_variable = $(".variable-content").text();
alert(php_variable);
Change:
alert(info);
to:
alert('<?php echo "some info"; ?>');
It looks to me like you are declaring the variable after you use it. So there is nothing in $info.
try:
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo $info; ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
try this
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<span id="info" hidden><?php
$info="some info";
echo $info;
?></span>
<form id="frm1" method="post">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = $("#info").text();
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
</body>
</html>
Primary issue with your example code
All of the PHP executes ahead of the JS. PHP executes, then outputs Your HTML and JS to the browser where they are rendered/executed/etc.
As such, your Print of $info is executing before your declaration and definition of $info. You need to define it, then output it.
Further issues you should consider
Once this is solved, you'll eventually run into issues with simply spewing data into the middle of JS. It is not easily maintained, and unprepared data will eventually break your JS syntax. When I have to do such a thing, I generally separate the two as much as possible:
<?php
// declare and define the data
$info = "foo";
?>
<script>
// prepare an IIFE which takes the data as a param
(function (info) {
// inside this function body you can use the data as you
// please without muddling your JS by mixing in PHP
alert(info);
}(
// in the invoking parens, output encoded data
<?= json_encode($info) ?>
));
<script>
Another benefit of this approach is that you can pass any PHP data structure to JS without changing the approach in any way. (As opposed to using inputs or element texts where you'd need to parse the JSON and keep track of which elements contain which values)
If you don't want to use JQuery you could put the php value into a hidden input and get it from the hidden variable with JavaScript documentGetElementById... that way you can keep your script in the head, which seems to meet your requirements. Either the hidden span as per #Miko or:
<input type="hidden" id="php_info_data" name="php_info_data" value="<?php echo $info; ?>" />
and in your header script which executes after the body has loaded:
var info = documentGetElementById('php_info_data').value;
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo($info); ?>";
alert(info);
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
Try this
var info = "<?php echo $info; ?>";
try this
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(<?php echo $info;?>);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
you can convert PHP variable to JSON and then send it Javascript, becoz JSON
is supported by all language
Example
var a=<?php echo json_encode($info); ?>
alert(a);
or simply
var a=<?php echo $info; ?>
alert(a);
<?php $info=10; ?>
<script>
var a=<?php echo $info; ?>;
var a1=<?php echo json_encode($info+10); ?>;
alert(a);
alert(a1);
</script>
I wrote a piece of code, when the user click on submit button it send a string to PHP and then my code will run a Mysql query (based on the submitted string) and then using file_put_content it will upload the mysqli_fetch_array result to the file.
All I want to do is without refreshing the page it submit the value to php form and run the code then show Download From Here to the user.
How should I do that using javascript or jQuery ?
if(#$_POST['submit']) {
if (#$_POST['export']) {
$form = $_POST['export'];
echo $form;
$con1 = mysqli_connect("localhost", "root", "", "test_pr");
$sql2 = "SELECT email FROM `my_data` WHERE email LIKE '%$form%'";
$result2 = mysqli_query($con1, $sql2);
$rows = array();
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$rows[] = $row['email'] . PHP_EOL;
}
$nn = implode("", $rows);
var_dump($rows);
echo $nn . PHP_EOL;
$file = fopen("export.csv", "w");
file_put_contents("export.csv", $nn);
fclose($file);
}
}
?>
<html>
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method=post>
<input name="export" type="text" value="example" /> Export Address<br/>
<input name="submit" type="submit" value="submit" />
Download From Here
</form>
</html>
Assuming you know how to include jquery, you would first bind a submit handler to the submit button, (I've added an id to make it easier) and prevent the default submit action. Then add an AJAX post request to the handler. This will post to your php file. Have that file echo out your link, then have the ajax callback function append it to the desired element. Something like this:
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="form1" //Add an id to handle with >
<input name="export" type="text" value="example" /> Export Address<br/>
<input name="submit" type="submit" value="submit" />
Download From Here
</form>
<script>
$("#form1").submit(function (event) {
event.preventDefault();
$.post("//path of your php file here",{inputText: $("input[type='text']")},function (returnedString) {
$("#whereToPutReturnedString").append(returnedString);
});
});
</script>
Also, if you want to just show the link when the button is clicked, do the following:
<script>
$("input[type='submit']").submit(function () {
$("#idOfElementToPlaceLink").append("Your anchor text");
});
</script>
or you could just have it hidden with css or jquery and do $("#theId").show();
If you need more help, just holler!
I have simple form:
<div class="form-style-2">
<form action="" name="formular" id="formular" method="GET">
<label for="actual_position"><span>From: <span class="required"></span></span><input name="actual_position" type="text" maxlength="512" id="actual_position" class="searchField"
<?php if(!empty($actual_position)){ ?>
value="<?php echo $_GET['actual_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<label for="final_position"><span>To: <span class="required"></span></span><input name="final_position" type="text" maxlength="512" id="final_position" class="searchField" <?php if(!empty($final_position)){ ?>
value="<?php echo $_GET['final_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<input type="submit" value="Find path" />
And another multiselect in form who gets values form url link and compere with database and get som results. Here is a code:
<table width= "570px">
<tr><td width="200px" style="align:center"><b>Waypoints:</b> <br>
<tr><td width="370px"><select style="float:center; margin-left:5px" multiple id="waypoints">
if(!empty($urls)){
foreach($urls as $url){
if($result = $conn->query("SELECT * FROM $table where $ID = '$url' "));
$atraction = $result->fetch_array(); ?>
<option value="<?php echo $atraction['lat']. "," . $atraction['lon']; ?>"
> <?php echo "<b>".$atrction['City']. ", " . $atraction['Name'];?> </option>
<?php
}
}
?>
</select></td></tr>
<br>
</table>
</form>
And getting ID-s from url code:
if(!empty($_GET[$ID])){
$urls = $_GET[$ID];
foreach($urls as $url){
// echo $url;
}
}
... and after submit, it Post to URL some variables like this:
http://127.0.0.1/responsiveweb/travel.php?actual_position=Paris&final_position=Praha&ID[]=23&ID[]=15&ID[]=55
... very important for me are ID-s values ... but when I change for example actual position and then submit I lost my ID-s and I get something like this: http://127.0.0.1/responsiveweb/travel.php?actual_position=Berlin&final_position=Praha
Can you help me how to get after clicking on submit button full url link? Thanks
I had some trouble understanding your question OP, but I think I understood somehow what you ment, so I decided to try giving you a answer.
I have re-written your code, and tried to make somehow better code-structure. I have also used form method POST in my example, so you can see how you can change the get data on the redirection url.
See my code example here: http://pastebin.com/wQ7QCBmt
I also decided to use the form method POST instead of GET, so you can easily do back-end tasks, and extend your link if neccessary. You could also add more data to the link even when using GET. You could add an hidden input inside your form, example:
<input type="hidden" name="more_data" value="a_value" />