I am new to codeigniter & javascript, I have been working with the form submission through ajax in codeigniter. I need to use form validation on the text field & other inputs in the form. I searched the web & couldn't find any resources or references. Currently my form submission is working fine, I just need to validate my inputs using Jquery or ajax.
Here is my Model
class test_model extends CI_Model {
function save_data()
{
$name = $this->input->post('Name');
$email = $this->input->post('Email');
$contact = $this->input->post('Contact');
$sex = $this->input->post('Sex');
$country = $this->input->post('Country');
$data = array(
'Name' => $name,
'Email' => $email,
'Contact' => $contact,
'Sex' => $sex,
'Country' => $country);
$result = $this->db->insert('test2',$data);
return $result;
}
}
My Controller just forwards the data to Model
class test extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('test_model');
$this->load->helper('url');
}
function index() {
$this->load->view('test_index');
}
function save() {
$data = $this->test_model->save_data();
echo json_encode($data);
}
}
Here is my View
<form>
<div class="container" style="padding-top: 80px;">
<div class="form-group">
<label for="Name">First Name :</label>
<div class="col-md-4">
<input type="text" name="Name" id="Name" class="form-control" placeholder="Your Name..">
</div>
</div>
<div class="form-group">
<label for="Contact">Contact :</label>
<div class="col-md-4">
<input type="text" class="form-control" id="Contact" name="Contact" placeholder="Your Contact No..">
</div>
</div>
<div class="form-group">
<label for="Sex" class="col-md-1">Gender :</label>
<div class="form-check form-check-inline">
<label >
<input type="radio" class="form-check-input" name="Sex" id="Sex" value="Male">Male </label><span style="padding-right: 10px;"></span>
<label>
<input type="radio" class="form-check-input" name="Sex" id="Sex" value="Female">Female </label>
</div>
</div>
<div class="form-group">
<select class="form-control custom-select col-md-4" id="Country" name="Country">
<option value="">Select Country</option>
<option value="Europe">Europe</option>
<option value="United Stated of America">United States of America</option>
<option value="India">India</option>
</select>
</div>
<div class="form-group">
<button type="button" type="submit" id="btn_save" class="btn btn-primary" >
<span class="spinner-border spinner-border-sm"></span>Create</button>
<button type="button" class="btn btn-secondary" >Close</button>
</div>
</div>
</form>
My JS code is below :
$('#btn_save').on('click',function() {
var Name = $('#Name').val();
var Email = $('#Email').val();
var Contact = $('#Contact').val();
var Sex = $('input[name="Sex"]:checked').val();
var Country = $('#Country').find(":selected").val();
$.ajax({
type : "POST",
url : "https://localhost/newCrud/test/save",
dataType : "JSON",
data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
success : function (data) {
if(data == 1) {
$('[name = "Name"]').val("");
$('[name = "Email"]').val("");
$('[name = "Contact"]').val("");
$('[name = "Sex"]').val("");
$('[name = "Country"]').val();
alert("Data Inserted"); }
}
});
return false;
});
});
Guys, my above code works just fine, I need your help to know how can i validate my form using ajax, as it is already passing data to the model from here. As far I've known that Codeigniter form_validate method can't be used in ajax form submission. Really need your help guys. Thanks for your time & suggestions.
Why not????
You can use CI validation as it is a built in server side validation method and you are hitting your server through AJAX
You need to alter your code a bit
$.ajax({
type : "POST",
url : "https://localhost/newCrud/test/save",
dataType : "JSON",
data: {"Name":Name, "Email":Email, "Contact":Contact, "Sex":Sex, "Country":Country},
success : function (data) {
if(data == 1) {
$('.form-group').removeClass('has-error');
$('[name = "Name"]').val("");
$('[name = "Email"]').val("");
$('[name = "Contact"]').val("");
$('[name = "Sex"]').val("");
$('[name = "Country"]').val();
alert("Data Inserted");
}
},
error : function (error) {
if(error.status == 500){
var response = error.responseJSON.validation;
$('.form-group').removeClass('has-error');
$.each(response, function(index, item) {
$('[name='+index+']').closest('.form-group').addClass('has-error');
});
}
}
});
Update your controller as like this
public function save() {
// add this if not loaded earlier
$this->load->library('form_validation');
$this->form_validation->set_rules('Name','Name', 'required');
$this->form_validation->set_rules('Contact','Contact', 'required');
$this->form_validation->set_rules('Email','Email Address','required|valid_email');
if ($this->form_validation->run() == FALSE) {
$validation = $this->form_validation->error_array();
return $this->output
->set_content_type('application/json')
->set_status_header(500)
->set_output( json_encode(array(
'validation' => $validation,
'message' => 'validation error !!!'
)) );
}
$data = $this->test_model->save_data();
echo json_encode($data);
}
Here i did validation for 3 fields name, email and contact. Also i used bootstrap error class 'has-error' to highlight failed elements.
Simply use the jQuery Validate plugin (https://jqueryvalidation.org/).
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
Related
Im trying to submit a form using a modal but im getting this error. 422 (Unprocessable Entity). In my Menu Model i specified my table name $menu using protected $table ='menu';
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
My read function is completely working but the adding is not working
function load(){
$.get('dash',function(data){
$.each(data,function(key,val){
$('#data')
.append("<tr>"+
"<td>"+val.Item_Code+"</td>"+
"<td>"+val.Name+"</td>"+
"<td>"+val.Printer+"</td>"+
"<td>"+val.Category+"</td>"+
"<td>"+val.Price+"</td>"+
"<td>"+val.Stocks+"</td>"+
"<td>"+val.Image+"</td>"+
"<td>"+
"<button type='button' class='btn btn-outline-success'>
<i class='fa fa-clipboard'></i> Edit</button>"+
"<button type='button' class='btn btn-outline-danger'><i
class='fa fa-trash'></i> Delete</button>"+
"</td>"+
"</tr>");
});
});
}
My add function does not add the data inputted in the modal
load();
$('form').submit(function(e){
e.preventDefault();
Item_Code = $('#Item_code').val();
Name = $('#Name').val();
Printer = $('#Printer').val();
Category = $('#Category').val();
Price = $('#Price').val();
Stocks = $('#Stocks').val();
Image = $('#Image').val();
$.post('/post',{Item_Code:Item_Code,Name:Name,
Printer:Printer,Category:Category,Price:Price,
Stocks:Stocks,Image:Image},function(data){
$('#Item_Code').val('');
$('#Name').val('');
$('#Printer').val('');
$('#Category').val('');
$('#Price').val('');
$('#Stocks').val('');
$('#Image').val('');
load();
});
});
});
My method
public function post(Request $req)
{
if($req->ajax()){
$req->validate([
'Item_Code'=>'required',
'Name'=>'required',
'Printer'=>'required',
'Category'=>'required',
'Price'=>'required',
'Stocks'=>'required',
'Image'=>'required'
]);
$post = new Menu;
$post->Item_Code = $req->Item_Code;
$post->Name = $req->Name;
$post->Printer = $req->Printer;
$post->Category = $req->Category;
$post->Price = $req->Price;
$post->Stocks = $req->Stocks;
$post->Image = $req->Image;
$post->save();
return response()->json();
}
}
My routes.
Route::post('/post', 'AdminController#post')->name('create.inventory');
My modal
<div class="modal-body">
<form>
<label for="required-input" class="require">Item Code:</label>
<input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">
<label for="placeholder-input" class="require">Name:</label>
<input type= "text" class="form-control" placeholder="Name" id = "Name">
<label for="single-select" class="require">Printer</label>
<select id="Printer" class="form-control">
<option>Kitchen</option>
<option>Bar</option>
</select>
<label for="single-select">Category</label>
<select id="Category" class="form-control">
<option>Japanese</option>
<option>Beverage</option>
</select>
<label for="required-input" class="require">Input Price:</label>
<input type ="number" class="form-control" placeholder="Price" id="Price">
<label for="required-input" class="require">Quantity:</label>
<input type ="number" class="form-control" placeholder="Quantity" id="Stocks">
<label for="required-input" class="require">Image:</label>
<input type = "file" class="form-control" id="Image">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
422 is the status code for Laravel validation
Check the input data, Probably one of values is null
This is how I would make such a function
bootstrap model - I added an ID to the form and I also added a div with the class of messages for the validation and success messages.
<div class="modal-body">
<div class="messages"></div>
<form id="productForm">
{{ csrf_field() }}
<label for="required-input" class="require">Item Code:</label>
<input type = "text" class="form-control" placeholder="Item Code" id = "Item_Code">
<label for="placeholder-input" class="require">Name:</label>
<input type= "text" class="form-control" placeholder="Name" id = "Name">
<label for="single-select" class="require">Printer</label>
<select id="Printer" class="form-control">
<option>Kitchen</option>
<option>Bar</option>
</select>
<label for="single-select">Category</label>
<select id="Category" class="form-control">
<option>Japanese</option>
<option>Beverage</option>
</select>
<label for="required-input" class="require">Input Price:</label>
<input type ="number" class="form-control" placeholder="Price" id="Price">
<label for="required-input" class="require">Quantity:</label>
<input type ="number" class="form-control" placeholder="Quantity" id="Stocks">
<label for="required-input" class="require">Image:</label>
<input type = "file" class="form-control" id="Image">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Ajax code
<script>
var form = $('#productForm');
var formData = form.serialize();
var createUrl = '{{ route('create.inventory') }}';
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: createUrl,
type: 'post',
data: formData,
dataType: 'json',
success: function (response) {
var successHtml = '<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign push-5-r"></i></strong> '+ response.message +
'</div>';
var messages = $('.messages');
$(messages).html(successHtml);
window.setTimeout(function() {
location.reload();
}, 800);
},
error: function(response) {
var errors = response.responseJSON.errors;
var errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors, function( key, value ) {
errorsHtml += '<li>'+ value[0] + '</li>';
});
errorsHtml += '</ul></div';
$('.messages').html(errorsHtml);
}
});
});
</script>
for the controller code.
make sure you add the use Validator; to the controller
now will make the validation in the controller
public function post(Request $request)
{
if ($request->ajax()) {
$validator = Validator::make($request->all(), [
'Item_code' => 'required',
'Name' => 'required',
'Printer' => 'required',
'Category' => 'required',
'Price' => 'required',
'Stocks' => 'required',
'Image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
} else {
$post = new Menu([
'Item_name' => $request->input('Item_code'),
'Name' => $request->input('Name'),
'Printer' => $request->input('Printer'),
'Category' => $request->input('Category'),
'Price' => $request->input('Price'),
'Stocks' => $request->input('Stocks'),
'Images' => $request->input('Images')
]);
$post->save();
return response()->json(['success' => true, 'message' => 'success'], 200);
}
}
}
This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
Can anyone tell me why this bit of code isn't working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('submit', function () {
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
</body>
</html>
When I push submit nothing happens. In the receiving php file I'm using $_POST['time'] and $_POST['date'] to put the data in a mysql query but it's just not getting the data. Any suggestions? I'm assuming it's something to do with the submit button but I can't figure it out
The form is submitting after the ajax request.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
JS Code
$("#submit").click(function() {
//get input field values
var name = $('#name').val();
var email = $('#email').val();
var message = $('#comment').val();
var flag = true;
/********validate all our form fields***********/
/* Name field validation */
if(name==""){
$('#name').css('border-color','red');
flag = false;
}
/* email field validation */
if(email==""){
$('#email').css('border-color','red');
flag = false;
}
/* message field validation */
if(message=="") {
$('#comment').css('border-color','red');
flag = false;
}
/********Validation end here ****/
/* If all are ok then we send ajax request to email_send.php *******/
if(flag)
{
$.ajax({
type: 'post',
url: "email_send.php",
dataType: 'json',
data: 'username='+name+'&useremail='+email+'&message='+message,
beforeSend: function() {
$('#submit').attr('disabled', true);
$('#submit').after('<span class="wait"> <img src="image/loading.gif" alt="" /></span>');
},
complete: function() {
$('#submit').attr('disabled', false);
$('.wait').remove();
},
success: function(data)
{
if(data.type == 'error')
{
output = '<div class="error">'+data.text+'</div>';
}else{
output = '<div class="success">'+data.text+'</div>';
$('input[type=text]').val('');
$('#contactform textarea').val('');
}
$("#result").hide().html(output).slideDown();
}
});
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() {
$("#contactform input, #contactform textarea").css('border-color','');
$("#result").slideUp();
});
HTML Form
<div class="cover">
<div id="result"></div>
<div id="contactform">
<p class="contact"><label for="name">Name</label></p>
<input id="name" name="name" placeholder="Yourname" type="text">
<p class="contact"><label for="email">Email</label></p>
<input id="email" name="email" placeholder="admin#admin.com" type="text">
<p class="contact"><label for="comment">Your Message</label></p>
<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
PHP Code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
$output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
$output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if (strlen($message) < 5) { //check emtpy message
$output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
die($output);
}
$to = "info#wearecoders.net"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
'Reply-To: ' . $useremail . '' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to, $subject, $message . ' -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
$output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
die($output);
} else {
$output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
die($output);
}
This page has a simpler example
http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/
Here is a nice plugin for jQuery that submits forms via ajax:
http://malsup.com/jquery/form/
its as simple as:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('form was submitted');
});
});
</script>
It uses the forms action for the post location.
Not that you can't achieve this with your own code but this plugin has worked very nicely for me!
JS Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time='+ time + '&date=' + date;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Form
<form>
<input id="time" value="00:00:00.00"><br>
<input id="date" value="0000-00-00"><br>
<input name="submit" type="button" value="Submit">
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
</div>
PHP Code
<?php
if($_POST)
{
$date=$_POST['date'];
$time=$_POST['time'];
mysql_query("SQL insert statement.......");
}else { }
?>
Taken From Here
type="button"
should be
type="submit"
In event handling, pass the object of event to the function and then add statement i.e.
event.preventDefault();
This will pass data to webpage without refreshing it.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="msg"></div>
<form method="post" class="frm" id="form1" onsubmit="">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
<!--><span class="sp"><?php// echo $f_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
<!--><span class="sp"><?php// echo $l_err;?></span><!-->
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
<!--><span class="sp"><?php// echo $e_err;?></span><!-->
</div>
<div class="form-group">
<input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
<!--><span class="sp"><?php //echo $m_err;?></span><!-->
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
<!--><span class="sp"><?php //echo $p_err;?></span><!-->
</div>
<div class="radio">
<input type="radio" value="male" name="gender" id="gender" checked>male<br>
<input type="radio" value="female" name="gender" id="gender">female<br>
<input type="radio" value="other" name="gender" id="gender">other<br>
<!--><span class="sp"> <?php //echo $r_err;?></span><!-->
</div>
<div class="checkbox">
<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
<!--><span class="sp"> <?php //echo $c_err;?></span><!-->
</div>
<input type="submit" class="btn btn-warning" name="submit" id="submit">
</form>enter code here
</div>
<div class="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(function () {
$(".submit").click(function (event) {
var time = $("#time").val();
var date = $("#date").val();
var dataString = 'time=' + time + '&date=' + date;
console.log(dataString);
if (time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else
{
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#data").html(data);
}
});
}
event.preventDefault();
});
});
</script>
<form action="post.php" method="POST">
<input id="time" value=""><br>
<input id="date" value=""><br>
<input name="submit" type="button" value="Submit" class="submit">
</form>
<div id="data"></div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
<?php
print_r($_POST);
if ($_POST['date']) {
$date = $_POST['date'];
$time = $_POST['time'];
echo '<h1>' . $date . '---' . $time . '</h1>';
}
else {
}
?>
I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.
I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}
Controller:
function post()
{
if(!$this->input->is_ajax_request())
{
show_404();
exit;
}
$data['result'] = false;
$config['upload_path'] = base_url().'userfiles/customer';
$config['allowed_types'] = 'pdf';
$config['max_size'] = 100000;
$this->load->library('upload', $config);
$file = $this->input->post('userfile');
if ( ! $this->upload->do_upload($file))
{
$data['result'] = true;
$error = array('error' => $this->upload->display_errors());
$data['error'] = $error;
}
else
{
$data['result'] = true;
$data_upload = array('upload_data' => $this->upload->data());
$data['success'] = $data_upload;
}
echo json_encode($data);
}
View:
<div class="form">
<div class="form-group">
<label class="form-label" for="package">Package :</label>
<select class="package form-control" id="package" name="package">
<option value="none">Please select..</option>
<?php foreach($package as $row) { ?>
<option value="<?php echo $row['id_order_package'] ?>"><?php echo $row['name'] ?></option>
<?php } ?>
</select>
<div class="error" id="msg_package"></div>
</div>
<div class="form-group">
<label class="form-label" for="price">Price ( Rp ) :</label>
<input type="text" class="form-control" name="price" id="price" placeholder="" disabled>
<div class="error" id="msg_price"></div>
</div>
<div class="form-group">
<label class="form-label" for="days">Days :</label>
<input type="text" class="form-control" name="days" id="days" placeholder="" disabled>
<div class="error" id="msg_days"></div>
</div>
<div class="form-group">
<label class="form-label" for="userfile">File :</label>
<input type="file" id="userfile" name="userfile" class="form-control">
<div class="error" id="msg_userfile"></div>
</div>
<div class="form-group">
<label class="form-label" for="description">Description :</label>
<textarea class="form-control" rows="5" name="description" id="description"></textarea>
<div class="error" id="msg_description"></div>
</div>
<div class="form-group center">
<div class="btn btn-primary">ORDER</div>
</div>
</div>
Javascript:
$('.btn').click(function(e){
$('#msg_package').html(' ');
$('#msg_userfile').html(' ');
$('#msg_description').html(' ');
if($('#package').val() == 'none') {
$('#msg_package').html('Please select package');
} else if($('#userfile').val() == '') {
$('#msg_userfile').html('This field is required');
} else if($('#description').val() == '') {
$('#msg_description').html('This field is required');
} else {
$.ajax({
url : '<?php echo base_url() ?>account_order/add/post',
type : 'POST',
dataType: 'json',
mimeType:"multipart/form-data",
processData: false,
data : { userfile: $('#userfile')[0].files , price: $('#price').val() , days: $('#days').val() },
success: function( data ) {
if(!data['result']){
}else{
alert(data['error']);
}
}
});
}
});
But, i get an error
{"result":true,"error":{"error":"<p>You did not select a file to upload.<\/p>"}}
I tried to post data & file from ajax, but it doesn't work.
My question is how to fix that error? Why the controller can't read userfile's content?
Thank you
try to put your inputs in form and give the form id='your_form_id' then send your data by this way in javascript:
var data = new FormData(document.getElementById("your_form_id"));
then replace this line data : { userfile: $('#userfile')[0].files , price: $('#price').val() , days: $('#days').val() },
with this data: data,
also set this after data: data,:
async: false,
processData: false,
contentType: false,