jquery $("#form").submit() not getting called - php

I have a form on a page that requires a captcha if the user has a blocked attribute set in a database.
$("#expressform").submit(function() {
if($("#op").val() == "")
return false;
if($("#tagbar").val() == "")
return false;
$.post("getallowed.php", function(data) {
if(data == "true")
submitNormal();
else if(data == "false"){
displayCaptcha();
}
});
return false;
});
If the user is not allowed, the displayCaptcha function is called instead of just submitting the form.
function displayCaptcha(){
$.post("expresscaptcha.php", function(data) {
var string = data;
$("#expressformdiv").html(string);
Recaptcha.create("xxxxxxxxxxx", "captcha",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
});
}
This function posts to a php script that returns a new type of form that returns the html for a new form with the id expressformcaptcha. Here is the php script.
<?php
echo <<<_END
<form id="expressformcaptcha">
//other form elements
<div id="captchadiv"><div id="captcha"></div></div>
</form>
_END;
?>
All of this works fine, the captcha displays, etc. However, the alert in the following never gets called. Why?
$("#expressformcaptcha").submit(function() {
alert("FORM SUBMITTED");
});
Does it have something to do with the captcha being there that screws with jquery? When submit the form, instead of the alert, the page just refreshes.

You need to use live or delegate as expressformcaptcha is injected into the DOM at a later time.
$("#expressformcaptcha").live('submit', function() {
alert("FORM SUBMITTED");
});

Related

Form submitting with "email already exist" conditon in Php using ajax

I am working with ajax Php, I want to check email availability using ajax(on blur function)
my code is working fine, showing whether email exists or not but my form submitting even " email already exists " message showing
, I just want that form should not submit if I enter existing email, Here is my code, Where I am wrong?
<script type = "text/javascript" >
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function() {
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if (filter.test(email_val)) {
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/Register/email_check", {
email: email_val
}, function(response) {
alert(response);
$('#loading').hide();
//$('#message').html('').html(response).show().delay(4000).fadeOut();
if (response.trim() == '1') {
$('#failuremsg').show().delay(4000).fadeOut();
} else {
$('#successmsg').show().delay(4000).fadeOut();
}
});
return false;
}
});
});
</script>
replace the submit button on the form with
<button id="submit-form">Submit</button>
set a validated=true variable in your main code when all checks have passed
add some jquery
$( "#submit-form" ).click(function() {
if(validated){
$( "#yourForm" ).submit();
}else{
return false;
}
};

check email availability in Codeigniter without going to database and disable form to submitting till email is available

I am using Codeigniter and i am creating a login registration form which check the email of user that it available or not. User can login with that id.
So I am Trying to use Ajax for it.
So I have Put this Ajax in my View.
$(document).ready(function() {
$("#email").keyup(function() {
var email = $(this).val();
if (email.length > 3) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: emailAvailability,
data: { email: email },
success: function(data) {
console.log(data);
$("#result").html(data);
if (data.indexOf('Available')) {
emailAvaliable = 1;
//$('#candidateLogin').removeClass('disabled');
} else {
emailAvaliable = 0;
//$('#candidateLogin').addClass('disabled');
}
}
});
return false;
} else {
$("#result").html('');
}
});
});
I am Using parsley plugin for validation.
$(".formValidationClass").on('click', function (e) {
e.preventDefault;
$(this).parsley();
});
Now the Controller Code.
public function check_email_availability(){
$data = $this->input->post();
// Now I want to check email is unique or not without going to database.
}
The Second Problem is i want to disable the form till email is available & valid.
I have tried this script to disable the form to submit but it's not working and form get submitted. I have done the server side validation to not submit but still i want to prevent it form the client side.
this is the script.
$(".formValidationClass").on('click', function(e) {
e.preventDefault;
$(this).parsley().validate();
console.log('on form click, After validation');
// return false;
});
var emailAvaliable = 0;
$(".formValidationClass").submit(function(event) {
// Validate form fields
if (emailAvaliable == 1) {
console.log('Email Avaliable');
$(this).parsley();
return true;
} else {
console.log('Email not Avaliable');
return false;
}
});
All the suggestion related improving the code is acceptable. Thanks.
if you want to prevent the form submit event then please use: e.PreventDefault(); Check this Using JQuery - preventing form from submitting for more information. I think this is useful for you.

jQuery Post and Get Form data

When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});

jquery click function inside form submit function

I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});

how to use jquery $.post posting on the same page rather than another?

here is my jquery $.post
$(document).ready(function() {
$("form[name=frmedit]").submit(function() {
$.post('index.php',
{
dealname: $("[name=dealname]").val(),
startdate: $("[name=startdate]").val()
},
function(data)
{
if(data.success)
{
location.href = data.redirect;
}
else
{
$("#colright #error").html(data.message);
}
}, 'json');
return false;
});
});
the php part is on the same page
if(isset($_POST['btnNext']) && ($_FILES['image']['size'] > 0))
{ //run query to save data }
so my question is can i have all this on one page?
i also have another question
where i have
$("form[name=frmedit]").submit
how can i put the name of the button btnNext in that rather than just .submit?
the reason why i want to use all this on one page is because when a submit is done i want to check
if a thumbnail uploaded is greather than 0 being that it exists, like i was normally doing.
thanks
if your ajax succeeds , then return true so that it will do form submit otherwise do a false, it won't do a form submit
function(data)
{
if(data.success)
{
return true
}
else
{
$("#colright #error").html(data.message);
return false
}
}, 'json');
return false;

Categories