I have the following code:
JS
<script type="text/javascript">
$(function(){
$('#fgotpwfield').hide();
$('#login_submit').click(function() {
$('#form_result').fadeOut('fast');
$('#myccrxlogin input').removeAttr('disabled');
$('#myccrxlogin').submit();
});
if ($("#myccrxlogin").length > 0) {
$("#myccrxlogin").validate({
rules: {
email: { required: true, email: true },
password: 'required'
},
messages: {
email: { required: 'Your email address is required.',
email: 'Please enter a valid email address.'},
password: 'Your password is required.'
},
submitHandler: function(form) {
$('#myccrxlogin input').attr('disabled','true');
$('#login_submit').fadeOut('fast');
$('#forgotpw').fadeOut('fast');
$('body').append('<div id="page_load"></div>');
var email = $("#email").val();
var pw = $("#password").val();
var data = 'email=' + email + '&password=' + pw;
$.ajax({
url: "hidden url",
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#page_load').remove();
if(html == 'OK') {
alert(html);
} else {
//$("#password").val('');
$("#form_result").html(html);
$('#form_result').fadeIn('slow');
$('#myccrxlogin input').removeAttr('disabled');
$('#login_submit').fadeIn('slow');
$('#forgotpw').fadeIn('slow');
}
}
});
} /*close submit handler */
});
};
});
</script>
HTML
<div id="form_result" style="margin:10px; display:none;" class="field-submit-error"></div><div style="clear:both;"></div>
<div id="loginformfield">
<p style="font-size:24px; font-weight:bold; font-family:Arial, Helvetica, sans-serif; color:#f93;">Login</p>
<form class="loginform" id="myccrxlogin" method="post" target="_parent">
<p>
<input name="email" type="text" id="email" tabindex="1" />
<label for="email">E-mail</label></p>
<p><input name="password" type="password" class="text large required" id="password" tabindex="2" />
<label for="password">Password</label></p>
<div class="loading"></div>
<p>I forgot my password</p>
<p><a class="readmore" href="#" id="login_submit" style="margin-bottom:0.5em;" tabindex="3">Login!</a></p>
</form>
</div>
A person enters their email and password, the file is first validated then run through an ajax call successfully. The ajax PHP page echo's either an error or 'OK'. I know the code gets to 'OK' because the alert(html) is triggered but it runs infinitely. Not sure why?
update
I believe I might be running into the recursion issue described here: http://docs.jquery.com/Plugins/Validation#General_Guidelines although I am not sure it applies.
I can't step through, but I believe you need to have your submithandler return false.
I believe the form is being submitted by the form action and the ajax submission.
Looking at the recursion link you posted, you would need to change this line:
$('#myccrxlogin').submit();
so that the raw form is being submitted, rather than the jquery-ized version of the form. In their example,
$(form).submit();
becomes
form.submit();
Try changing your submit line in a similar way.
The amazingly unclear and wild answer is this: I had to add the following into my ajaxed-PHP page. Something about running locally or with the setup I have is wacky. Hopefully this helps somebody.
Add to the first line of your ajax php page:
header('Access-Control-Allow-Origin: *');
Related
I'm not a tech completely, and I'm trying to build my custom theme for WordPress.
So, I came to a point that I need to implement a custom JS script to send the form data. As far as I understand, it's going to be a PHP file, but now I'm concentrated on front-end. This is AJAX + jQuery validation.
I don't want my form to refresh the page after it sends the data, just a simple message telling that everything went successful.
Can anyone have a look at the code I wrote and tell me what's wrong with it? It took me just two days..
PS - the file, that stores that code is embedded into WP theme properly, with a jQuery as a dependancy. I wonder, do I have to do anything to implement AJAX, or it comes with jQuery?
http://codepen.io/anon/pen/MpdRpE
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">Sorry, but this field can't be empty.</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">Oopps, I haven't seen emails like that.</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Want to leave any message?*" class="textarea" required></textarea>
<p class="error-message">Nothing to say at all? Really?</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="error-message error-message_main_success val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
.error-message {
display: none;
}
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(){
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error", ".error-message").css("display", "block");
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
First you need to prevent the default click event
Second you need a action variable to pass to the wordpress hook
3th you jquery selector for showing the errors is incorrect, the coma needs to be in the string
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();//a little bit cleaner
}
else {
jQuery.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
for more information read the wp documentation on ajax
Little changes required otherwise code is looking fine.Have a look
$(document).ready(function(){
$(".submit-btn").click(function(){
var name = $(".firstname").val();
var email = $(".email").val();
var message = $(".textarea").val();
if(name === "" || email === "" || message === "") {
$(".val-error", ".error-message").css("display", "block");
return false;
}
else {
$.ajax({
url:"/assets/php/send.php",
method:"POST",
data:{name:name, email:email, message:message},
success: function(data) {
if(data){
$("form").trigger("reset");
$(".val-success").show(fast);
}
}
});
}
});
});
Here is my javascript and php code for loging in jquery mobile but i got parser error for this request. please help me with this.
<script>
$("#login").click( function () {
//collect userName and password entered by users
var username = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(username, password);
});
//authenticate function to make ajax call
function authenticate(username, password) {
$.ajax({url: "http://localhost/track/signinmobile.php",
data: '{"username": "' + username + '", "password" : "' + password + '"}',
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
alert(result);
},
error: function (request,error) {
alert("this is"+ error);
},
successCallback:function(){
}
});
</script>
<div data-role="fieldcontain" class="ui-hide-label">
<form id="login" >
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="submit" name="login" id="login" value="Login"/>
</form>
</div>
Is there any error in my javascript code?
Here is my signinmobile.php and the data base connections are working.
<?php include"connection.php";
$email=$_GET['username'];
$password=$_GET['password'];
$user=mysql_query("SELECT * FROM users");
while($row=mysql_fetch_array($user))
{
if (($email==$row['email']) && ($password==$row['password']))
{
$response_array['status'] = 'success';
}
else {
$response_array['status'] = 'error';
}
}
header('Content-type: application/json');
echo json_encode($response_array);
?>
You are missing a } to close the authenticate function.
Besides that your form and the submit button have the same id. It is in general a bad idea to have two html tags with the same id and this means that your function is called after clicking on the form.
You should wrap your script inside a $(document).ready.
$(document).ready(function() {
// your script.
});
This will prevent your script from running before the elements are loaded.
You should also prevent the form from submitting by ending the click function with a return false; statement. This prevents the page refresh.
And I don't have experience with jsonp but it generates an error for me. I would suggest using normal json but I don't know your other plans with the script.
The data you send to the server is a string, you should use a javascript object. This is done by removing the quotes and the plus signs.
data: { username: username, password: password },
Please help me out...
I'm creating a multistage sign up form,
on my first step user is asked for email,password and confirm password...
so when email input is typed and user enters the password, i need the script to be run in background for checking availability of email id, and if not available then message should be shown via image not echo message, so in short all these happens without submit ...
and I'm using PHP
please help me out...
Thanks in advance
This is HTML:
<input type="password" id="signuppassword" name="signuppassword" class="register-input" placeholder="Password" />
<input type="password" id="signup-cpassword" name="signup-cpassword" class="register-input" placeholder="Confirm Password" />
<input type="button" name="next" class="next action-button" id="first-next" value="" />
give ur email field a class or Id n use the folling function.
$("#email").blur(function()
{
var searchbox = $(this).val().trim();
checkEmailExistance(searchbox);
});//end on blur
function checkEmailExistance(searchbox){
var dataString = 'searchword='+ searchbox.trim();
if(searchbox=='')
{
}
else
{
$.ajax({
type: "POST",
url: '<?php echo base_url()."index.php/register/email_validation"; ?>',
data: dataString,
cache: false,
beforeSend: function() {
},
success: function(dataString)
{
if(dataString=="0"){
$("#error").text("This is Unique Address");
$("#error").attr('isverified','1');
}else
{
$("#error").text("This email address is already present");
$("#error").attr('isverified','0');
}
}
});//end ajax
};
I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.
I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!