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
}
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 can't seem to make this to work. I'm trying to submit form using jquery dialog and I want to receive in php so I can use $_POST.
Any idea?
HTML:
<div id="table_rows_form">
<form id="fieldsform" action="system/create">
<label for="fields">How many fields are needed?</label>
<input type="text" id="fields" name="fields" />
<button type="submit">Submit</button>
</form>
</div>
Javascript:
$(document).ready(function() {
$('#table_rows').on('click', function() {
$('#table_rows_form').dialog({
open: function() {
$(this).find('[type=submit]').hide();
},
draggable: true,
modal: true,
resizable: false,
closeOnEscape: false,
width: 'auto',
minHeight: 235,
title: 'Number of Fields',
dialogClass: 'no-close',
buttons: {
"Send": function() {
$('#fieldsform').submit(function(event) {
var formData = {
'fields': $('input[name=fields]').val()
};
$.ajax({
type: 'POST',
url: $('#fieldsform').attr('action'),
data: formData,
dataType: 'json',
encode: true
});
});
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
return false;
});
});
PHP:
print_r($_POST);
The dialog opens correctly but when pressing send button doesn't do anything and doesn't gives any error at the console. Any idea about the error? I'm a newbie with jquery.
You're just adding a submit handler with your code $('#fieldsform').submit( ... ) so it doesn't trigger anything.
Rather, you should do that on document ready, and in the click handler for "Send" button, call $('#fieldsform').submit();
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;
});
I am trying to use a JQuery dialog to act similar to an open file dialog, but instead of files I am using records from a database to populate the dialog.
The problem that I am having is that I cannot seem to get the html option data loaded into the html select in my dialog. I have used the Google Javascript debugger in Chrome and have stepped through my javascript code which is called from my PHP ajax. I see no errors and I see the data is there and formatted correctly when I put it into the append statement. I don't understand why it does not show up in my html select.
Thanks for your help.
below is my Ajax function which receives the data.
function doOpenAjax(filterStr)
{
$.get(
"contenteditServerAjax.php",
{filter: filterStr },
function(data) {
var optsArr = data.split('|~|');
var seloption = "";
$.each(optsArr, function(i) {
seloption += '<option value="' + optsArr[i] + '">' + optsArr[i] + '</option>';
});
$('#chooseArticleName2').find('option').remove().end();
$('#chooseArticleName2').append(seloption);
},
"html"
);
}
For reference this is part of my php which contains the jquery dialog:
<head>
<script>
$(document).ready(function() {
var dlg = $("#opendiv").dialog({modal:true, height:550, width:650,
hide:{ effect: 'drop', direction: "down" },
autoOpen:false,
maxHeight: 1200,
maxWidth: 1200,
minHeight: 250,
minWidth: 300,
buttons: { "Open": function() { $('#state').val('Open Doc'); $('#contentform').submit(); $(this).dialog("hide"); },
"Cancel": function() { $(this).dialog("close");}}
});
dlg.parent().appendTo($("#contentform"));
});
</script>
<div id="opendiv" name="opendiv" title="OPEN">
<p align="center">Enter Name to Open Article as:</p>
<p>
Filter:
<input name="docFilter2" id="docFilter2" type="text" value="$filter2" maxlen="64" size="28"/>
<input name="LoadTitles2" id="LoadTitles2" type="button" value="Load Available Titles"
onclick="doOpenAjax( $('#docFilter2').val() );"/>
</p>
<p>
<div id="ajaxOutput2">
<select name="chooseArticleName2" id="list2" size="8" style="min-width:92%"
onchange="
var mytext = $('#chooseArticleName2 :selected').text();
$('#textBoxArticleName2').val(mytext);">
</select>
</div>
</p>
<p>
Document:
<input type="text" id="textBoxArticleName2" name="textBoxArticleName2" size="56"/>
</p>
</div>
Just FYI, it would be more efficient to do this:
$('#chooseArticleName2').empty().html(seloption);
Than this:
$('#chooseArticleName2').find('option').remove().end();
$('#chooseArticleName2').append(seloption);
Really not familiar with jQuery. Is there anyway I can pass form data to a PHP file using jQuery?
FORM:
<div id="dialog-form" title="Fill in your details!">
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name"/>
<label for="email">Email</label>
<input type="text" name="email" id="email" value=""/>
<label for="phone">Phone</label>
<input type="phone" name="phone" id="phone" value=""/>
</fieldset>
</form>
It's a pop-up dialog with jQuery and gets submitted with:
$("#dialog-form").dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid) {
$.ajax({
url: 'process-form.php',
success: function (response) {
//response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}
});
$(this).dialog("close");
}
}
}
});
What I want to do is to send the form data that the user enters into process-form.php, where it will be processed and sent as an email (which I can do). Just not to sure on the jQuery side of things. Is it even possible?
You can use the .serialize() function
$('yourform').serialize();
Docs for .serialize() here
You would use it like this :
$.ajax({
url: 'process-form.php',
data: $('form').serialize(), // **** added this line ****
success: function (response) { //response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
}
});
Yes, you can use the jQuery .post() method, which is detailed here
$.post( "process-form.php", $( "#dialog-form" ).serialize( ) );
Given your current code the easiest way is to serialize the form into the data property:
[...]
url: 'process-form.php',
data: $('#dialog-form').serialize()
You're on the right lines with $.ajax, but you need to actually pass the data with the submission, which you haven't done so far. You're best off setting the 'type' as well.
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid ) {
$.ajax({
url: 'process-form.php',
type: "post",
data: {
name: $('[name=name]').val(),
email: $('[name=email]').val(),
phone: $('[name=phone]').val(),
},
success: function (response) { //response is value returned from php
$( "#dialog-success" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
$( this ).dialog( "close" );
}
These variables should now be available in your PHP script as $_POST['name'], $_POST['email'] and $_POST['phone']
Whats the point for form if you're sending with ajax?
On the problem now, get the inputs by:
var fields = [];
$("#dialog-form form fieldset > input").each(function() {
fields.push( $(this)[0].value );
});
...
$.ajax({
url: 'process-form.php',
data:fields
...