I have a php-file with a link in it. When pressing the link a jQuery alert popup shows up asking the user if he would like to proceed.
In the alert popup I want to be able to ask the user if he would like to proceed in different languages depending on what language he have chosed from the begining on my site.
So my code partially looks like this and some of the code is to explain how I think about it.
example.php:
<?php
$lang = $this->lang->line('alert_message');
echo 'Accept';
?>
functions.js:
$("a.link-alert").click(function(event){
var answer = confirm($lang);
if(answer){
// go to destination
return true;
}else{
// cancel
return false;
}
});
As seen above $lang is in the .php-file and I want to print it through an alert in functions.js. I preferably dont want to do inline js-code, though this would be messy.
Add it as a data attribute like this:
echo 'Accept';
And fetch it in the click event like this:
var lang = $(this).data('lang');
As a side note, you could refactor your code a bit:
return confirm(lang);
Related
I want to add a button on my website, where a User can delete his Account. Unfortunately I don't know how to realize it...
my Code so far:
Javascript:
<script language = "JavaScript" >
function delete(id) {
if (confirm("Do your really want to delete your account?"))
{
header("refresh:1;url=intern.php?act=account");
}
else
{
}
}
</script>
my .html file:(there are no tags like html title head... it begins with ?php..)
<td></form><input type='submit' name='deleteuser' value='Delete Account' onClick='return delete()'/></form></td>
Also i have an if clause in the .html file:
if(isset($_POST['deleteuser'])) {
if(delete() == true){
delete_user;
}
else{
header("refresh:1;url=intern.php?act=account");
}
}
The Button is there and when I click on it, it asks me if I'm sure to delete my account, but afterwards I got an error: "Fatal Error:Call to undefined function delete() "
I have a stored procedure named: sp_deleteAccount. In my config.php I declared it as:
$SQL_delete_user = "CALL sp_deleteAccount('";
Now I don't know how to bind that stored procedure in the code so that the Account will be deleted after pressing "Yes I want to delete my Account".
Hope I didn't miss anything and someone can help me
JOP
In this portion you're calling a php redirect(i think?) in javascript without php open tag so that's not going to work. Instead you can use a javascript reditrect if the 'if' statement returns true(yes) then redirect to a url with a get variable of delete or something, see below.
edit -- you'll probably want the id as well so i made adjustments. PLus in the onclick in the form you'll need to pass the id, unless it's stored in a session variable or something, in which case you don't need to pass it into the url. your sql should end with "WHERE id=" then just tack the id onto the query. This is just a simple example to get you started, always be cautious of sql injection, but i'll leave preventing it up to you.
<script language = "JavaScript" >
function deleteUser(id) {
if (confirm("Do your really want to delete your account?"))
{
window.location.href= 'intern.php?delete=true&id='+id;
}
else
{
window.location.href = 'intern.php?act=account';
}
}
</script>
next in intern.php check for the get variable
if(isset($_GET['delete'])) {
$mysqli = new mysqli(connection variables here);
$mysqli->query($SQL_delete_user.(int)$_GET['id']);
}
give that a try, rearrange the code as you like but that should get it done.
as for the error, you can't use the keyword delete for a function name. One last thing, for this to work make the input type "button"
I am not sure there might be a way to achieve it using the approach you are trying , but I am not aware of it. For this I would typically use an ajax call to an url, on the click event of the OK button in the jquery-ui Dialog. And then process the logic and on success create another dialog for confirmation.
I searched and struggled with this issue until I did a little lateral thinking.
I used JavaScript to show a hidden div containing the Yes/No options.
Then an onClick around the Yes option which loaded the php script into a hidden iFrame.
The onClick around the No option simply hid the div and did nothing else.
A bonus is being able to style the div any way I wanted, show and hide it with an effect and place it exactly where it looked best.
Ok so here's my situation: I have a page with 5 jquery-ui tabs, 3 of them contain a table each that is generated by php for the data, with each of them there's a set of input to filter according to the date, each table have their own form and update button. Now what I want to achieve is once I refresh and get back to the controller I want to add the corresponding fragment according to the button I pressed.
For example: If I click on the update button from the first tab I want to add #tabs-1, if it's the second one then I want to add #tabs-2.
Now I know I can do:
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
Fine that gives me the correct url, but how do I make the browser go there at runtime? Is there any way to do this?
Here's a part of my controller, the main one.
class PageOptimisationV2C {
public static function main() {
$class = __CLASS__;
$c = new $class;
$c->get();
}
public function get() {
$this->display();
}
private function display() {
$tpl = new PageOptimisationV2V();
$client = ConsulterClient::getClientByNoClient(isset($_GET['cid']) ? $_GET['cid'] : 0);
$tpl->client = $client;
if(isset($_GET['cid'])){
$tpl->StatsLignesCellulaire = self::buildCellStatsReport();
}
$_SERVER['SCRIPT_URI'] = $_SERVER['SCRIPT_URI'] . "#tabs-2";
$tpl->display();
}
}
And then it goes on and displays the page. What would be the optimal solution to get to a fragment of the page, according to the submit button that is pressed.
I tried to make a jsFiddle to show you how the page looked but it got too messy and couldn't get the CSS to work right.
Every detail of information is appreciated.
The only way i'm aware of to do this with PHP is to do a redirect.
header('Location: ' . $_SERVER['REQUEST_URI'] .'#tabs-2');
This of course will result in another request and require you to do some workaround with your flow but its the only way to send a new url back to the browser.
Though it isn't a runtime PHP method you can also just embed the selection Javascript, for example:
var index = $.index($(<?PHP echo $tab; ?>));
$('#tabs ul').tabs('select', index);
and allow it to go through the normal selection process.
You can also just embed a hidden element, something like
<input type="hidden" name="tab-selected" id="tab-selected" value="tabs-2" />
and have some Javascript to check if the element exists and has a value and then select the tab like this:
$(function() {
if ($('#tab-selected').val()) {
var index = $.index($('#tab-selected').val()));
$('#tabs ul').tabs('select', index);
}
});
Today, with a fresh mind, I thought of something else to do while reading MWJump's answer... Why not use the action attribute of the form! It's there for a reason! So for each of my form (I have one in each of my tabs) I slapped the action attribute to be the fragment of the according tab so for the first tab action="#tabs-1" and the second action="#tabs2" and so on...
I found this solution to be the simplest and easiest in this particular case.
I have a form which uses the target attribute to target an iframe when the form is posted which posts to a PHP script. This part is working fine but I need to do something based on several results that the php script will put in the iframe.
What I am thinking of doing is when the PHP script has finished posting it echo's out some hidden input fields that contain various elements, such as the state of the post, whether it succeeded and what the final result was if it was successfully posted.
However, if I did this it would put it into the iframe so then the main web page wouldn't be able to access the hidden input fields.
How would the main web page be able to access these hidden input fields so that the main web page can perform some action, I.e. make a div within the web page show a specific error message or whatever.
The other thing is, once I know how I can get the data from the hidden input field, how would I know when I can go and get the values. I was thinking that when the form is posted via a JavaScript document.forms["myform"].submit() code I could then do a while loop and check to see if another hidden input field status is set to complete and once it says complete I can then get the values from the hidden input field.
I'm not sure if the way I suggested is the right way or doing what I want to achieve or if there is a better way of doing it.
UPDATE
I've tried what #lanzz suggested but it doesn't appear to have worked. Below is what I have tried.
$("iframe#image_upload_frame").on('load', function()
{
var iframeBody = this.contentDocument.body;
var data = $(iframeBody).find("#imageDirectory");
alert("data: " + data);
});
Below is how the iframe is defined
<iframe id="image_upload_frame" name="image_upload_frame"></iframe>
and I am echoing out a hidden input field in the php script that's within the iframe.
echo '<input type="hidden" id="imageDirectory" value="'.$imageDirectory.'" />';
The echo is definetly working as when I see view the iframe source I can see the hidden input however, the alert dialog is never shown as if something isn't working. There are no errors being reported either by the google chrome dev console.
If I understand correctly - you need a value from the iframe in the parent window, once the value is loaded into the iframe. I would add javascript to the iframe calling the parent and executing a function.
In the main frame:
function incomingValue(val) {
alert(val)
}
and somewhere in the generated iframe:
<script type="text/javascript">
parent.incomingValue("Hello world");
</script>
This should work assuming both frame sources share the same domain.
You can use postMessage for cross document communication between an iframe and it's parent.
See:
http://viget.com/extend/using-javascript-postmessage-to-talk-to-iframes
http://javascript.info/tutorial/cross-window-messaging-with-postmessage
Since you're running on the same domain, your main page's Javascript will have no trouble to access the contents of the <iframe> (example uses jQuery, you could rewrite into whatever libs you plan to use):
$('iframe#the-id-of-the-iframe').on('load', function() {
var iframeWin = this.contentWindow;
var iframeBody = this.contentDocument.body;
// access global JS vars defined in the iframe:
var someIframeVariable = iframeWin.globalIframeVariable;
// or, directly access elements in the iframe:
var someIframeElement = $(iframeBody).find('#element-id-inside-iframe');
});
A while ago I wrote a piece of code to upload a picture using some javascript and two iframes. The most important thing for me was to preview the pic. Maybe it will help you:
HTML:
<div id='fakebutton' onclick='select_pic()'>Just a button to select a pic</div>
<iframe src='uploadform.php' name'pic_frame'></iframe>
<iframe src='#' name='target_frame'></iframe>
both the iframes are hidden. The targetframe has no source (or an empty page, if you want to).
uploadform.php contains a form:
<form id='upload_form' action='dosomething.php' method='post' enctype='multipart/form-data' target='target_frame' onsubmit=''>
<input id='realfoto' name='realfoto' type='file' onchange='parent.foto_upload(window.frameElement.id)'>
</form>
and then some javascript:
First of all something to trigger the filebrowser when the user clicks the fake
function select_pic(){
b=window.frames['pic_frame'];
b.document.upload_form.realfoto.click();
}
And then a part to actually upload the pic, triggered by the onchange() in the input element:
function foto_upload(o){
var b=o;
o=getElementById(o);
if(o.contentDocument ) {o = o.contentDocument;}
else if(o.contentWindow ){o = o.contentWindow;}
else{return false;}
if(test_pic(o,b)){ //test if it is really a pic
getObj('foto_tmpdir').value=o.getElementById('tmp_dir').value;
o.getElementById('doctype_nr').value=b;
o.fotoform.submit();
}
else{
return false;}
}
In dosomething.php I perform actions on the uploaded pic (rename, resize etc). And it contains a few lines of javascript:
$a = 'upload was succes';
$b = 'my_image_name';
$c = 'whatever you want to put here';
?>
<script type="text/javascript">
window.top.window.smurf(<?php echo "'$a','$b','$c'" ?>);</script>
<?php
if you create in javascripty a function named smurf(a,b,c) you can pass along whatever you want form the php-script. One of the most important things for me was that I now can pass the filename of the uploaded pic to javascript, and use it to change an image.src for a preview.
Hope you can use something of it.
Your iframe source page should has a javascript call function instead of the hidden field. The function will call the opener window (your main page) and then it do any functionality you want. As blue print look at the following:
//in iframe src.php
<?php
if ($something){
?>
<script>
function doSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doSomethingWithOpenerWindow()
</script>
<?php
}
else{
?>
<script>
function doAnotherSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doAnotherSomethingWithOpenerWindow()
</script>
<?php
}
?>
In my website I set some values to session object like "user_status", "user_name" and like so. The php file looks like this:
<script type="text/javascript">
var logged = <? echo $this->session->getValueOf("user_status"); ?>;
</script>
<a class="show_message" href="#">SHow my status</a>
Well, I have a js script that pretends do an action according to user status in the website, so, I have this:
$('.show_status').click(function(event){
//ask for user status
if (logged){
//do something
}
else{
//do another action for visitors
}
});
Walking around I thought if it is the best way flow data between session -> javascript, because if you inspect the page source at browser the value of user_status will be visible and could be riskable for website security.
Thanks in advance
EDIT:
logged var only takes a boolean value.
The js action must be executed each time the element #(".show_status") is clicked.
If the JavaScript is just being used for interface stuff, and doesn't have any back end effects, I probably wouldn't worry too much about the insecurity of handling that logic client-side.
If security is an important thing though, I would recommend you use PHP to write the appropriate JavaScript function. For example:
On the page being viewed, perhaps in the header, you have:
<script type="text/javascript">
<?php
if ($this->session->getValueOf("user_status")) {
require_once('logged_in_user_functions.js');
} else {
require_once('visitor_functions.js');
}
?>
</script>
In the file `logged_in_user_functions.js' you have:
function showComment(id) {
//logic that shows the comment here
}
function showCommentSubmissionForm() {
//logic that adds this form to the page goes here
}
Meanwhile, in the file `visitor_functions.js' you have:
function showComment(id) {
//logic that shows the comment in a different way goes here
}
function showCommentSubmissionForm() {
//logic to display a message saying the user needs to log in to post a comment goes here
}
Then you can add your logic into your page without having to check the user status. The proper behaviour is provided by virtue of which .js file was included:
<button id='add_comment_button' onclick='showCommentSubmissionForm()'>Add Comment</button>
This gives PHP (and thus the server, not the client) final say in what gets displayed to the user.
Assuming that user_status will be something like Active, then this isn't really a security risk.
If you want to hide everything from casualy prying eyes, you could try using an encrypted cookie, using something like How to save encrypted data in cookie (using php)? to encrypt your values.
Hi I'm trying to create a form that is pre-populated partially by form on the page before. This information is then posted to this new page which is then populated into the form on that page ready to be submitted to a database.
I'm not a developer so I'm a little out of my depth here but this is what I've got so far..
<?php
$amount = $_GET['text-386'];
$covermultiple = $_GET['radio-30'];
$coverdobd = $_GET['d-o-b-d'];
$coverdobm = $_GET['d-o-b-m'];
$coverdoby = $_GET['d-o-b-y'];
?>
<script type="text/javascript">
document.getElementById('text-386').value = "<?=$amount ?>";
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = "<?=$coverdobd ?>";
document.getElementById('d-o-b-m').value = "<?=$coverdobm ?>";
document.getElementById('d-o-b-y').value = "<?=$coverdoby ?>";
</script>
I'm getting the values out of the URL ok and can echo these out on the page fine, I've even managed to get text-386 appearing in the right place.. so thats one down! The problem is the other elements are a radio button with two options (radio-30) and a 3 select boxes with the days, months and year of a persons d-o-b. These two bits are populating.
So in a nutshell..
How can I use javascript (if that is the right way) alongside php to populate the radio and select tags on this form using information in the url? In a preferably straight forward way as possible?
The url if it helps is..
http://localhost/datacapture/form-page/radio-30=Just+for+me&text-386=%C2%A340%2C000&d-o-b-d=11&d-o-b-m=05&d-o-b-y=1977
Thats obviously on the local build I'm using so that URL wouldn't work for you. I can see when googling lots of help posting information using radio/select etc but I want the opposite, how do you populate these from a url?
Any help would be a lifesaver
I would just use an if statement.
if( $covermultiple == "Just for me" ) {
// Echo the field here
echo "<input type='radio' name='radio-30' value='Just for me' checked />";
}
else {
// Check for the next case
}
Put this block right where you want the radio buttons to be.
I think something like that will work fine. I don't think you really need javascript in this case unless you really want to use it.
Im not 100% I have an answer, but I cant find comment anywhere so I will joust post here.
You cant access PHP variables from Javascript. PHP is running on the server, and Javascript is inside users browser.
Javascript cant get $_GET and $_POST variables like PHP.
Now what you can do is this, with JavaScript you can get document.location string that holds your current URL. And you can brake that URL into parts. To do that use this function:
<script>
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
alert($_GET['someVar']); // This will alert content of someVar
Now you can use $_GET['vars'] to get your URL vars.
And then you dont use PHP to echo variable content, you joust prepare your URL so it holds variables you want to insert into your form.
So you do something like this:
<script type="text/javascript">
document.getElementById('text-386').value = $_GET['urlVar'];
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = $_GET['urlVar'];
document.getElementById('d-o-b-m').value = $_GET['urlVar'];
document.getElementById('d-o-b-y').value = $_GET['urlVar'];
</script>
So as you can see, JavaScript takes variables from URL, using function $_GET you wrote and it dosent needs PHP. And you can use PHP to generate URLs you need, so they contain variables you can get using $_GET javascript function.
Hope this answers your question.