i am trying to embed a simple jquery dialog-message into a form. The dialog should only show some additional information and not interact with the form in any way except beeing called via a button from inside the form.
My problem is the following: If the dialog is called from inside the form the whole page gets refreshed instantly, not showing the dialog at all and clearing all form fields. If the button is outside the form everything is working just fine.
The dialog content is being loaded via templates like this:
<script>
$(function() {
var dlg = $( "#dialog-message" ).dialog({
autoOpen: false,
width: '80%',
closeOnEscape: false,
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
},
open: function() {
// Content laden...
$("#dialog-message").load('template.html', function() {}).dialog()
}
});
$( "#opener" ).click(function() {
$( "#dialog-message" ).dialog( "open" );
});
});
</script>
The form integration:
<form method="post" name="post" action="index.php?site=bewerbung">
<table width="100%" border="0" cellspacing="1" cellpadding="2" bgcolor="$border">
...
</tr>
<tr bgcolor="$bg1">
<td height="25"> </td>
<td><input class="input" type="checkbox" name="rules" id="rules" value="1" /><button id="opener">Regeln</button></td>
</tr>
</table>
</form>
Your button submits the form, so you need to prevent the default button action via JavaScript:
$("#opener").on('click', function(e) {
dlg.dialog("open");
e.preventDefault();
});
You don't mentioned what jQuery (UI) version you are using. My code above is for the newer versions.
Here's the demo.
Generally for Buttons and Submit-inputs: you can prevent the refreshing of the page, if you place "return false;" on the end of your function. In your case
$( "#opener" ).click(function() {
$( "#dialog-message" ).dialog( "open" );
return false;
});
Related
I am using a ui-dialog and want to pass a php variable to a url if the Delete button is clicked. I have looked at a large number of other answers to similar questions but nothing seems to quite fit what I am trying to do.
The code below works correctly for the link shown, but doesn't work when I try to pass the php variable to the url.
This code works fine
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id=');
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
I have tried using this but it doesn't work
window.open('https://example.com/page.php?id=<?php echo $id?>')
Try add ";" at the end.
<?php echo $id;?>
Assuming your above code is in .php file, try below code:
<script>
$( function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open("https://example.com/page.php?id=<?php echo $id; ?>");
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
You can assign pageid in input hidden fields like below.
After you need to get this fields value using val() function.
<input type="hidden" value="<?php $id; ?>" id="pageId" />
$( function() {
var PageId = $('#pageId').val();
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
"Delete": function() {
window.open('https://example.com/page.php?id='+PageId);
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
I am trying to send some custom post data from a page that displays specific posts in a jquery pop-up email.
At the moment, I have a completed HTML form , and JQuery modal box setup.
Here is this js code for this:
jQuery(document).ready(function($){
var email = $( "#email" ),
message = $( "#message" ),
allFields = $( [] ).add( email ).add( message ),
tips = $( ".validateTips" );
$( ".email-course" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
$( "#dialog-form" ).dialog({
autoOpen: false,
modal: true,
width: 550,
height:260,
resizable: false,
show: 'fade',
title: 'Email course',
buttons: {
"Send": function() {
//Need help here
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
});
And the HTML form:
<div id="dialog-form" title="Email this course">
<form>
<fieldset>
<label for="email">To:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="email">From:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="message">Message (optional)</label>
<input type="text" name="message" id="message" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
and the button:
<div class="right"><button class="email-course">Email this course</button></div>
My question is how to read the data from the form and also I will have to pull some post data with ids from the page that loads them all and send it by Wordpress's wp_email I assume? I will have to merge the "message (optional)" with that specific post ID's data as well. Any other information I need please let me know. Thanks in advance.
Background:
jQuery has a .serialize() method that:
Encode a set of form elements as a string for submission.
With the use of this method you can serialize all the fields values without having to collect them individually.
For example, you can do:
$('form').serialize()
and you will get a string with all the collected form fields & values, then you can pass this string to the server in a data: {} object inside a $.ajax request.
.serialize() documentation at jqAPI
Filling the Send callback:
"Send": function() {
//Need help here
$.ajax({
data : $('#dialog-form form').serialize(),
error : function (jqXHR, textStatus:string, errorThrown:string) {
if (errorThrown) {
// Show message.
}
},
success : function (response_from_server:ResponseFromServer, statusText:string, xhr) {
// Do post-processing here.
},
type : 'POST',
url : ajaxurl
});
},
Here:
ajaxurl: A javascrip global variable set by WordPress to be used in AJAX queries pointing to '/wp-admin/admin-ajax.php'
$('#dialog-form form').serialize() : This method is the one that will serialize all the Successfull HTML controls present in the form and will append them as data in the AJAX query.
Here only is missing the nonce checking to validate the AJAX request, I didn't put it there to make the code simple.
Then on the WordPress PHP backend you have to capture that serialize that data in order to process it as you like.
Hope it helps.
I have a modal dialogue with jquery which populate a div,I need instead of populate a div to submit directly ,How can I achieve that,
What I did: I have a button when I click it opens a modal dialogue,with this modal dialogue I add data and I save data in another div,below the code:
My part of code :
<script>
$(function() {
$( "#MyDialog2" ).dialog({
autoOpen: false,
height: 300,
width: 700,
modal: true,
buttons: {
"ADD": function() {
$('#keyword_new_name').val($('#keyword_new_nameadd').val());
$( this ).dialog( "close" );
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
$('#keyword_new_nameadd').val("");
}
});
$( "#newKeyword" ).click(function() { $( "#MyDialog2" ).dialog( "open" ); });
});
</script>
HTML looks like that:
<div id='MyDialog2' >
<table cellpadding='11' >
<tr>
<td></td>
<td>Name:</td><td><input type='text' name ='keyword_new_nameadd' id='keyword_new_nameadd' size ='35' /></td>
</tr>
</table>
</div>
<form method="POST" action="">
<div>
<table cellpadding='11' >
<tr>
<td></td>
<td>Name:</td><td><input type='text' name ='keyword_new_name' id='keyword_new_name' size ='35' /></td>
</tr>
</table>
</div>
<input type='button' value='NewKeyword' id='newKeyword' />
<input type='submit' value='addKeyword' id='addKeyword' />
</form>
Thank you for your help!!!
If you mean that you want to directly submit your form, right after (or instead of... not sure which you need)
$('#keyword_new_name').val($('#keyword_new_nameadd').val());
add
$('form').submit();
Personally I would give the <form> and ID and use that instead
$('#myFormId').submit();
I got it I added
$( this ).dialog( "close" );
$("#add_keyword").click();
add_keyword is the ID of 1 of my submit buttons
I am trying do some file upload using jquery. The upload box have to be in the dialog box.
Now I just want to know after I click on the dialog's upload button. How can I submit yet the page do not load.
I tried using this
$('#uploadForm').submit().preventDefault();
It has not action at all.
html
<script>
$( "#dialog-upload" ).dialog({
autoOpen: false,
height: 200,
width: 350,
modal: true,
buttons: {
"Upload": function() {
var bValid = true;
bValid = bValid && checkCSV()
if(bValid){
**$('#uploadForm').submit().preventDefault();**
}
$( "#dialog-upload" ).dialog( "close" );
},
Cancel: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
$( this ).dialog( "close" );
}
});
</script>
<div id="dialog-upload" title="Upload csv file">
<form>
<fieldset>
<form action='ajax.php' id = 'uploadForm' method='post' enctype='multipart/form-data'>
<input type="text" name="file" id="fileUpload" size = 30 class="text ui-corner-all" />
</form>
</fieldset>
</form>
</div>
php
if (isset($_FILES['file'])) {
echo "success";
}
Use the EVENT delegation for your form submit
$('#uploadForm').submit(function( e ){
e.preventDefault(); // browser 'submit' event behavior prevented
});
Than do:
"Upload": function() {
var bValid = true;
bValid = bValid && checkCSV()
if(bValid){
$('#uploadForm').submit();
}
// ......
You can bind something to the submit event prior to submitting.
$(function() {
$('#uploadForm').submit(function(evt) {
evt.preventDefault();
});
});
Then just call .submit() without the preventDefault() in your original location.
All code below is a stand-alone working example (greatly simplified) of what I am trying to do. If anyone copy/pastes the below code blocks into 3 separate files, the code is fully self-contained-- just remember to reference/include test5.js and the jquery libraries in script tags at top of document.
SUMMARY: HTML div injected via Ajax not opening in the jQuery UI dialog widget.
Objective: On document load, jquery-ajax injects an html form (ultimately, it will retrieve appropriate form values from DB which is the reason for ajax). A div with id="clickme" is injected with the html. Clicking the div should open the dialog.
Problem: The jQueryUI .dialog does not appear. I put an alert box inside the click event, and that fires. But the dialog remains elusive.
Therefore, problem appears to be the fact that the HTML is injected. What am I missing?
HTML: index.php
<div id="putit_here">
</div>
JAVASCRIPT/JQUERY: test5.js
$(function() {
var pih = $('#putit_here');
$.ajax({
type: "POST",
url: "ajax/ax_test5.php",
data: 'contact_id=1',
success:function(data){
pih.html(data);
var etc1 = $( "#editThisContact_1" );
/* *****************************************************************
Moving Dialog up >here< was correct answer.
********************************************************************
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
****************************************************************** */
}
}); //End ajax
/* **** This is where I had it previously ***** */
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
$(document).on('click', '#clickme', function(event) {
alert('HereIAm...');
$( "#editThisContact_1" ).dialog( "open" );
}); //End #clickme.click
}); //End document.ready
AJAX - ax_test5.php
$rrow = array();
$rrow['contact_id'] = 1;
$rrow['first_name'] = 'Peter';
$rrow['last_name'] = 'Rabbit';
$rrow['email1'] = 'peter.rabbit#thewarren.nimh.com';
$rrow['cell_phone'] = '+1.250.555.1212';
$r = '
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<p class="instructions">Edit contact information for <span class="editname"></span>.</p>
<form name="editForm" onsubmit="return false;">
<fieldset>
<span style="position:relative;left:-95px;">First Name:</span><span style="position:relative;left:10px;">Last Name:</span><br />
<input type="text" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'" name="fn_'.$rrow['contact_id'].'">
<input type="text" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'" name="ln_'.$rrow['contact_id'].'"><br /><br />
<span style="position:relative;left:-120px;">Email:</span><span style="position:relative;left:30px;">Cell Phone:</span><br />
<input type="text" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'" name="em_'.$rrow['contact_id'].'">
<input type="text" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'" name="cp_'.$rrow['contact_id'].'">
</fieldset>
</form>
</div>
';
echo $r;
EDIT:
Updated question to move dialog definition inside AJAX success callback. Did not completely solve problem, though. The dialog now appears if I change the autoOpen flag to true, but that is not how the script must work. The dialog still does not open upon clicking the (injected) #clickme div.
EDIT 2:
My bad. At first I thought it didn't work, but then found that my live test and posted SO question varied in one line: how the .dialog("open") was being called. In live code, it was still using the var: etc1.dialog("open") -- but in post above the selector was fully referenced: $('#editThisContact_1').dialog("open"). The posted syntax was correct. Thanks gents, and also itachi who got me to check chrome console.
You are trying to initialize a dialog on an element before the element exists. You need to initialize the dialog on "#editThisContact_1" after your ajax call comes back successfully.
Like this:
....
success:function(data){
pih.html(data);
//now your DIV is actually there so init the dialog
var etc1 = $( "#editThisContact_1" );
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
}