The submit button not working please help
with Ajax code on PHP form when I click on continue nothing happens at all see source code bellow
What am I doing wrong?
Code:
<div
style="display:none;"
class="col-xs-12 col-md-4 no-margin sm-margin-bottom xs-margin-top-screen-md xs-margin-bottom-screen-sm"
id="errorUserID"
ng-show="loginForm.userId.$invalid && (loginForm.userId.$touched || loginForm.$submitted)"
>
<span class="icon-alert red-icon" icon-bg="red" icon="alert"></span>
<span class="text-bold text-std" ng-transclude="" translate="">Please enter a value</span>
</div>
Ajax code:
$('#loginForm').submit(function(e) {
e.preventDefault();
var userId = $('#userId').val();
if (userId == null || userId == '') {
return false;
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=login',
data: $('#loginForm').serialize(),
success: function (data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
}
})
});
Related
How can i go back to the view page and modal with the validation errors if the validation runs false ..
I want to show validation errors in the modal ..
Im new to jquery ajax ..
Is there needed to add in my jquery .. or what way can i do it..
Controller
public function update(){
$this->form_validation->set_rules('lname', 'Family Name', 'required');
if ($this->form_validation->run() == FALSE) {
}
else {
$this->home_model->update();
redirect(base_url());
}
}
Jquery
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
console.log(data);
$('#no').val(data.rec['no']);
$('#lname_edit').val(data.rec['lname']);
$('#fname_edit').val(data.rec['fname']);
$('#mi_edit').val(data.rec['mi']);
$('#bdate_edit').val(data.rec['bdate']);
$('#module_edit').val(data.rec['module']);
$('.updatemodal').modal({
backdrop: 'static',
keyboard: false
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
To pass form validation status to client, use the below code in your controller. The code responds with a json-formatted, error, and notice text.
if ($this->form_validation->run() == FALSE) {
$json_response['form_errors'] = $this->form_validation->error_array();
exit(json_encode($json_response));
}
Client side, in your jquery ajax success handler, you can use the below code so the status response emitted server side is displayed to the client.
if (data.form_errors != undefined) {
var errors = '';
$.each(data.form_errors, function(i, val) {
errors = errors + "\n" + val;
});
if (errors != "") alert(errors);
}
else {
alert('no error(s) in form... submit form..');
}
Alternative to the above js code:
For updating each form elements' status when they change, use the below code. Place it outside your form submit handler.
function update_form_validation() {
$("input,select,textarea").on("change paste keyup", function() {
if ($(this).is(':checkbox') == true) {
$(this).siblings("label:last").next(".text-danger").remove();
} else if ($(this).is(':radio') == true) {
$(this).siblings('input[type="radio"][name="' + $(this).attr('name') + '"]:last').next(".text-danger").remove();
$(this).next(".text-danger").remove();
} else {
$(this).next(".text-danger").remove();
}
});
}
update_form_validation();
For displaying general notice and displaying each errors and notices right after their respective form element,
use the below code. In your form submit handler, place the code inside your ajax success function.
if (data.form_errors != undefined) {
$.each(data.form_errors, function(i, val) {
if ($('input[name="' + i + '"]').is(':hidden') == false) {
if ($('input[name="' + i + '"]').is(':radio') == true) {
$('input[name="' + i + '"]:last').after('<div class="text-danger">' + val + '</div>');
} else if ($('input[name="' + i + '"]').is(':checkbox') == true) {
$('input[name="' + i + '"]').siblings("label:last").after('<div class="text-danger">' + val + '</div>');
} else {
$('input[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('select[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
$('textarea[name="' + i + '"]').after('<div class="text-danger">' + val + '</div>');
}
}
});
} else {
alert('no errors in form... submit form..');
}
You can use CodeIgniter form validations function :
$errors = array();
if ($this->form_validation->run() == FALSE) {
$errors['validation_error'] = validation_errors();
echo json_encode($errors);
exit();
}
Now in jquery:
$(document).on('click', '#update', function() {
console.log($(this).attr('data-registerid'));
$.ajax({
url: "<?php echo base_url('home/get_data')?>",
type: "POST",
dataType: "JSON",
data: {
"id": $(this).attr('data-registerid')
},
success: function(data) {
var myObj = JSON.parse(data);
$('#error_div').html(myObj.validation_error);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
View
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">Login Form</h5>
</div>
<div class="modal-body">
<div id="modelError"></div>
<form method="post" action="javascript:void(0)">
<div class="input-group">
<input type="text" name="name" id="name" placeholder="First Name">
</div>
<div class="input-group">
<input type="text" name="last_name" id="last_name" placeholder="Last Name">
</div>
<input type="submit" id="my_form" name="Save">
</form>
</div>
</div>
</div>
</div>
Script
<script>
$('#my_form').click(function(){
$.ajax({
url: "<?php echo base_url('controller/function')?>",
type: "POST",
data: {
'name': $('#name').val(),
'last_name': $('#last_name').val(),
},
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
});
});
</script>
Controller
public function insert()
{
if(isset($this->input->post())){
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('last_name','Last Name','required');
if ($this->form_validation->run() == FALSE)
{
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}else{
$this->your_model->insert($this->input->post());
redirect(base_url());
}
}else{
$this->load->view('view-page');
}
}
I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});
I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];
I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}
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.