Jquery Mobile - Getting an ajax result issue - php

Trying to do a simple web app with jquery mobile. I have put together a simple log in form with ajax results to be displayed. Problem is my ajax is not getting a result even when I alert out to see if the URL is valid. Is there something special I need to do using jquery mobile?
Any thoughts/answers much appreciated!
Here is the HTML code:
<div data-role="page" id="login" data-theme="a" data-add-back-btn="true">
<div data-role="header">
<h2>Log in</h2>
</div>
<div data-role="content" data-theme="a" data-add-back-btn="true">
<form action="mobilelogin.php" method="post">
Email: <input type="text" name="email" id="useremail">
Password: <input type="password" name="password" id="userpassword">
<input type="submit" value="Enter">
</form>
<div id="loginresult"></div>
</div>
<div data-role="footer"><h4>Chris Sherwood Design 2012</h4></div>
</div>
Js file:
$(document).ready(function() {
$('form').submit(function() {
var emailchecker = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $("#useremail").val();
var userpassword = $("#userpassword").val();
var checklength = userpassword.length;
if(email == ""){
alert('Please fill in email field');
return false;
}else if(userpassword == ""){
alert('Please fill in password field');
return false;
}else if((!emailchecker.test(email))){
alert('Please use a valid email');
return false;
}else if(checklength < 6 || checklength > 6){
alert('Password must be six characters');
return false;
}else{
var datastring = $(this).serialize();
alert(datastring);
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
}
});
PHP
<?php
echo 'nothing special here...';
?>

From your code:
return false;
$.ajax({
type: "POST",
url: "mobilelogin.php",
data: datastring,
success: function(data){
$("#loginresult").html(data);
}
});
You are returning false before the ajax request.
EDIT (assumed it was a simple mistake, have added more explanation)
You will need to either move that return false; to below the ajax() call, or use the event object like so:
$('form').submit(function(e) {
e.preventDefault();
The problem with just using return false; is that if there is an error in something before it it will not stop the default action. So if your ajax request errors it will miss the return false; and start loading the action page.

Related

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

Ajax and jQuery custom form submission in Wordpress

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

Displaying login error on same page when using a class (php)

I have a form to login
<div class="fade_bg">
<div class="actionDiv">
<form id="login_form" action="./classes/login/Authenticator.php" method="post">
<p>username: <input type="text" name="username" /></p>
<p>password: <input type="password" name="password" /></p>
<p>
<input type="submit" name="adminLogin" value="Log in" id="adminLogin" />
<input type="submit" name="cancelLogin" value="Cancel" id="cancelLogin" />
</p>
</form>
</div>
</div>
Notice the form action is './classes/login/Authenticator.php.' The PHP script is by itself with no HTML or anything.
What I want is for an error message to display inside
<div class="actionDiv">
If the user enters an empty form or the wrong credentials. I've tried using AJAX, but it didn't work.
The login itself works. I just need to print the errors.
Here is the AJAX I used:
$('#adminLogin').on('click', function() {
$.ajax ({
type: 'post',
url: './classes/login/Authenticator.php',
dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
if(data == 'invalid credentials')
$('body').html(data);
else
$('.fade_bg').fadeOut(200);
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
The form is probably getting submitted by the browser. You can prevent the default action.
$('#login_form').submit(function(e){
e.preventDefault();
//perform ajax request here.
});
Prevent the submit button from submitting the form:
$('#adminLogin').on('click', function(event) {
event.preventDefault();
...
And if you want to display the return message in the .actionDiv, then do so in your ajax success callback:
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').text(data));
...
For client side validation you need to check before $.ajax call this condition
You have to also give id to both input fields
$(document).ready(function(){
$('#adminLogin').on('click',function() {
//alert("hello");
var name = $("#username").val();
var error = 0 ;
if(name == ""){
$("#errUsername").fadeIn().text("Username required.");
$("#username").focus();
error++;
}
var password= $("#password").val();
if(password== ""){
$("#errPassword").fadeIn().text("Password required.");
$("#password").focus();
error++;
}
if(error > 0)
{
error = 0;
$('.actionDiv').append($('<p/>').text('invalid credentials'));
return false;
}
$.ajax ({
type: 'post',
url: 'login.php',
//dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
alert(data);
if(data == 'invalid credentials')
{
$('.actionDiv').append($('<p/>').text(data));
return false;
}
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
});
You need to add these two <span> tags near to Username and Password inputs respectively so that client side errors can be show in these two spans
Then on Server side When you check submitted form like
<?php
$uname = isset($_POST['username']) ? $_POST['username'] : "";
$pswd = isset($_POST['password']) ? $_POST['password'] : "";
//perform query operation whether Username with valid password is exist or not
if($notExist)
echo "invalid credentials";
else
echo "success";
?>
And when $.ajax response comes then you can inform user about invalid credentials in success like
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').html(data));

send post variables via jquery(ajax) to php himself document

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!

Submit form (jquery) and show results in colorbox

I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>

Categories