Submit directly from a modal dialogue jquery - php

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

Related

What's wrong with my jquery-ajax code so it's not working properly?

Following is my HTML code from Smarty template :
<div id="user-popup-login" title="Demo Test Packages">
<div id="pop-up">
<!--<div class="popup-right"><img src="images_new/close.gif" alt=" " align="right" width="29" height="29" /></div>
<div class="clear"></div>-->
<div class="error_msg" id="login_error" style="text-align:center; margin-top:5px;">
</div>
<div class="clear"></div>
<div class="popup-left">
<form name="user_login_form" id="user_login_form" class="login_box" method="post" action="{$site_url}login">
<input type="hidden" name="referral_url" value="{$referral_url}" id="referral_url" />
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><input name="user_name" id="user_name" class="user" type="text" value="E-mail" onblur="if(this.value=='') this.value='E-mail';" onfocus="if(this.value=='E-mail') this.value='';" />
</td>
</tr>
<tr></tr>
<tr>
<td colspan="2"><input name="user_password" id="user_password" class="user" type="password" value="password" onblur="if(this.value=='') this.value='password';" onfocus="if(this.value=='password') this.value='';" />
</td>
</tr>
<tr></tr>
<tr>
<td><input name="Submit" type="submit" class="login-btn" value="" /></td>
<td><div id="registern">Register Now</div></td>
</tr>
<tr>
<td align="right" colspan="2">Forgot Password? </td>
</tr>
</table>
</form>
</div>
<!--<div class="popup-right"><img src="images_new/facebook-sign.gif" alt=" " width="156" height="229" /></div>-->
<div class="clear"></div>
</div>
</div>
Following is my jQuery code :
<script language="javascript" type="text/javascript">
$(function() {
$("#user-popup-login").dialog({ autoOpen: false });
$( ".user-not-loggedin" )
.click(function() {
$( "#user-popup-login" ).dialog( "option", "width", 400 );
$( "#user-popup-login" ).dialog( "option", "modal", true );
$( "#user-popup-login" ).dialog( "open" );
return false;
});
$( ".get-start" )
.click(function() {
$( "#user-popup-login" ).dialog( "option", "width", 400 );
$( "#user-popup-login" ).dialog( "option", "modal", true );
$( "#user-popup-login" ).dialog( "open" );
return false;
});
//This function is used to submit User Login form
$('#user_login_form').live('submit', function() {
$('.login-btn').attr('disabled', 'disabled');
show_request('#login_error');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data:$(this).serialize(),
dataType: 'json',
success: function(response) {
$('.login-btn').removeAttr('disabled', 'disabled');
var log_error = response.log_error;
if(log_error=='yes') {
var error_msg = response.error_msg;
var dialog_title = 'Input Errors Found';
var dialog_message = error_msg;
$("#login_error").html(error_msg);
} else {
$("#login_error").html('');
$( "#user-login" ).dialog('close');
var suc_msg = response.suc_msg;
var dialog_title = 'Logged in Successfully';
var dialog_message = suc_msg;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
buttons:{
'OK': function() {
$(this).dialog('close');
}
}
});
$dialog.dialog('open');
$('#user_login_form')[0].reset();
}
}
});
return false;
});
});
</script>
And my php file named user_login.php which has an alas name as login which is used in action attribute has following code :
<?php
include_once("includes/application-header.php");
prepare_request();
$obj_login = new Login();
if($gSession->ReadFromSession('IS_LOGGEDIN') && $_GET['act'] !='logout') {
header("location:".SITE_URL."home");
die();
} else {
if( "POST" == $_SERVER['REQUEST_METHOD'] ) {
$login_data = extract_array( $_POST , array("user_name", "user_password") );
$user_id = $obj_login->DoUserLogin($login_data);
if($user_id) {
list($subscription_type, $days_left) = $gUsers->GetUserSubscriptionDetailsByUserID($user_id);
if($gUsers->InitiateUserSession($user_id, $subscription_type, $days_left)) {
$gUsers->UpdateUserLoginHistory($user_id);
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();
}
} else {
$error_msg = $obj_login->GetError();
list($login_data) = prepare_response($login_data);
$error_msg = '<b>We are unable to log you in for one of the following reasons:</b>
</p>
<ul>
<li>Incorrect email or password (case sensitive)</li>
<li>Cookies are not enabled on your browser</li>
<li>You havent registered with entrance prime</li>
<li>We have not activated your account</li>
</ul><p></p>';
$reponse_data['login_error'] = 'yes';
$reponse_data['error_msg'] = $error_msg;
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();
}
}
// CODE FOR LOGOUT
if(isset($_GET['act']) && $_GET['act']=='logout') {
$gUsers->UpdateUserLogoutHistory();
$obj_login->UserLogout();
header("Location:".SITE_URL."home");
die();
}
}
?>
My issue is when a I click on Login button without filling any values,the form is submitted without any error and displays "undefined" in the pop-up instead of showing me the errors. Can anyone help me out to resolve this issue?
in php , --> login_error
$reponse_data['login_error'] = 'no';
in ajas callback --->log_error
var log_error = response.log_error;
try to change all log_error to login_error
I believe that $(this) inside of $.ajax does not point to the $ object you want it to (form).
Try writing just below this line:
$('#user_login_form').live('submit', function() {
myform = $(this); // caching the jquery object to a local variable
and then writing this in the proper section below (replace your code):
$.ajax({
type: myform.attr('method'),
url: myform.attr('action'),
data:myform.serialize(),

Why is jquery dialog-message refreshing my page unwantedly (inside form)

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;
});

.submit() without reloading page

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.

jQueryUI Dialog with ajax-injected html selector

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
}

JQuery use in a (PHP) form

I have been building a page where an administrator of the page can come look at some abstracts that have been submitted. I have used jquery to insert a modal-form where they can categorize the abstract to fit within one of five choices(four sessions, and one n/a). However, I am stuck on the function in the script.
What I want it to do is to go to the .php page where I'll have the appropriate code written to UPDATE the record in the database, then send the administrator back to the main page, to continue categorizing abstracts if they wish.
I have the form:
<div id="dialog-form" title="Categorize this abstract">
<p class="validateTips">Please select one session for this abstract.</p>
<form method="post" action="savecat.php">
<fieldset>
<label><input type="radio" name="abstractcategory" value="session1" />Session 1</label>
<label><input type="radio" name="abstractcategory" value="session2" />Session 2</label>
<label><input type="radio" name="abstractcategory" value="session3" />Session 3</label>
<label><input type="radio" name="abstractcategory" value="session4" />Session 4</label>
<label><input type="radio" name="abstractcategory" value="NULL" />Irrelevant</label>
</fieldset>
</form>
</div>
In the script I have the categorize button:
$( "#categorize" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
And this is where I'm not sure what to do, in the dialog-form function:
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Categorize this abstract": function() {
What should I put here? I don't know. I want it to re-direct(?) to the savecat.php that is the action of the form.
Then there's the rest, to cancel, close, etc.
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
Can anyone point me in the right direction? I have a feeling it's a simple thing that I just am unaware of.
I guess you just want to submit the form?
$(this).find('form').submit();

Categories