Form is not submitting in jQuery ajax success - javascript

I am making a simple form of single text input.I want to cross check from db that is it exist or not.So my html is
<form action="zoneAdd" method="post" id="zoneAdd" name="zoneAdd">
<div class="box-body">
<div class="form-group">
<label>Zone Name<span id="required">*</span></label>
<input type="text" class="form-control" name="zone_name" id="zone_name" placeholder="Enter Zone Name" />
<span id="zone_name_error"></span>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-primary btn-flat btn-sm" name="submit" value="Submit"/>
</div>
</form>
and my javasript is
$('document').ready(function(){
$("[name=submit]").click(function(e){
e.preventDefault();
if ($('#zone_name').val().length <= 0) {
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please enter Zone name!');
//isStepValid = false;
}
else if(!$('#zone_name').val().match(/^[a-zA-Z\s-, ]+$/)){
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Please use only alphabats!');
//isStepValid = false;
}else{
var data = {'zone':$('#zone_name').val()}
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success:function(err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
//document.forms["zoneAdd"].submit();
$('form#zoneAdd').submit();
//console.log($('form#zoneAdd').submit());
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
}
});
});
every thing is going right. My problem is my form is not submit in ajax success

I think problem in form action.
Specify exact path in the form action such that
<form action="<?php echo site_url('filenameWhereyouSubmit')?>" method="post" id="zoneAdd" name="zoneAdd">

You don't have a handler function on form submit and your ajax call
happens after $("[name=submit]").click().
You're submitting the form after ajax success:
success:function(err){
if(err == 0)
{
...
$('form#zoneAdd').submit();
...
}
}
but the submit is not ajax call, so try to handle the form
onsubmit.
something like this:
$('document').ready(function(){
$('form#zoneAdd').submit(function(e){
e.preventDefault();
// You checks code ...
var data = {
'zone': $('#zone_name').val()
};
$.ajax({
type:"post",
data:data,
url:"<?php echo site_url('zone/checkZoneName');?>",
success: function (err){
if(err == 0)
{
console.log('hello');
$('#zone_name_error').html('');
$('#zone_name_error').removeClass("errMsg");
$('#zone_name_error').removeClass("errMsgDngr");
}
else
{
$('#zone_name').addClass("errMsg");
$('#zone_name_error').addClass("errMsgDngr");
$('#zone_name_error').html('Zone Name already existed!');
}
}
});
});
});

Start form like this :
<form id="FORM-ID" method="post" action="">
For ajax submit
$(document).ready(function(){
$('#FORM-ID').submit(function(e) {
var myarray= array of all form values
var data = JSON.stringify(myarray);
e.preventDefault();
$.ajax({
type: "POST",
data: {value:data},
url: "URL TO SUBMIT",
success: function() {
//Sucess function
}
});
});

Related

if i click anywhere in the form - form submitting after ajax validation, can anyone tell me how to solve this issue

Validation is working good and form also submitting if i click submit button, only problem is form submitting if click anywhere in the page, please help me here. thanks in advance.
Javascript:
$(document).ready(function(){
$(":input[type='submit']").on('click', function(){
$(':input[type="submit"]').prop('disabled', true);
});
$("#locationName").on('change', function desgCheck()
{
var locationName = $('#locationName').val();
$.ajax({
type: "POST",
url: "../designation/locationName.htm",
data: {
locationName: locationName
},
dataType: "text",
success: function (data)
{
if ($.trim(data) !== 'Data available')
{
alert("This Location already exist!!");
$("#locationName").val("");
} else {
$("#desgForm").submit();
}
},
error: function (error) {
$("#locationName").val("");
}
});
});
$("#locationName").on('keyup', function desgCheck(){
var str = $("#locationName").val();
var a = str.toUpperCase();
$("#locationName").val(a);
});
jQuery("#desgForm").validationEngine();
});
HTML:
<form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">
<input type="text" id="locationName" autocomplete="off" name="locationName" class="form-control validate[required]">
<button type="submit" class="btn btn-primary" >Save</button>
</form>

how to clear form after submit the form and pass the data to php file without reloading page

how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<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: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>

Returning json results at the same page in laravel

I have trouble returning my search results as json in same page that I searched,
this is my function for search page
public function track(Request $request){
return view('front.track');
}
this is route for it:
Route::get('/track', 'frontend\FrontendController#track')->name('track');
and this function to get results of my search
public function shippingcode(Request $request){
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxxxxxxxxxxxxxx');
$shippingcode = $request->input('shippingcode');
$item = Order::where('shippingcode', $shippingcode)->first();
$courier = $item->courier;
$results = $rajaongkir->waybill($shippingcode, $courier);
return response()->json($results);
}
and this is route for it:
Route::post('/shippingcode', 'frontend\FrontendController#shippingcode')->name('shippingcode');
and finally this is my search form in blade:
<form class="form-inline text-center" action="{{route('shippingcode')}}" method="post">
{{csrf_field()}}
<lable>Shipping Code #</lable>
<input type="text" class="form-control" name="shippingcode" placeholder="93657275025">
<button class="btn btn-success" id="submit" type="submit" name="button">Track</button>
</form>
Issue
Issue is except getting results bottom of my form I will redirect to another page and see results as JSON.
any idea?
UPDATE
I have added jquery to my page in order to get results but still i will redirect to another page:
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('button[id="submit"]').on('click', function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
$.ajax({
url: '{{ url('shippingcode') }}',
type: "GET",
dataType: "json",
success:function(data) {
$('div#results').empty();
$("div#results").html(data);
}
});
});
});
</script>
and added this div bottom of my form <div class="col-md-8 col-md-offset-2" id="results"></div>
You need to prevent the default action of your form which is submitting the form via POST method to provided action URL.
Try adding -
$('button[id="submit"]').on('click', function(e) {
e.preventDefault();
// Your own login
});
SOLVED
Note: using e.preventDefault(); alone would not help at all, however
is necessary to have it.
Here is how I done it:
first of all I changed my function to code below:
public function shippingcode($code){
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxx');
$shippingcode = $code;
$item = Order::where('shippingcode', $shippingcode)->first();
$courier = $item->courier;
$results = $rajaongkir->waybill($shippingcode, $courier);
return response()->json($results);
}
and then I changed my route from POST to GET and added my {code} into it (look in my function).
Route::get('/shippingcode/{code}', 'frontend\FrontendController#shippingcode');
Finally I changed my JavaScript code to the following code. here I used e.preventDefault(); but pay attention how I got my button.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').on('click', function(e) {
e.preventDefault();
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var shippingcodedd = $("#code").val();
if(shippingcodedd) {
$.ajax({
url: '{{ url('shippingcode') }}/'+encodeURI(shippingcodedd),
type: "GET",
dataType: "json",
success:function(data) {
$('div#results').empty();
var summar = data.data.summary;
$('div#results').append('Data prints here!');
}
});
}else{
$('div#results').empty();
$('div#results').append('Sorry there is no info regarding to your tracking code in our system!');
}
});
});
</script>
PS: just for completeness here is my form HTML code:
<form class="form-inline text-center" action="" method="post">
{{csrf_field()}}
<lable for="shippingcode">Shipping Code #</lable>
<input type="text" id="code" class="form-control" name="shippingcode" placeholder="93657275025">
<button class="btn btn-success" id="submit" name="button">Track</button>
</form>
Hope it help others.

Confirm a form & display message if form is valid with JQuery

I'm developing my Django application and I would like to use JavaScript in order to improve my website.
I have a form and I would like to display 2 things :
Confirm the form before submit
If form is well submitted, display a message : 'Form is saved'
It's the first time I'm using JS and I need help to make this process.
This is my code :
<form class = "form" method='POST' action=''> {% csrf_token %}
<br></br>
{{ form.as_p}}
<br></br>
<button type="submit">Valider</button>
</form>
<script>
$('#form').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
</script>
And if my form is valid and saved :
<script type="text/javascript" >
$(document).on('Valider', 'form.form', function(form) {
var $form = $(form);
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
});
</script>
Could you help me ?
Thank you
You can try to adopt by your purpose this code:
$('#form').submit(function(e) {
// Prevents form to be submitted by default post request with page reloading
e.preventDefault();
if (confirm("Click OK to continue?")) {
// Here you can call your AJAX request
callAjax($('input[type=text]').val())
}
});
function callAjax(value) {
// Making AJAX request to your endpoint
// GET ipify just for example
$.ajax({
url:"https://api.ipify.org?format=json",
type: "GET",
success: function(form) {
alert("Form is saved");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" value="MOCK FOR CSRF TOKEN" />
<br></br>
<input type="text" required />
<br></br>
<button type="submit">Valider</button>
</form>
Use .valid() in submit function
$('#form').submit(function() {
var isValid=$("#form").valid();
if (isValid) { //If there is no validation error
var c = confirm("Click OK to continue?");
if(c){
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
}
}
else {
alert('form is not valid');
}
});
</script>

How to login users using ajax and php?

I've added an ajax jquery function to do a much nicer login, but it still doesn't work. What am I doing wrong? Thanks.
form_log.php withing heads:
<script type="text/javascript">
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
type: "POST",
url: 'login.php',
data: {
username: $("#username").val(), //id
password: $("#password").val()
},
success: function(data)
{
if (data === 'Correct') {
window.location.replace('index.php');
}
else {
alert(data);
}
}
});
});
});
</script>
And the in form_log.php's html bodies:
<form id="myform">
<label for="username">Username</label>
<input type="text" id="username" value="waqmaz#gmail.com" />
<label for="password">Password</label>
<input type="text" id="password" value="Lol123" />
<input type="submit" id="login" value="Login"/>
</form>
Now login.php:
<?php
session_start();
require("funkcje_bazy.php");
//require('fff.php');
$lacz = lacz_bd();
$nazwa_uz_l = $_POST['username'];//nazwa_uz_l
$haslo_l = $_POST['password']; //haslo_l
$wynik = $lacz->query("SELECT * FROM uzytkownicy WHERE email='".$nazwa_uz_l."' AND haslo = '".$haslo_l."' AND aktywacja IS NULL ");
if($wynik->num_rows>0) {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
echo ('Correct');
}
else
{
echo 'Incorrect username/password';
}
?>
At the top of all these 2 files I have session_start(); icluding index.php.
The login doesn't work. When I click input submit, nothing happens. I am new to an jquery ajax. I check the correct answers, thanks.
Try to prevent the default action of the submit button by using event.preventDefault(), meaning block the post back which is about to happen,
$('#myform').submit(function(e) {
e.preventDefault();
.
.
//rest of your code.
An alternative is to use:
$('#login').click(function() {

Categories

Resources