Confirming action before processing! - php

Am doing a contact management site in codeigniter, i have a function which delete the contact based on id.
For example the page will have all contacts listed. And each contact will have a link saying delete near it. The link will be to the function passing the id, like:
www.site.com/index.php/action/delete/23
So i want a confirmation box to ask user, yes or no for each link. So if user press yes it will be deleted and otherwise nothing happens. Hope I'm clear.

You need a javascipt prompt:
Your JS
function confirm_delete(){
var r=confirm("Are you sure?");
if (r==true){
//Do somthing
}else{
//cancel
}
}
Then add an onclick event to your link.
Delete
If you want something shiny and less intrusive may i suggest jquery with one of a multiple of confirm dialog plugins.
http://projectshadowlight.org/jquery-easy-confirm-dialog/
http://kailashnadh.name/code/jqdialog/

You could have a confirmation page with a form to post back to the same url. In the controller check whether the form has been submitted. If it has, delete the contact. If not, display the confirmation page.
function delete($id)
{
if ($this->input->post('confirm'))
{
$this->contact_model->delete($id);
}
else
{
$contact = $this->contact_model->get_contact($id);
$this->load->view('delete_confirm', array('contact' => $contact));
}
}
If you don't like the idea of an extra page you could use some javascript to display a confirmation box and do an AJAX post if the user confirms.
Edit :
Just as an aside, what I'd avoid doing is implementing the delete through a HTTP GET. A spider or bot following the delete links could inadvertently delete all the contacts. Its better to use HTTP POST.

Related

Joomla 2.5 modal popup component form

I'm trying to modify a Joomla component to achieve some ajax functionality to make things a little bit more streamlined for my website users. I've changed the information below to keep the project a little anonymous because I'm paranoid :-)
What I want to achieve is simple in my head:
-> User lands on 'order' page in xyz component
-> If there are no delivery addresses for this user on the order page, give a link to create one
-> When user clicks 'Add an address' a modal window appears and does an ajax request to the 'addaddress' page which has the form to add an address
-> Modal does not display the full page, instead it only displays the form and the essential (required) form fields
-> User inputs address information and clicks button to submit the form.
-> The fields are validated then posted
-> The modal closes
-> The field which has the delivery addresses on the originating 'order' page is refreshed and now includes the new address. This should not refresh the entire page as the user might have put data into the other form elements. This is important.
OK, so now you know what I want to achieve, let me introduce you to what I currently have.
-> User lands on 'order' page in xyz component
-> If there are no delivery addresses for this user on the order page, give a link to create one
I have written a simple php if statement that creates an anchor link with the text 'Add an address' and id 'addNewAddress'
-> When user clicks 'Add an address' a modal window appears and does an ajax request to the 'addaddress' page which has the form to add an address
I am using a mootols plugin called SimpleModal from http://simplemodal.plasm.it
-> Modal does not display the full page, instead it only displays the form and the essential (required) form fields
I have extended the functionality of the modal to allow me to inject some mootools filtering because I only want to display the form, nothing else. I have added this as a new parameter called getSomething that I can inject if I need to.
//SIMPLEMODAL
$("addNewAddress").addEvent("click", function(){
var SM = new SimpleModal({"width":600});
SM.addButton("Action button", "btn primary", function(){
$('addressForm').submit();
this.hide();
});
SM.addButton("Cancel", "btn");
SM.show({
"model":"modal-ajax",
"title":"New address",
"param":{
"url":"index.php?option=com_address&modal=true",
"getSomething":"#addressForm",
"onRequestComplete": function(){}
}
});
});
And this is the function that it calls:
else if (param.getSomething.match(elid))
{
// Request HTML
this.request = new Request.HTML({
evalScripts:false,
url: param.url,
method: 'get',
onRequest: function(){},
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
var f = responseElements.filter(param.getSomething);
$('simple-modal').removeClass("loading");
$('simple-modal').getElement(".contents").adopt(f);
param.onRequestComplete();
// Execute script page loaded
eval(responseJavaScript)
// Resize
this._display();
// Add Esc Behaviour
this._addEscBehaviour();
}.bind(this),
onFailure: function(){
$('simple-modal').removeClass("loading");
$('simple-modal').getElement(".contents").set("html", "loading failed")
}
}).send();
}
*Now, everything up to this point I have managed to get working but I can't figure out the next part. *
-> User inputs address information and clicks button to submit the form.
At the end of the ajax request url, you might notice that I sent the modal=true request, this is so that I can hide certain elements on the form that I don't need to be displayed in the modal window - the form's own submit button is hidden when called from the modal.
-> The fields are validated then posted
If I call the 'addaddress' page without the modal, the form has it's own validation. Using the modal however, when I click submit, no validation happens and the address is added without any validation. I need to implement some validation to the fields using a standalone validation from within the modal itself.
-> The modal closes
At the moment, when the form is posted I get redirected to the 'viewaddresses' page but I'm confident I can fix this on my own. Instead I just want the modal to close.
-> The field which has the delivery addresses on the originating 'order' page is refreshed and now includes the new address. This should not refresh the entire page as the user might have put data into the other form elements. This is important.
This is self explanatory but I'm not sure where to even begin.
I think I've been as clear as I can be, but if you need anything else, please let me know.
I really appreciate any help you can provide.
What you are maybe missing is how to trigger a form submit.
You can submit a form with: $('myForm').fireEvent('submit');
So, using your example I changed the code of one of the modal buttons to:
SM.addButton("Submit button", "btn primary", function () {
$('addressForm').fireEvent('submit');
});
In the Mootools Form.Validator you can capture the formValidate event. Description:
formValidate - (function) callback to execute when the form validation completes; this function is passed three arguments: a boolean (true if the form passed validation); the form element; and the onsubmit event object if there was one (otherwise, passed undefined).
I'm not sure why the form is not submited when the submit is fired programatically, but anyway you can add a new .submit() inside this function that checks the validator boolean result.
So you can do like this:
new Form.Validator.Inline(myForm, {
onFormValidate: function (bool, element) {
if (bool) {
element.submit();
}
}
Demo here

verify entrance source in php

I have a link on the page that opens a contact form in a modal window.
How can I verify that the user clicked on the link to access the contact form, and did not go to the page directly. I don't want users or bots inadvertently browsing to that page.
Thanks in advance!
You can check for $_SERVER['X_HTTP_REQUESTED_WITH'] header, which will be xmlhttprequest whenever it's an ajax request
You can use the referral url (you can access this url in PHP using $_SERVER["HTTP_REFERER"]) but you can't rely on it. First because it can be changed using a very simple script and second because that field is not always filled.
Another method is to use session to store the last visited page and then check this in your contact page. Anyway this method will also fail if the user see another page before access to the contact form but the page which you want the users start with was already loaded.
You can send a variable with it like
Contact Me
and in the modal test weather it set or not
if(isset($_GET['co'])):
//show the form
else:
//redirect
endif;
or you can use jquery to select that link and sends a variable posted with it like
Contact Me
$('.contact').click(function(){
$.post( 'contact.php', { direct: 'no'},function()
{
//call modal from here
}
);
});
then test if direct = no
if($_POST['direct'] == 'no'):
//show the form
else:
//redirect
endif;
and the jquery solution is more reliable
Sorry I was wrong
Have a form with a hidden field that contains a token, and validate that token with the session on postback.

help with javascript confirmation dialog

So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.

php navigation validation

How to check if the user has entered the page by clicking on the button and not from copy pasting the URL ?
For example, if a user has clicked on Register I want him/her to go to that page only by clicking the Register button and not by copy pasting the link.
Also, is it a good practice to give the page name on the address bar or should I have to hide the page. If I am hiding the page will I be able to do that ?
For example, if localhost/projname/register.php. I don't want people to see the register or login or about or anything on the address bar except localhost/projname.
Maybe check if he used $_POST, something like:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
// do ya thing
}
else
{
?>
<form action="index.php" method="post">
are you sure? <input type="submit" value="yes">
</form>
<?php
}
?>
You can use the HTTP_REFERER data of the $_SERVER reserved variable to see where did the user come from.
if(empty($_SERVER['HTTP_REFERER'])) {
// if we are here, the user copy pasted the url.
}
As for your second question, you can't totally "hide the page" like you're suggesting. The web server must know which page to show, so the browser must know has well.
You can however obfuscate the page name. For example you can call the page "sfhjgdjkfg" so the user won't be able to know that this is the "registering" page. But I think it's really a bad idea, why in the first place want you to hide this ?
One method is to use $_SERVER['HTTP_REFERER'] to verify that they clicked a link from your site, but this method isn't fool-proof as many Firewall and Anti-virus suites will remove the Referrer information.
A better method would be to generate a temporary session token on the pages of your site, and check for that token when the Register page is opened.
If your form uses POST parameters, the browser will pass on some POST data. You could then check
if (empty($_POST)) {
//didn't click the button, just went straight to the url
}else{
//did click the button
}

Zend Framework - using jquery dialog for popup form in a Zend controller/action

I am editing to try to put my primary question at the beginning of this post:
1) I am sitting at my customers/preferences page updating info in the form
2) I want to add a widget to my list of available widgets, so I need to open the widgets/addWidget page/form to add a new widget (note I am still working in my current customers/preferences page/form, so I need to continue with this page after adding a new widget in the widgets/addWidget page/form.
3) I select a link to go to widgets/addWidget, and I have jQuery dialog open this link in a dialog with the addWidget form and submit button
4) after adding a newWidget in the dialog popup form, I want to submit the newWidget (the code for addWidget is in the widgets/addWidget controller/action, not in the customers/preferences action)
Problem: the addWidget form action goes to widgets/addWidget, so when I submit the addWidget form in the dialog, it takes me away from my current customers/preferences page
Question 1) what is the proper/best way given this scenario to popup a form in another controller/action to submit that form, but then resume my current controller/action?
Question 2) should I move all of my form and code from the widgets/addWidget controller action into my existing customers/preferences action? (that seems to be the wrong approach)
I have researched jQuery documentation, Zend documentation, and searched other threads with trusty Google and stackoverflow, but I am still struggling to figure out the right way to get this to work with Zend Framework and popup forms such as jQuery dialog.
I have a working Zend action/controller that using a Zend Form and view to display and process my form. I have also been able to use jQuery dialog to popup a window when I click the link to that controller/action.
My issue is with the proper way to get the dialog to display the form and still be able to submit and process the page. If I only load the #content tag in the dialog the form and submit button appear in the dialog box, but the submit button no longer works. If I let the dialog open the full page (not just the #content) now the form will process properly, but the form submit is set to go to my action page for processing, so the form submits and takes me away from the original page and to the real controller/action page instead.
In my customerController I have a preferencesAction where a customer can choose a widget from a list of widgets. When the customer needs to add a new widget to the list, I want to open the addWidgetAction from the WidgetsController in a popup form. I want to add the widget in the popup form, submit the form to the addWidgetAction, and come back to the customer/preferences page I was already working in (with the newly added widget available in my list to select from).
//CustomerController
public function preferencesAction(){
//this is where I click a link to /widgets/addWidget and use jQuery dialog for form
}
//Customer preferences.phtml
<script>
$(document).ready(function() {
$('#add-link').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
autoOpen: false,
title: $link.attr('title'),
width: 600,
height: 500,
buttons: {
"Add Widget": function(){
$("#AddWidget").submit();
},
"Cancel": function(){
$(this).dialog("close");
}
}
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
});
});
</script>
<a id="add-link" href='<?php echo $this->url(array('controller' => 'widgets',
'action' => 'addwidget')); ?>'>Add a Widget...</a>
//WidgetsController
public function addWidgetAction(){
// display form to add widget
// process form, validate, add to widgets table
$baseUrl = $this->getRequest()->getBasePath();
$action = $baseUrl . '/widgets/addWidget';
$form = new Form_Widget();
$form->setName('Add Widge')
->setAction($action);
}
I need to understand how to get the dialog to load my Zend action page for form processing, but without requiring the entire layout with header, footer, etc. I also need to understand how to process the form in the dialog popup without moving away from my original page where the popup was linked from.
Thank you for your assistance!
Well, I am not sure if i understand your question but you can try this
You can load your form in UI dialog box, to disable layout do this on you can do this
public function addwidgetAction(){
$this->_helper->layout()->disableLayout();
//just diable layout and do eveything normal
}
on your preferences.phtml file load the content of url baseurl/contrller/addwidget to jquery modal dialog
UPDATE
One way is use a jqueryplugin fancybox (external src) check the forgot password link
The other way is to use ajax
UPDATE
Well now i read your question well, though don't understand so clearly, i understand that you are trying to do something that is quite ambitious. And you cannot achieve through normal load method. You need to use ajax
I have to admit that I don't like jquery ui modal dialog so i don't know much about it, and i usually use jquery fancy box where it would give me an ability to load external page. Maybe you can do this through jquery ui modal dialog box.
I guess the problem that you are facing right now is you open a dialog box, you get the form in dialog, and you submit the form, it sends the normal post request, so dialog is reloaded, that's what happens in the link i have above, just click on forgot password link
Well there's solution for that too, the solution is ajax, and i hope you are quite familiar with it. you send ajax request and get response back, and depending on your response, you can exit dialog box as well update the the parent (preferences controller page) but that is quite ..... I tried to so same with few months back, but not with zf, i don't know how much i accomplished but it sure gave me a nasty headache

Categories