Creating a custom confirm box after submitting an AJAX form - php

I'm submitting a form using the AJAX JQuery validation plugin. The code looks something like this:
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
fname: {required: true},
sname: {required: true},
gender: {required: true},
},
messages: {
fname: {required: " *"},
sname: {required: " *"},
gender: {required: " *"},
},
submitHandler: function(form) {
$('input[type=submit]').attr('disabled', 'disabled');
$('#results').html('Loading...');
$.post('process_participant.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Now so the problem is after I send this information to my PHP page to be prcoessed (process_participant.php) I want to respond with a confirmation box asking if the user wants to add another participant. The PHP code looks something like this:
if (everything processes okay){
echo '<script type="text/javascript">';
echo 'input_box=confirm("Saved successfully. Would you like to add another participant?");
if (input_box==true) {
window.location = "new_participant.php"
}
else {
window.location = "home.php"
}';
echo '</script>';
}
This all works fine but the default confirmation box isn't acceptable. I need to be able to style it and change it from OK and CANCEL to YES and NO. I decided to use this plugin: http://kailashnadh.name/code/jqdialog/ and use the following code on the PHP side:
echo '<script type="text/javascript">';
echo " function confirmBox() {
$.jqDialog.confirm(\"Are you sure want to click either of these buttons?\",
function() { window.location = \"new_participant.php\"; },
function() { window.location = \"home.php\"; }
);
});";
echo "confirmBox();";
However I can't seem to get it to work. Maybe I should avoid using a plugin? The whole AJAX thing is making things confusing. Anyone know the best way to implement a custom confirm box in this situation?

create the box from the start with display:none
and when the function from the post request returns
do the checks (based on the variable data)
and if everything is ok change the visibility using jquery's show()

try this
its easy to implement just define your own html for alert and conform-box

Related

Issue in JQuery validate when opening add/update form using ajax

Problem
JQuery Validate does not work. In the below plunker, Please click on "Please click here" button and then click on save. It will not validate form.
Sample code in Plunker
I have jQuery validation code which is working fine in case I open the add/update form in new page. I meant by redirecting the user to a new route.
$("form#" + createRoleForm).validate({
rules: {
},
messages: {
},
submitHandler: function(form) {
}
});
In case I open the add/update form on clicking the button in same page when I am inside List page...The above jQuery validate code does not work. I am assuming that I will need something like this...
$(document).ready(function() {
$(document).on("eventtype", "object", function() {
});
});
But, I am not sure how can I bind the validate event in this way....
Since your form is async, your element is not already on the dom when you are creating the validator.
What you should do is add the validate code on your ajax success function:
//...
success: function(result) {
$('#SaveRoleModal').html(result);
createValidator("form#" + createRoleForm)
return false;
},
//...
function createValidator(target) {
$(target).validate({
rules: {
Role: {
required: true
}
},
messages: {
Role: {
required: "Please enter Role"
}
},
submitHandler: function(form) {
console.log('ok :)')
}
});
}

Search data from dynamically created table

I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});

getting response from a php script

So I created a html site with multiple forms, using jQuery dialog UI for display and jQuery form plugin for ajax submission.
Form looks like this:
<form id="login_form" action="admin.php" method="post">
Username: <input type="text" name="username" id="username"/><br/>
Password: <input type="password" name="password" id="password"/>
</form>
...the form options look like this:
$('#login_form').dialog({
buttons:{
"Login": function(){
var options = {
success: function(data){
alert(data);
$(this).dialog("close");
$('#news_form').dialog("open");
},
timeout: 3000,
fail: function(data){
alert('fail');
},
clearForm: true
};
// bind form using 'ajaxForm'
$('#news_form').ajaxSubmit(options);
},
"Exit": function(){
$(this).dialog("close");
}
}
});
...and the php file is a simple:
<?php
$data = 'Herro!';
echo $data;
?>
Problem is that on success the form returns the html page that was the source of the submit and not 'Herro!' like i anticipated. So what am i doing wrong?
Both the admin.html and the admin.php files are in the same dir.
Also the web is run locally via xampp, but i tried to put it on a web server as well with no improvements.
FINAL EDIT: the problem was in fact because I was calling a different form object in the DOM to submit the data, a form that doesn't have the action property set. Thanks to everyone for a quick solution.
Change $('#news_form').ajaxSubmit(options); to $('#login_form').ajaxSubmit(options);
Try wrapping the result in a JSON object(in the php file) and on the java script end you can now decode this JSON object using any standard json javascript library(you can download one here: http://www.JSON.org/json2.js).
Then you the below code
admin.php:
<?php
$data = json_encode('Herro!');
echo $data;
?>
Then in your html(javascript) you can make this little adjustment:
<script>
var result; //adjustment 1
$('#login_form').dialog({
buttons:{
"Login": function(){
var options = {
success: function(data){
result = JSON.parse(data); //adjustment 2
alert(result); //adjustment 3
$(this).dialog("close");
$('#news_form').dialog("open");
},
timeout: 3000,
fail: function(data){
alert('fail');
},
clearForm: true
};
// bind form using 'ajaxForm'
$('#news_form').ajaxSubmit(options);
},
"Exit": function(){
$(this).dialog("close");
}
}
});
</script>
remeber to reference the json2.js file you downloaded in your page. Let me know if this helps you.

Form Validation with $.post()

I am using bassistance.de's Validation jQuery plugin to validate a form #signup-form. Instead of submitting the form data directly to the server the usual way, the form data should be submitted AJAX'ly via $.post().
JS Code
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
});
Problem: If a user entered data that does not pass the jquery validation, the click handler on #submit-btn will still allow the form to be submitted! Is there a way to check that there are no validation errors?
Try this:
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
if ($('.signup-form').valid()) {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
The best way to do this is to use the submitHandler option to validate:
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
},
submitHandler: function(form){
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
This will automatically be called once the form is valid. No need to attach anything new to your submit button or the submit event.

jQuery validation , submit handler, and submit form

I am having some problems on executing the following code.
The code submits but it doesnt do anything, it comes back to the same screen, it seems that the values of the form have been not submited.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
var result;
$.post('test.php', $('#signin_form').serialize(), function(data){
result = $.parseJSON(data);
if (result.flag == 'false'){
$('#results').show()
}
})
.success(function(data){
if (result.flag == 'true'){
form.submit();
}
}, 'json');
}
});
});
</script>
If I change the code to the following, it works and it takes me to the proper screen, but i need to validate, a captcha code, i am not sure if it is the right place to do it, i tried to use beforeSubmit but then the captcha is not validated.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
There is something about the $.post that i dont underestand... and doesnt submit the information.
Does anyone know what it could be?
thanks!
You don't need to change how the form submits, in this case, for validating the captcha, use remote function from jquery.validate.
There are some problems around the remote usage with jquery.validate. Check if you did the following:
1) Make sure you are using jQuery version 1.6.1 and above only.
2) Use the "synchronous" option for remote execution (default being asynchronous) and to do this set async argument to false.
Example of usage:
Suppose this is my form...
HTML:
Add id and name attributes to all the form elements or just the captcha (this one must have both).
<form id="signin_form" action="save.php" method="POST">
Enter captcha: O1S2C3A4R
<br/>
<input type="text" id="captcha" name="captcha" value=""/>
<input type="submit" id="save" name="save" value="Save"/>
</form>
jQuery:
Add type, async and data arguments. This last argument passes the captcha value to check.php file and that's why that element needs the id attribute. Then you are able to use this selector $('#captcha').
(For me this is better but you can also call the element by name using other selector type)
Just to know, you need to also define an error message for the remote, in this case I used Invalid captcha.
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
required: true,
remote: {
url:"check.php",
type:"post",
async:false,
data: {
/* this is the name of the post parameter that PHP will use: $_POST['captcha'] */
captcha: function() {
return $.trim($("#captcha").val());
}
}
}
}
},
messages: {
captcha: {
required: "*",
remote: "Invalid captcha"
}
}
});
});
PHP: check.php
At this point it is important to use "true" or "false" as string to let know the jquery.validation plugin if the captcha is valid or not. In this case, if captcha is equals to O1S2C3A4R then is valid and, at client side, you will look that the submit will process the form to save.php file specified in the html form action attribute.
<?php
$captcha = $_POST['captcha'];
if($captcha == "O1S2C3A4R"){
echo "true";
} else {
echo "false";
}
?>
Doing this way, you can validate the whole form without problems and also check the captcha value remotely without altering plugin functionality.
Also you can test all this code together and look that it works :-)
Hope this helps.
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
remote: {
url: "remote.php"
}
}
}
},
messages: {
captcha: {
remote: "Please enter the text in the captcha."
}
}
});
});
</script>
HTML form:
<form id="signin_form">
<input type="text" name="captcha">
<input type="submit">
</form>
PHP:
$response = $_GET['captcha'];
$answer = 'captcha_answer';
if($response==$answer){
echo 'true';
} else {
echo 'false';
}
Sorry for shoving this part into an answer -- I'm not allowed to comment:
Keep in mind that setting the 'async' parameter to false will lock up your page until you get a response, which might not be what you want. The validation library should block normal form submission if it's waiting on a response for remote validation, at least in newer versions (I'm using jQuery 1.7.2 and Validation 1.10.0).
IIRC the jQuery Validate library will treat anything other than the exact string "true" as being an error. This can be used to pass different custom messages depending on the reason for rejection. json_encode adds extra quotation marks that cause jQuery Validate to see it as a custom error message.

Categories