Related
I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
I have a website, that I am building that allows consumers to order food. The user will search by their Postal code (UK) such as A1 1AA for example. Once they search by their postal code, the restaurants that deliver to their area will appear.
I am currently working on the checkout page, and i want to stop users from inputting a postal code that, that said restaurant does not deliver too. I would like to do this the moment the user presses enter on the postal code field.
I just have no idea how to do this, i have put together some ajax following a number of posts (see below,very first time using ajax so please forgive me if its sloppy) to do this,i know it is not complete but i have no idea where to go from here.
I have a string url with the users area and postal code, within it. and i also have a database with the postal codes the restaurants delivers to, i would like to do something along the lines of if the restaurant does not deliver to the postal code entered echo "Sorry, This restaurant does not deliver to A1. ".
I have tried to achieve this using both AJAX and Jquery
Code
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
$(function() {
$("#container").keypress(function (e) {
if (e.which == 13) {
e.preventDefault(); // this prevents the default action of a enter
$.post('ajax-example.php',$("#myform").serialize() , function(response) {
$('#ajaxDiv').html(response); // this will echo any response from ajax file
});
}
});
});
I have just tried it in Jquery. It work almost perfectly apart from it doesn't work on keypress but onclick, but i don't know how i would do something along the lines of if $_POST['postal'] is not equal to $postcode( users postcode variable from string url)/ the postcodes the restaurant delivers to column in my db
$(function(){
$('input[name="postal"]').click(function(){
alert('Hello...!');
});
$('#city').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('input[name = postal]').click();
return false;
}
});
});
As far as I understand, here you are trying to add a keypress handler on the input field.
This handler will make a post request and will validate whether deliver is possible in the specified postal code.
If that's the case then it would be better to use blur handler instead of keypress.
Because keypress will trigger server request for every key pressed, i.e. if user enters 5 digit postal code e.g. AA110 then 5 times post request will be sent which is unnecessary.
For jQuery; You may want to try this approach and see if it does what you want:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// DO WHATEVER YOU WANT TO DO HERE
// BECAUSE ENTER WAS PRESSED INSIDE OF THE FIELD WITH THE NAME postal
// FOR TESTING... ALERT SOMETHING...
alert("Sure, you pressed the Enter Key inside of the Postal Field...");
}
}
});
});
})(jQuery);
</script>
You can test and Fiddle it out here: https://jsfiddle.net/csqsLmxh/
OK, so here's how it all ties together.
JAVASCRIPT: JQUERY
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// SEND OUT AN AJAX REQUEST TO THE PHP-SCRIPT ON THE SERVER
// HERE WE ARE SIMPLY SAYING:
// ONCE THE USER FINISHES TYPING INSIDE THE POSTAL FIELD & HITS ENTER
// GO TO THE SERVER AND ASK THE SCRIPT: ajax.processor.php TO USE THE
// POSTED POSTAL CODE & CITY TO SEARCH FOR THE NEAREST AVAILABLE RESTAURANT...
// IN THIS CASE WE USE JSON, JUST IN CASE WE MAY WANT TO SEND BACK A COLLECTION OF DATA...
// AND SO OUR AJAX GOES LIKE THIS:
$.ajax({
url: "./ajax-processor.php",
dataType: "json", //<== CHANGE TO "HTML" IF YOU ARE EXPECTING HTML DATA.
cache: false,
type: "POST",
data: ({
postal : $("#postal").val(),
city : $("#city").val()
}),
success: function (data, textStatus, jqXHR) {
// IF OUR AJAX CALL SUCCEEDS AND THUS RETURNS SOME RESULTS
// IN THIS CASE JSON, WE CAN USE IT TO UPDATE THE #ajaxDiv...
// HOWEVER IF WE ARE EXPECTING JUST HTML WE WILL GO A DIFFERENT ROUTE IN THE SUCCESS HANDLER...
// PLEASE, NOTE THAT YOU MAY NOT HAVE BOTH JSON & HTML SIMULTANEOUSLY
// THIS IS AN "EITHER-OR" CASE HERE:
// SO IF YOU EXPECT HTML, YOU ARE ADVISED TO
// EITHER DELETE OR COMMENT-OUT FROM THE BEGINNING
// TO THE END OF JSON HANDLING LOGIC BELOW & VICE-VERSA
if(data){
// ##BEGINNING OF JSON HANDLING...## //
if(data.restaurant){
var output = "<em>Restaurant: </em><strong>" + data.restaurant + "</strong>";
output += "<br /><em>Take-Away: </em><strong>" + data.takeAway + "</strong>";
$("#ajaxDiv").html(output );
}
// ## END OF JSON HANDLING... ## //
// ##BEGINNING OF HTML HANDLING...## //
$("#ajaxDiv").html(data); <== JUST UPDATE THE DIV WITH THE RAW DATA FROM THE RESPONSE... IT IS EITHER HTML OR STRING OR NUMERIC DATA...
// ##END OF HTML HANDLING...## //
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
}
});
}
}
});
});
})(jQuery);
</script>
HTML
<html>
<body>
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
</body>
</html>
PHP
<?php
// FILENAME: ajax-processors.php <== MUST MATCH THE URL WE DECLARED IN THE AJAX DEFINITION (JS)
$postal = isset($_POST['postal']) ? htmlspecialchars(trim($_POST['postal'])) : null;
$city = isset($_POST['city']) ? htmlspecialchars(trim($_POST['city'])) : null;
// RUN YOUR QUERIES AND DO ALL YOUR MAGIC USING THE POSTED $postal & $city
// TO DETERMINE WHICH DATA ARE RELEVANT TO BE RETURNED...
// ASSUMING IN THE END YOUR QUERIES RETURNED SAY 2 RESULTS LIKE Derby Inn, Kings Pizza.
// YOU CAN THEN BUNDLE THE RESULTS INTO AN ARRAY (IF IT IS NOT ALREADY AN ARRAY OR OBJECT) LIKE SO:
$arrResponse = array(
"restaurant" => "Derby Inn",
"takeAway" => "Kings Pizza",
);
// HOWEVER, THIS IS NOT NECESSARY IF YOU ARE SENDING BACK ONLY A STRING VALUE...
// IN THE CASE OF A STRING VALUE (SAY, JUST "Kings Pizza")
// YOU COULD JUST DO IT OTHERWISE. LIKE THIS:
/* die("Kings Pizza"); */
// IF YOU DID IT LIKE THIS, BE SURE TO CHANGE YOUR THE "dataType" ATTRIBUTE
// IN YOUR AJAX FROM *JSON* TO **HTML** AND ALSO TO HANDLE THE SUCCESS
// CALLBACK DIFFERENTLY... ***SEE THE JAVASCRIPT SECTION FOR COMMENTS***
// NOW WE ARE DONE... ALL WE NEED DO IS SEND THIS RESPONSE BACK TO THE SCRIPT AS JSON LIKE SO:
die( json_encode($arrResponse));
// ALTHOUGH THERE ARE NO REAL QUERIES HERE OR ANY PROCESSING LOGIC,
// THIS SCRIPT WILL STILL RUN & SEND BACK JSON DATA TO THE JAVASCRIPT
// DOUBT IT? THEN TRY IT....
After talking to you what I understood is that you have successfully done
On pressing enter you sent a query to database
Then from database you sent process it and send error message if postal codes do not match
Now you want to know .howt to process no delivery error message sent from database inside the post callback function so as to provide alert or notification to user
For that purpose I have put down a small example
create two files Example.php and Example.html in root directory and copy each of the files content from here to inside them now in browser type
localhost/Example.htmlpress enter notice each time you run the file the output changes.
Data from php to html page is sent using json format which will be useful to you in future a lot.First data to be sent is inserted into an associative array
then it is encode into json format using json_encode() function in server side
JSON.parse() method is used to parse the json format data obtained here the value of json object is accessed using jsonobjectname.keyName to get the value sent from server.
Here in case
var returned = JSON.parse(data)
console.log(returned.Key);
these lines explains it
And by the way when associative array is converted into json format it looks like this
$result = array("Key"=>"1");
echo json_encode($result);
{"Key":"1"}
Here is document of json_encode function
Another thing I used random variable generator function rand() to simulate both true and false conditions for the loop .
Example.php
<?php
$trueorfalse = rand(0, 1);
if($trueorfalse){//your condition if there is delivery
$result = array("Key"=>"1");
echo json_encode($result);
}else{//your condition if there is no delivery
$result = array("Key"=>"0");
echo json_encode($result);
}
?>
Example.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.post("/NTD.php",function(data){
console.log(data);
var returned = JSON.parse(data)
console.log(returned.Key);
if(returned.Key==0){
$("#NotifcationDiv").html("There is no shipping to your region");
alert(returned["Key"]+"No delivery");
}
})
});
</script>
</head>
<body>
<p id="NotifcationDiv"></p>
</body>
</html>
Disclaimer:Sorry for being late I saw the OP question and worded a simple example of json and php interaction from server to client and I only so the another answer posted down later only
<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>
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
I'm implementing a relatively simple autosave system and I'd like to do so using the Prototype library. I'm using the PeriodicalUpdater request, but it's not working as I'd hoped. In short, I'm trying to, periodically, send a textarea's content via an AJAX request to a PHP page that will save it to a MySQL database. I'm doing something like (abbreviated code):
<html>
<head>
<script type="text/javascript" src="scripts/prototype.js"></script>
<script>
function autosave() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
}
</script>
</head>
<body>
<input type="hidden" id='id' name='id' />
<textarea id='myInput' name='myInput'></textarea>
<script>
autosave();
</script>
</body>
</html>
Then autosave.php will take the form contents and write them to my database. That part is working fine. What is happening, as I discovered, is PeriodicalUpdater is called with the original form input, then is called periodically with that initial form input.
So that was a long setup for a relatively short question: How do I use Prototype (if possible) to periodically make an AJAX request using the current textarea's value?
you could just use Ajax.Request with setinterval,something like this:
document.observe("dom:loaded", function() {
intervalID = window.setInterval("autosave()",500);
});
function autosave() {
new Ajax.Request('autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
});
}
Ajax.Request is the right move, but why not make it more reusable
If you just have one input, or even if you had many I'd advise something like:
<form action="/user/4" method="post">
<input type="text" name="user[name]" value ="John" class="_autosave" />
<input type="hidden" name="user[id]" value ="4" class="uid"/>
<input type="submit" />
</form>
...
$$('input._autosave').each(function(s){
s.observe("change", function(event){
var el = event.element();
var uid = el.next("uid").value;
var r = new Ajax.Request(el.up("form").readAttribute("action"),{
parameters: {el.readAttribute("name"): el.value},
});
});
});
Just place your periodical updater in dom:loaded event. It is used to ensure that all components have been loaded, better than using window.onload event. Just remember, that there is a little bit different between dom:loaded event and native window.onload event, where dom:loaded called when all dom loaded except images and window.onload called when all dom loaded including images file.
document.observe("dom:loaded", function() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php', {
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
});