auto submit form to a url if textfield is not empty - javascript

I'm trying to auto submit a form when the username column is not null. i've got my script down there but since i'm new to jquery, i've got it missed up and its not working
$(function() {
var $username = $('#username'),
if ($username != null){
$("#form1").submit,function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "http://mysample.com/ans.php",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
});
});

Try to use on change listener, like
$(document).on('change', '#input_id', function(e) {
$('form_selector').submit();
});
$(document).on('submit', 'form_selector', function(e) {
//Your ajax submit logic
});

If you want to do an AJAX submission, just call $.ajax in the if:
$(function() {
var $username = $("#username").val();
if ($username != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form1").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
}
});
You don't need to define a $("#form1").submit() handler for this.

Related

How to stop blur() event function to trigger twice?

I am trying to fetch the records from the database using blur function. There are two input fields where this function triggers. I have used different names, variables, javascript, controller using laravel to fetch the records. I am able to fetch the records through ajax and successfully opens the modal. When the modal pop ups when the blur function triggers, it also triggers the function for the second field.
I just want to trigger the modal according to the field, where the blur triggers and not to trigger twice.
//input field: originS
<script type="text/javascript">
$(document).ready(function(){
var origin = "";
var _token = "";
var ovalue = "";
$('#originS').blur(function(){
ovalue = "";
origin = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchOrigin') }}',
data:{origin:origin, _token:_token},
success: function(response){
if(response){
$("#originSelect").modal('show');
console.log(response);
$(".result").html(response);
$(document).on('change', '#selectSuburb', function () {
ovalue = $(this).val();
if ($(this).is(':checked')) {
$('#originS').val(ovalue);
$("#originSelect").modal('hide');
$this.die('blur');
}
});
$('#originSelect').on('hidden.bs.modal', function (e) {
if (ovalue == "") {
$("#originS").val('');
$(".result").html(response);
}
});
}
},
});
});
});
</script>
//input field: destS
</script>
<script type="text/javascript">
$(document).ready(function(){
var dest = "";
var _token = "";
var dvalue = "";
$('#destS').blur(function(){
dvalue = "";
dest = $(this).val();
_token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: '{{ route('pagescontroller.fetchdest') }}',
data:{dest:dest, _token:_token},
success: function(response){
if(response){
$("#destSelect").modal('show');
console.log(response);
$(".dresult").html(response);
$(document).on('change', '#selectSuburbdest', function () {
dvalue = $(this).val();
if ($(this).is(':checked')) {
$('#destS').val(dvalue);
$("#destSelect").modal('hide');
$this.die('blur');
}
});
$('#destSelect').on('hidden.bs.modal', function (e) {
if (dvalue == "") {
$("#destS").val('');
$(".dresult").html(response);
}
});
}
},
});
});
});
</script>

Show modal form before ajax cal and get data from it

I have an ajax function something like this:
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
beforeSend: function() {
$('#mform').show();
},
complete: function() {
$('#fountainG').hide();
},
success: function(data) {
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
}
I need to show some modal form to user, and get the data from it in ajax script. I tried to add show function to ajax beforeSend - but I do not understand how to wait for user form submit, and get data from modal form. Ajax function call in html: href="javascript:void(0)" onclick="javascript:foo(3800064420557,1,138)
You just need to re-arrange your logic. Instead of trying to show the modal "within" the ajax request, hold off on sending the ajax request until you have gotten the necessary data from the modal. Here is a rough outline, presuming that your modal element $('#mform') has a form in it with an id of myform which is the form you want to get data out of.
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
var modal = $('#mform');
var form = $('#myform', modal);
form.on( 'submit', function(){
$('mform').hide();
// make your ajax call here the same way, and inside the
// onsuccess for this ajax call you will then have access to both
// the results of your ajax call and the results of the form
// data from your modal.
$.ajax({ ... });
});
}
To get form data, you can try with below code
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
form_values = {}
$('mform').show();
$('#myForm').submit(function() {
var $inputs = $('#myForm :input');
$inputs.each(function() {
form_values[this.name] = $(this).val();
});
console.log("form data:", form_values)
// with form_values continue with your coding
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
success: function(data) {
$('mform').show();
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
});
}
Hope it will help you :)

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

Jquery send post form ajax not work

am try to send form ajax like this code
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#non").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { title: $('#mak').val(),meaning: $('#za').val()} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
it not alert success,and i check action after click button is ok
If jquery.min.js added. Then please ignore it. Else add it. To get action of <form> Use var action_url = form.attr('action');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: formData,
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
</script>
User's Requirement
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var val1 = $('#text1').val();
var val2 = $('#text2').val();
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: { text1: val1, text2: val2 },
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
Or, check Send FormData and String Data Together Through JQuery AJAX?
Additional
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var title_f = $('#mak').val();
var meaning_f = $('#za').val();
formData.append(title,title_f);
formData.append(meaning,meaning_f);
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: formData,
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
Why not attach your Handler directly to the Submit-Button & do something like this:
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#submitBtn").on("click", function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
// HERE IS THE PROBLEM... THE $(this) VARIABLE POINTS TO THE BUTTON, NOT FORM.
var $form = $( this ).parentsUntil("form").parent("form"),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { title: $('#mak').val(),meaning: $('#za').val()} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

Categories

Resources