how do I overcome nesting in functions? - javascript

I'm pretty new to javascript and jquery, and have run into a problem that I have not yet found a solution for. I'll attempt to paint it in a fairly simple way.
I have a page that offers the user a few choices (its a game, so..) like attack or defend, what weapon to use. It then loads two html 's, each with a "commit" button. The commit buttons are tied to (separate) functions that pass data to ajax.
The problem I have is that I'm getting buried in nested functions. Does that make sense? My code looks something like this:
code:
$(function() {
$('#choice1').click(function() {
//do some stuff
});
$('#choice2').click(function() {
//do some stuff
});
$('#choice3').click(function() {
//do some stuff, including creating the choices below, and their submit boxes
$('#subChoice1').click(function() {
//send data with ajax to a php document. get result
//create some text on my document to display results
//create an input button, along with an id="subButton1"
});
$('#subChoice2').click(function() {
//send data with ajax to a php document. get result
//create some text on my document to display results
//create an input button, along with id="subButton1"
//(yes, feed both back to same func)
});
}); // end choice3
$('#subButton1').click(function() {
//my buttons in the subChoices do not call this function(!!??)
});
});
edit: link no longer works, sorry. And I've created a living example here.
Thanks for any tips or pointers. I'm almost certain that there is just something simple that I'm missing or unaware of that will get me on the right track.

You could always use normal named functions instead of inline anonymous ones. That might help if the mountain of functions is getting too tall.
Update:
Here's your working Case 1:
$('#button1').click(function(){
$('#div1').append('<span id="span1"><br>Alright. Button 1 worked. Here\'s another button.</br></span>');
$('#div1').append('<input type="button" value = "Button 2" id="button2"/>')
$('#button2').click(function() {
$('#div1').append('<span id="span1"><br>Hey! Button 2 worked!. Let\'s keep going.</br></span>');
$('#div1').append('<input type="button" value = "Button 3" id="button3"/>')
$('#button3').click(function() {
$('#div1').append('<span id="span1"><br>Hey! Button 3 worked!. That\'s probably enough.</br></span>');
});
});
});
What I'm proposing is to update it like this:
function button3_click() {
$('#div1').append('<span id="span1"><br>Hey! Button 3 worked!. That\'s probably enough.</br></span>');
}
function button2_click() {
$('#div1').append('<span id="span1"><br>Hey! Button 2 worked!. Let\'s keep going.</br></span>');
$('#div1').append('<input type="button" value = "Button 3" id="button3"/>');
$('#button3').click(button3_click);
}
function button1_click() {
$('#div1').append('<span id="span1"><br>Alright. Button 1 worked. Here\'s another button.</br></span>');
$('#div1').append('<input type="button" value = "Button 2" id="button2"/>')
$('#button2').click(button2_click);
}
$('#button1').click(button1_click);
That way the structure of the logic stays the same, but you can pull out the nested function definitions.

If you're consistently reusing classes or ids for the submit buttons you can leverage jQuery's live() method. It would allow you to create the bindings for $('#subChoice1') and $('#subChoice2') outside of the click handler for the parent choice, but still have them bind up properly when they're created.

Related

Sitecore 8 Speak UI - Call Pagecode Javascript from HTMLTemplate link

I am working on ListControl and one of the columns has Delete link which I am formatting using HTMLTemplate as follows:
<a href="javascript: app.showConfirmation()" >Delete</a>
My Javascript looks as follows:
define(["sitecore", function (Sitecore) {
var DestinationRules = Sitecore.Definitions.App.extend({
initialized: function () {
this.processDestinationRules();
},
showConfirmation: function () {
alert('here');
},
});
return DestinationRules;
});
For some reason, I am not able to call showConfirmation(). It says is undefined. I even tried Sitecore.Speak.app.showconfirmation() but not working.
I tried my best to search online but not able to find much help around calling function through controls embedded inside HTMLTemplate.
My next step is to call DialogWindow.
Please if you can help me with the syntax of the above. Thanks in advance.
Fixed it in a different way.
I wanted to show in-line Delete button in each row of the Listcontrol. Could not figure out way to call the
javascript: app.showConfirmation()
I changed the way to delete the record:
Have one Delete button outside the ListControl.
Enable/Disable the Delete button based on binding ListControl.HasSelectedItem.
On click of the Delete button, call showConfirmation()
As of now seems to be a better way. Sitecore itself uses similar approach for "Kicking off" users. Can be found here:
/sitecore/client/Applications/LicenseOptions/KickUser
Hope that helps. Thanks.
Finally, managed to do this. Always knew that it can be done this way but did not like the way its done.
The Delete link in List control opens up a confirmation Dialogue window. And if user selects Yes then it calls the app.onDeleteYes()
The HtmlMarkup for the column:
Delete
Added a button called btnDelete with visibility set to false.
Added following function, outside the scope of App:
var destinationRulePage = (function () {
var self = this;
self.showDeleteDialog = function (id) {
$("button[data-sc-id='btnYes']").attr("data-sc-click",
"javascript:app.onDeleteYes(" + id + ");");
$("button[data-sc-id='btnDelete']").click();
}
return self;
}())
This does the job for me. Thanks.

why do my onClick functions take two clicks

I've noticed from a few different projects of mine that whenever I click something I add an onClick function to, it always takes two clicks to get them going when a page is freshly loaded. The general structure I use for them is:
function PageChange(){
var welc_p = document.getElementById("welcome");/**gathers page DIVs**/
var page01 = document.getElementById("page01");
var page02 = document.getElementById("page02");
var start = document.getElementById("start_btn");/**gathers buttons**/
var p1_back = document.getElementById("p1_back");
var p1_next = document.getElementById("p1_back");
var p2_back = document.getElementById("p2_back");
var p2_next = document.getElementById("p2_back");
start.onclick=function(){
page01.style.display="block";
welc_p.style.display="none";
window.location="#page01";
};
}/**function**/
then the way I call it in the html is
<div class="some_class" id="start_btn" onClick="PageChange()">!!!LETS GET STARTED!!!</div>
Here's a fiddle of it as well.
https://jsfiddle.net/Optiq/42e3juta/
this is generally how I structure it each time I want to create this functionality. I've seen tons of other posts on here about their items taking 2 clicks to activate but none of them were doing anything near what I was trying to accomplish and it seemed their problem was within their coding. Does anybody know why this is happening?
This is because you are attatching a event handler to your button on click of your button.
This means that one click of the button activates the event handler, not the code within start.onclick=function() {
Then, the second click works becasue the event handler has been activated, and now the code will run.
Try moving your code out of the function, then it will work with just one click
Just had the same issue, and found an easy solution based on the above answer.
Since your function needs two clicks to work, I just called the function above the function and it works fine. This way the function already gets called one time on load, then it gets called the second time when you click it.
yourFunction();
function yourFunction(){
-- content --
}
I also had the same 2 clicks required on intitial interaction and after many searches couldn't find the best solution for my specific nav menu. I tried this solution above but couldn't get it to work.
Stumbled upon this code from a youtube example and it solved my issue. I wanted to nest submenu's for multiple levels and modified it from its original implementation to work best for my responsive mobile menu.
var a;
function toggleFirstLevelMobileSubMenu(){
if(a==1){
document.getElementById("mobile-sub-menu-depth-1").style.display="none";
return a=0;
}
else {
document.getElementById("mobile-sub-menu-depth-1").style.display="flex";
return a=1;
}
}
var b;
function toggleSecondLevelMobileSubMenu(){
if(b==1){
document.getElementById("mobile-sub-menu-depth-2").style.display="none";
return b=0;
}
else {
document.getElementById("mobile-sub-menu-depth-2").style.display="flex";
return b=1;
}
}
Of course, in the CSS I had display: none set for both ID's.
First, the problem:- On first click instead of running js your browser runs the button aka the event.
Solution:- in order to resolve this we need to make sure our function is already before the event is run (this is one of the ways to solve the problem). To achive this we need to load the function aka call the function in some way.
So, i just simply called the function after function is completed.
Code answer-
Just add at the end of your code
PageChange();

How to make a Javascript Link activate an Existing Contact form on the site?

I dont know if this will make sense, but I have this site: http://commentgreendrycleaning.com/, the site has a contact form, but its all javascript activated.
when you go to the site, If you choose 3 stars you will see the contact form. If you choose 5 stars, it will go to another page, with logos. Under those logos it says "If you dont have an please give us feedback here". So my goal is to make the word "here", link to the contact form. But its all javascript, so I dont know how to do that?
Basically make it link to the contact page or activate...?
Thanks
I find that when a link's href is "javascript:void()", the original coder wired up a click event handler to perform the desired function. That is what has happened here.
The anchor with the id "tellCo" (The "Tell us about it" link") has a click event setup in the window load() function in common.js. The code that sets up the link's click event is on approximately line 265. See the code snippet cut from your code below:
//screen 1 new : start
$('#tellCo').click(function() {
$('.bad-exp').addClass('fadeOutLeft').fadeOut(1000);
$('#badContent').addClass('fadeOutRight').fadeOut(1000);
setTimeout(function() {
$('.s4').fadeIn(1000).addClass('fadeInRight');
}, 500);
setTimeout(function() {
$('.s4').removeClass('animated fadeInRight');
// $('.help-con').remove();
$('.help-btn').removeClass('active');
}, 2000);
});
//end
The simplest solution would to just call the click event on the link, such as:
$('#tellCo').click();
But... personally, I would extract the inline function out of the event binding and place it into a separate function that could be called independently and be a little more maintainable (IMHO), such as:
function tellMeAboutIt() {
$('.bad-exp').addClass('fadeOutLeft').fadeOut(1000);
$('#badContent').addClass('fadeOutRight').fadeOut(1000);
setTimeout(function() {
$('.s4').fadeIn(1000).addClass('fadeInRight');
}, 500);
setTimeout(function() {
$('.s4').removeClass('animated fadeInRight');
// $('.help-con').remove();
$('.help-btn').removeClass('active');
}, 2000);
}
Then replace the original click event setup with:
$('#tellCo').click(function() { tellMeAboutIt(); });
This way you can call tellMeAboutIt() whereever and whenever you like.
So, for the simpler solution, add this to the window.load() function:
$('#yourNewLink').click(function() { $('#tellCo').click(); });
'yourNewLink' is whatever the 'id' property is of the new link you are creating. the new link would look something like this:
<a href='javascript:void()' id='yourNewLink'>here</a>
Remember the javascript creates the click event, so the HTML is very basic.

Return value from custom alert [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create TRULY modal alerts/confirms in Javascript?
TL;DR: I've overridden the default alert() function with a custom HTML based one. I want the new dialogue to still block execution, and get the buttons within my dialogue to return true or false from the call to alert() to use in logic (and continue execution).
I'm trying to implement a custom alert box, which replaces the default browser alert with a nicely themed box with the same (or similar) functionality.
I've read this question, and I'm using the solution given in this answer (to the same question). What I want to do now is get my overridden alert to return a true or false value for use in if() statements, depending on whether OK or Cancel was clicked:
if(alert('Confirm?') {
// Do stuff
}
However, due to having custom HTML instead of a normal alert I can't do this for two reasons:
I can't return a value from the buttons in the replacement dialogue (click events bound with $.on()) because I have no idea how to.
I can't block program flow with this alert, as far as I know.
I've bound $.on() events to the Cancel and OK buttons in the replacement dialogue which hide the box. These work fine, but the problem I have now is returning a value when a button is clicked, so that execution will halt until an action is taken by the user.
HTML:
<div class="alert background"></div>
<div class="alert box">
<div class="message"></div>
<hr>
<div class="buttons">
<input type="button" name="cancel" value="Cancel">
<input type="button" name="confirm" value="OK">
</div>
</div>
Current JavaScript: (pretty much a carbon copy of the answer in my linked question)
(function () {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
(function (proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null' : arguments[0];
var type = (!arguments[1]) ? '' : arguments[1];
if (type && type == 'native') {
nalert(message);
} else {
// Custom alert box code
console.log(message);
}
};
})(this);
Ideally, I want to be able to put something like this in the // Custom alert box code part:
$('.alert.box input[name="confirm"]').on('click', function() {
// Hide dialogue box - I can do this already
// *** Return `true` or other truthy value from
// alert for use in `if()` statements
});
So that when the OK or Cancel button is clicked, it removes the custom alert box and returns a true or false value from the call to alert(). I can already remove the alert with $.fadeOut() and $.remove(), that's easy. What isn't is knowing how to get the button click events to get alert() (overridden) to return something.
I've tried to be as clear as I can, but I may have missed something out. Please let me know if I have.
The example below shows an approach to creating a custom alert and handling the outcome of the user selection
/*
message = String describing the alert
successCallBack = callback function for when the user selects yes
*/
function exampleAlert(message, successCallback)
{
/*Alert box object*/
var alertBox = document.createElement("div");
/*Alert message*/
var msg = document.createElement("div");
msg.innerHTML = message;
/*Yes and no buttons
The buttons in this example have been defined as div containers to accentuate the customisability expected by the thread starter*/
var btnYes = document.createElement("div");
btnYes.innerHTML= "Yes";
/*Both yes and no buttons should destroy the alert box by default, however the yes button will additionally call the successCallback function*/
btnYes.onclick = function(){ $(this.parentNode).remove();successCallback();}
var btnNo = document.createElement("div");
btnNo.innerHTML= "No"
btnNo.onclick = function(){ $(this.parentNode).remove();}
/*Append alert box to the current document body*/
$(alertBox).append(msg, btnYes, btnNo).appendTo("body");
}
function test()
{
alert("Example alert is working, don't use this test as a replacement test - horrible recursion!")
}
exampleAlert("shoe", test)
This is fairly basic and doesn't allow for additional data to be supplied to the callback function and for that reason is not ideal for production however jQuery's .bind() and similar methods allow for data to be associated with the callback method
It's worth commenting that while the above demonstrates a full implementation of the problem, there are in fact only two lines that actually matter.
btnYes.onclick...
btnNo.onclick...
Since we're achieving the desired result by binding onclick events for true and false respectively, everything else is there to paint the picture.
With that in mind it is possible to effectively turn any container object with at least one sibling into an alert box for eaxmple:
<!-- Example html -->
<div id='a'>
<ul>
<ul>
<li>Something</li>
<li>Something Else</li>
<li id='yesIdentifier'>Something not necessarily suggesting a trigger?</li>
</ul>
</ul>
</div>
As long as your yes / no (if no exists) options destroy the appropriate container a converting a container into an alert box can be handled in a couple of lines of code.
$('#yesIdentifier', '#a').click(
function(){ someCallback(); $(this).closest('#a').remove()});
Neither of the above are exemplary models for implementation but should provide some ideas on how to go about the task.
Finally... do you really need to replace the native alert method? That is, either you're writing the alert calls, in which case you'd know to use your custom method, or you're overwriting default behaviour that you can't guarantee the other developers will be aware of.
Overall recommendation:
I feel the best approach to this would be to create a jQuery plugin which creates the custom alerts on the fly and track callbacks, results and what not within the plugin.
SOliver.
Why don't you just use a confirm box like so.
var c = confirm('Confirm?');
if(c)
{
// Yes clicked
}
else
{
// No clicked
}
Or you could use jQuery UI's dialog confirmation box.
http://jqueryui.com/demos/dialog/#modal-confirmation

jQuery Modal Confirmation Dialog Not Submitting Form

I am trying to pop up a confirmation modal when the user presses the delete button on the edit form. The modal pops up fine, but when jQuery should be submitting the form, it's not doing anything. I have delete as a type="button", because when it is of type submit the modal function does not hold up the process and it just deletes the user right away.
The HTML ...
-- EDIT --
(I added the <form> tags)
<form action="/admin/edit-user" enctype="application/x-www-form-urlencoded" method="post" name="edit_user_form" id="edit_user_form">
...
<p><input type="submit" value="Save" name="submit" id="submit"/></p>
<p><input type="submit" value="Cancel" name="cancel" id="cancel"/></p>
<p><input type="button" value="Delete User" name="delete_btn" id="delete_btn" onclick="confirmDeleteUser();"/></p>
...
</form>
...
<div id="dialog-modal" title="Confirm Delete User">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Are you sure you wish to delete this user?</p>
<p>To continue editing, click cancel.</p>
</div>
The Javascript:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
When I inspect the source, I'm seeing that the code is properly appending the new hidden element, but the submit just doesn't seem to want to fire. What step am I missing?
Try it a different way.
HTML
Your html has the following: onclick="confirmDeleteUser();"
Why? jQuery is supposed to make this easier for you, not harder.
Your HTML should be pure and not calling functions (with the exception of ultra-extreme circumstances you are very unlikely to encounter). Why not use the jQuery library to bind the event to the element, rather than mix javascript function calls into your HTML? You should be doing something like this in the <script> tags, after a document ready statement.
$("#delete_btn").click(function(e){
/*Code that runs on click of the "delete_btn" ID tag*/
});
If you're unfamiliar with jQuery selectors and events then start reading here.
You can find all the events here.
You can find all the selectors here
The other reason you should do this is in the event the document isn't correctly/fully loaded in order to prevent it from breaking on your users.
CSS
You've also done this: style="float:left; margin:0 7px 0 0;" in an HTML tag? That's evil, dude. Just evil. How am I going to maintain this code in five months?
Instead, use CSS.
In your tags, or CSS file, you need an entry such as:
.dialogAdjust {
float: left;
margin: 0 7px 0 0;
}
Then in your HTML you would say:
<span class="ui-icon ui-icon-alert dialogAdjust"></span>
And now you can tweak the thing to your heart's content. It's better if you can make the class on the dialog div, rather than individual HTML elements, and in this case you absolutely can.
JavaScript
Hokay, so, here's your function:
function confirmDeleteUser()
{
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
$('#dialog-modal').dialog('open');
}
What's going on here? First step, you should try and use a tool to measure code quality. Two popular ones are JSHint and JSLint. You don't need to follow things they say like it's the only way to write your code, but it's immensely helpful in finding bugs due to small mistakes. I like JSHint, so we're going to run it through that.
And here's the output:
Errors:
Line 17 tmpElm = $('<input type="hidden" />');
'tmpElm' is not defined.
Line 18 tmpElm.attr('name', 'delete');
'tmpElm' is not defined.
Line 19 tmpElm.attr('id', 'delete');
'tmpElm' is not defined.
Line 20 tmpElm.val(true);
'tmpElm' is not defined.
Line 21 tmpElm.appendTo(form);
'tmpElm' is not defined.
Oops. Looks like you've got an undefined variable in there, meaning it's now global. Global variables are bad, they break scope and can make your code function in strange ways.
We need to fix that. You should always declare local variables in local scope. That means putting a var tempElm; at the top of the "Delete User" function.
Do away with that function wrapper, you won't need it. Your code should create the dialog object and code when the document is done loading, and open the dialog when it's clicked. What is happening in your original code both creating the dialog and opening it every time you click that button. What's the problem with that? You keep creating the object, even though it's created. You're creating the same object again and again and again. In this implementation, you won't notice it, but your design will carry over to places it will unless you take notice of this now.
So, what does that look like? In your <head> tag you should see something like this:
<script>
/*
This makes all the code inside
run when the window is done loading,
not before, which may cause issues.
*/
$(window).load(function(){
/*
This sets up the dialog
as you've described before
*/
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
//We've added the var infront of tepElem
var tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
}
});
/*
This is the part where I talked
about selectors and events in the HTML
*/
$("#delete_btn").click(function(e){
$('#dialog-modal').dialog('open');
});
});
</script>
When asking for help, use a tool like jsFiddle to post JavaScript in to make it easier for other people to help you.
Here's a jsFiddle of the revisions we've made so far. Spend a bit of time learning how to use it if you're doing a lot of work in JavaScript and want to test something really quickly.
Here's why I wanted you to learn jsFiddle:
You didn't give us enough code to work with successfully, thus leading to me writing this huge post about code quality and how to ask questions, doubly so when you post a bounty.
If you want help, don't make people work really hard for it. You won't get good help unless someone is totally insane.
jsFiddle requires you post actual working code (or non-working code) that lets us see if there's a problem with form.submit(), such as any strange attributes or properties on the form element, or any number of other issues that could be kicking around that you excluded.
So let's look at what's breaking your "Delete User" function.
function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.prop('name', 'delete');
tmpElm.prop('id', 'delete');
tmpElm.val(true);
tmpElm.appendTo(form);
form.submit();
return true;
}
Why have you declared self? You never use it once. Lets get rid of that.
You could use something called chaining, it's really up to you. Some people hate it.
You append a whole new input to the form for something that looks like a choice, I'm not sure this is wise. I'd suggest changing the value of a normal input, or using another pattern, this could lead to a lot of issues, but for the sake of the question I'll imagine it's done for all the right reasons. Be careful however, if someone double clicks submit, that input's in there two times.
form is a word reserved by used in the DOM, you should avoid using that one to avoid confusion between your variable and the DOM API.
Which form submission button are we clicking here? You have a lot, and jQuery isn't going to guess and hope for the best.
How forms should look:
The w3 explains what forms are and the purpose of things.
Key points:
Names are paired with values
The submit button clicked is sent, the submit buttons not clicked are not.
The DOM is can be navigated based on NAME and ID attributes
Something weird is going on in your form.
Here's a form that javascript understands how to submit:
http://jsfiddle.net/YS8uW/2/
Here's javascript attempting to submit your form (stripped down to bare-bones):
http://jsfiddle.net/LfDXh/
What's different here?
You have IDs all over the place.
You use keywords for names
Lets look at something you've done, given an ID of submit to something:
http://jsfiddle.net/fdLfC/
And what happens when we don't use that as an ID?
http://jsfiddle.net/fdLfC/1/
Ahh. So that's weird.
It's like giving it an id of submit won't let you call submit. A proper explanation is, you've re-written it because the dom did it when you assigned that ID and Name, it's trying to call the element.
You can see this if you open up a debugger or something, it gives you an alert to the effect of:
TypeError: Property 'submit' of object # is not a function
Keep away from using keywords to mean something else and you won't fall into these weird traps.
A big thank you to #MattMcDonald for linking me to this resource, which explains how to deal with, and why, NAME and ID attributes over-write the built-in HTML DOM methods.
Do the other stuff I said too. Disclaimer: Everyone's going to wage war on me saying it's not absolute that you should be doing all those things, I agree, but I think this post is long enough, and we'll all agree that doing these things is a step forward in code quality, not backwards. It's up to you at the end, but try avoiding mixing things together into a huge messy pot. Think about the execution of your code and how it's happening also.
If you are sure it appends the hidden input, then the problem must be in using duplicate ID.
The button and the hidden input have the same ID. Make them different and try again.
Dont ask me the reason why it worked, all i can tell you is after doing this and that and tearing each part of your code, finally i made it work. click below link to see the demo
http://jsfiddle.net/praveen_prasad/KaK5A/4/
The changes i made are: removed id and name attributes from submit buttons from form
Example:
<input type="submit" value="Save" name="submit" id="submit"/>
changed above to below
<input type="submit" value="Save" />
Note For JsFiddle Demo: when you will click delete user on modal, form will submit. jsfiddle will say "Error 404", as it wont find the link you are posting your form. Open firebug and see that its actually posting to correct url.
"Delete User": function() {
var self = $(this);
var form = $('#edit_user_form');
tmpElm = $('<input type="hidden" />');
tmpElm.attr('name', 'delete');
tmpElm.attr('id', 'delete');
tmpElm.val(true); // HERE ----------------
tmpElm.appendTo(form);
form.submit();
return true;
}
At the designated location, shouldn't it be :
tmpElm.value(true);
or
tmpElm.attr('value', 'true');
I find it less confusing to handle my form submits upon confirms via jQuery ajax with serialized form values. It has the added benefit of avoiding unwanted form submits from buttons inside the <form> tags. So, it would look something like this:
<form id="edit_user_form">
...
<button id="submit_btn">Submit</button><br />
<button id="cancel_btn">Cancel</button><br />
<button id="delete_btn">Delete</button>
...
</form>
And then the javascript:
$('#delete_btn').click(function() {
$('#dialog-modal').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
return false;
},
"Delete User": function() {
$.ajax({
url: "/admin/edit-user",
type: "POST",
data: $('#edit_user_form).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred: " + errorThrown);
},
success: function(){
//Notify of success, redirect, etc.
}
});
}
}
});
});
So, it still submits via a POST. It now can happen asynchronously (or not) You can "do things" on success without changing the page, or alternatively redirect as you might need. I use a "dispatcher" page to submit to my object oriented framework, which then returns the output back to the PHP dispatcher to be json_encoded and echoed as a string for the AJAX call to use on success. Using this pattern, I only have to have one page that spits out plain text and the rest can reside in my OO Classes, which can't be called directly by ajax without doing some serious clooging (by using xajax)

Categories

Resources