Passing PHP Result to JS via jQuery .get - php

I have several instances where a form is brought into the page in an overlay via ajax. On these forms I have a "math validation" question (I know not the most secure). I am using the following to generate the problem:
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
$randomNumTotal = $randomNum + $randomNum2;
?>
the random number is displayed in a text box like so:
<input type="text" name="someName" value="<?= $randomNum ?> + <?= $randomNum2 ?>" readonly>
and validated:
...
SomeName: {
required: true,
equal: <?php echo $randomNumTotal; ?>
}
...
This works fine when the form is on the page, hidden and then displayed with a .click function. I would like to store the files remotely and display them via AJAX. No problem doing that, the problem is when I do this, the numbers generated don't match the value. I've tried putting the PHP $randomeNumTotal function on both the form itself that is brought in via AJAX and on the parent page. Neither works.
So my question is this: Can I store the PHP function in a remote file "random.php", then pass the value to it via .get? If so, how do I make "SomeName" value equal the value from the file?
<script>
$.get( 'random.php', function ( data ) {
$("SomeName").val('random.php')?//I know this isn't right
});
</script>
Thanks!

$.get( 'random.php', function ( data ) {
$("SomeName").val(data);
});
Should work. Alternatively, you could use jQuery's load() if you wanted to load the content in as the HTML of any element.

Related

updating $_POST and passing to php via jquery without submit

caveat: this would probably be pretty simple with a submit, but because of someone else's #%^$!& code, every submit clears all data on all forms on the page, so i cannot use .submit()
here's what i'm trying to do:
step 1: a link on a page, via Javascript, opens a popup. that popup has a some fields you fill it out, and using window.opener.getElementById('hiddenX').value, various hidden html elements on the original page are then updated, and the popup is closed.
step 2: on unload of the popup, the html elements are modified via Javascript.
step 3: the updated html elements are added back to $_POST on the page
Step 4: a bit of php code runs a php function using the values from $_POST as well as the values produced by earlier php code to create and send an email.
I do not think i can pass the values via a GET-style url since some of the values are very very long text strings, and tehre will probably be some arrays as well. I have tried using .post(window.location, {val1 : "1stvalue"}) in combination with a .load() on the div containing the php code from step 4. i think the div updates, but the POST value remains empty. any ideas?
script:
$(".email1").on('click', function (event) {
var win1 = window.open("../sub1.php","_blank","height=450,width=510, status=yes,toolbar=no,menubar=no,location=no");
$(win1).on('unload', function (event){
if(document.getElementById('hidden1').value != "z"){
$tosend2 = document.getElementById('hidden3').value;
...... // various changes to $tosend2 and other elements on the page
$.post( window.location, { hidden3 : "abc" }); //temporarily use "abc" instead of $tosend2
$( "#emaildiv" ).load(location.href+" #emaildiv2>*","" );
}
});
});
html / php :
<div style="display : hidden" name="emaildiv" id="emaildiv">
<input type="hidden" name="hidden1" id="hidden1" value="z" />
<input type="hidden" name="hidden3" id="hidden3" value="z" />
</div>
<div style="display : hidden" name="emaildiv2" id="emaildiv2">
<?php
echo "<div class='error'> what is the val?: " . $_POST['hidden1'] . " </code></div>";
if( !empty($_POST['hidden1']) ){
if( $_POST['hidden1'] != "z" ){
echo "<div class='error'> what is it now?: " . $_POST['hidden1'] . " </code></div>";
//emailstuff($locnlist, $_POST['hidden1'], $_POST['hidden3']);
//echo "email sent";
}
}
?>
</div>
I solved this by moving the email function and php div to a separate php page, called sub2.php, and then sending the post values to that page via ajax
$.ajax({
type: 'post',
url: '/routing/sub2.php' ,
data: { hidden1 : document.getElementById('hidden1').value ,
hidden2 : document.getElementById('hidden2').value ,
hidden4 : document.getElementById('hidden4').value ,
locnlist : loclist },
success: function () {
alert("Email has been sent!");
}
});
this doesn't actually solve the initial issue, but it works just as well.
if someone has a better solution, i'd be very pleased to know what it is

Passing the link's text as a value to the next page

I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

How to pass data from input form to js on another page

I have a page where a user enters an address and clicks search. The user should be taken to the next page which should contain a google map with the address the user specified. How should I pass the address from the form on page 1, to js on page 2 where I can manipulate it with the google maps api? I'm using codeigniter btw.
EDIT:
My ideal solution would be to use flash data or pass the address in the url the codeigniter way. My problem is i'm not sure how I would retrieve the data if I used either of these methods.
In the CodeIgniter view for page 1:
<form method="POST" action="getMap">
<input type="text" name="address" value="" />
<input type="submit" value="Map It!" />
</form>
In the CodeIgniter view loaded by getMap() method of the controller (in other words, in page 2):
<script>
address = "<?php echo htmlspecialchars($this->input->post['address']); ?>";
// create the map with the address here
</script>
You'll want to take care to do some validation on the user input.
Use url variables to accomplish this. An example might look like this:
http://www.testurl.com/mappage.html?address=someaddress&city=somecity&state=ca&zip=12345
You can pick up the values of these url variables in javascript and pass it to the google map.
Do you want the user to be able to save the url?
If you don't, just use POST in the input field and retrieve the data in the second page this way (inside the javascript):
var address = '<?=$this->input->post('address')?>'
Otherwise:
In javascript, in the first page, prevent the default action on form submit and instead redirect the user to [url of the second page]/[stuff written in the form] (I can give you a jquery example if you want);
In the second page controller (let's pretend the function is called get_map and it is in the maps controller you get the data in this way
function get_map($address = null)
Now you have the input address. Pass it to the view that should contain the map.
Why don't you simply print the POSTed information via PHP on the destination page using Javascript literals syntax?
As an example, if your form POSTs the following (both GET or POST query):
firstname=aaron&lastname=pink
you can print in a destination PHP page:
<html>
<head>
<script type="text/javascript">
var fname = "<?php echo addslashes($_POST['firstname']); ?>";
var lname = "<?php echo addslashes($_POST['lastname']); ?>";
</script>
</head>
<body>
...
<button onclick="alert(fname);">Say First Name!</button>
</body>
</html>
Then, you can simply use fname and lname Javascript vars as you wish, just as my sample button does on click!
I hope it was helpful, even if very simple :)
If you are using jquery, you can use the $.cookie plugin to transfer informations between PHP and Javascript.
or 2. Send data from 1. page per $_GET or $_POST and catch the data in 2. page
<script>
var myData = '<?php=htmlspecialchars($_POST['data_from_page1']);?>';
</script>
#Catfish you're getting all confused. The objective of making your urls "pretty" and having them resemble paths / files rather than query strings is for SEO & user friendliness. You shouldn't really be including any form input in as a "pretty" url. Either send your address data via the $_POSTS global or send it as a query string. CI uses the [QSA] flag in its mod_rewrite definitions in the htaccess file so you're totally fine to stick on a (IMO) semantically correct query string on the end.
Anyway, to the code.
On form.php:
<form action="map.php" method="get">
<input type="text" name="addr" />
</form>
On map.php:
<?php
$addr = $this->input->get('addr');
// or $addr = $_GET['addr'];
echo $addr;
?>
You can use sessionStorage on modern browsers to stock your datas between pages inside the same browsing session.
For older browser you can use an hacky solution that allow you to stock datas inside the window.name
if( typeof sessionStorage !== 'undefined' ){
myStorage = sessionStorage;
}else{
myStorage = {
setItem:function(key,val){
this.removeItem(key);
window.top.name+=(window.top.name.length?'&':'')+escape(key)+'='+escape(val);
}
,getItem:function(key){
var r = window.top.name.match(new RegExp('(^|&)'+escape(key)+'=([^&=]*)($|&)'));
return r?unescape(r[2]):null;
}
,removeItem:function(key){
window.top.name = window.top.name.replace(new RegExp('(^|&)'+escape(key)+'=([^=&]*)(?=$|&)'),'');
}
};
}
Now you can use myStorage.setItem('key',value) with each of the form fields you want to keep and retrieve them on the next page with myStorage.getItem('key')
It's not more complicated than using cookies, and have the benefits to not transfer the cookie datas in each request header.
Hope this help..
Why not do it entirely in JavaScript, using the Google Maps API ?
Let's say that your Map is initialized with the variable var Map and the Geocoder in the var Geocoder and that you have an <form id="searchForm">Address:<input /> <br /> <input type="submit" /></form>.
I'm also assuming you have jQuery loaded, so:
<script type="text/javascript">
$('#searchForm').submit( function(e) {
e.preventDefault();
var searchString = $(this).find('input:first').val(); // get the address
Geocoder.geocode( { 'address': searchString}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Map.setCenter(results[0].geometry.location);
} else {
alert("Geocode error: " + status + "\n" + "Try another address");
}
});
});
</script>
Demo here: http://jsfiddle.net/toxik/Xjy3S/embedded/result/
Codeigniter sessions would be the easiest to work with.
Once you get the address submitted, set some userdata like so.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mycontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//do something from post
$this->session->set_userdata('street', $this->input->post('street'));
$this->session->set_userdata('city', $this->input->post('city'));
$this->session->set_userdata('state', $this->input->post('state'));
$this->session->set_userdata('zip', $this->input->post('zip'));
//then redirect to the next page
redirect('mycontroller/map');
}
else
{
//load the form
$this->load->view('address_form');
}
}
function map()
{
$data = array(
"street" => $this->session->userdata('street'),
"city" => $this->session->userdata('city'),
"state" => $this->session->userdata('state'),
"zip" => $this->session->userdata('zip')
);
$this->load->view('map' $data);
}
}
Set the values in a hidden input. Just have javascript grab the value of that inputs ID...
check this
// JavaScript function function abc(pram1, pram2) { alert(pram1 + pram2); } // end of JS function
now call this function on your search form. pass all parameters you want to move other page
like
<a name="search" href="javascript:void(0)" onclick="abc('param1','param2')> search </a>

Categories