Laravel dynamic form input text and upload file - javascript

I have a problem when I add input type="file" to the dynamic form insert
all works before I tried to add input type="file"
also, I got no error message on the browser
addMore.blade.php
<form name="add_name" id="add_name" enctype="multipart/form-data">
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button> //add dynamically input
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
here the ajax
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
});
//note the dynamic add input filed button already works #add
//already tried remove serialize() still not work
//also i got no error message on the browser
here the HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal')->store('proposals'); //already change to ->file(proposal[]) not work
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}

you are using serialize while sending data via ajax, you need to pass FormData with ajax.
Below is a complete code for sending file with ajax, and also you can trigger event when form is submitted so you can get entire formdata:
<form name="add_name" id="add_name" enctype="multipart/form-data" action="home" method="post">
#csrf
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$('#add_name').submit(function(e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
url: form.attr('action'),
method: "POST",
data: formData,
type: 'json',
processData: false,
contentType: false,
success: function(data) {
if (data.error) {
printErrorMsg(data.error);
} else {
i = 1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display', 'block');
$(".print-error-msg").css('display', 'none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
return false;
});
</script>
HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal');
foreach ($proposal as $file) {
$file->store('proposals');
}
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}

Related

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Confirmation Message not working Using Ajax Codeigniter

I am fetching data from database using ajax in codeigniter and now i am trying to put "delete confirmation box"
in controller but that button is not working,
Here is controller file/code
$user['result']=$this->crud->AddMember($data);
foreach($user['result'] as $row) {
echo "<td>";
<input type="hidden" name="id" value="'.$id.'">
<input type="submit" class="btn btn-danger btn-sm" value="Delete" name="delete" onclick="return confirm('Are you sure you want to delete this item')">
</form>';
echo "</td>";
}
Here is view file
<form method="post" name="myForm" class="form-horizontal" id="user_form" enctype="multipart/form-data">
<input type="text" class="form-control" id="FlatNumber" name="FlatNumber" placeholder="">
<button type="submit" class="btn btn-primary btn-lg" id="butsave">Add Details</button>
</form>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
event.preventDefault();
var FlatNumber = $('#FlatNumber').val();
if(FlatNumber == '') {
alert("Please enter Flat Number");
}else{
$.ajax({
url:"<?php echo base_url() . 'index.php/Member/AddRecord'?>",
type: "POST",
data: {FlatNumber : FlatNumber},
dataType: "html",
success: function(msg){
alert(msg);
if (msg == 'exist') {
$("#successs").hide();
}else{
$("#errorr").hide();
}
}
});
}
});
});
</script>
It is because onclick works only for elements who already on this page. after ajax response it will not work so you need to use code like this.
$(document).on("click",".btn-danger", function(){
});

422 (Unprocessable Entity error when submitting form with ajax

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

Ajax submitting form without refreshing page [duplicate]

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 {
}
?>

Ajax form submit without page refresh

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

Categories

Resources