How to disable an element based on ajax error respond - javascript

I've form with single input field name and with jquery i'm checking the name availability before submit and it gives either error message if didn't passed the check or gives message correct if passed the check out.
Now my question i wonder if this code can be adjusted so that it disable submit in case it didn't passed the availability check
or whatever so that it prevent clicking on submit button if didn't passed availability check.
I'm using the following
Form Code
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#name").change(function() {
var usr = $("#name").val();
if(usr.length >= 4){
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "name="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK'){
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' correct');
}else{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}else{
$("#status").html('<font color="red">The name should have at least 4 characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
});
});
</SCRIPT>
<div id='myform'>
Name <input type="text" name="name" id="name"><div id="status"></div>
<br />
<input id="submit" type="submit" name="Submit" value="Submit">
</div>
~ thanks for help

You can simply disable the submit input element:
$("#submit").prop('disabled', true);
Example

Related

Classic ASP + Ajax Form - success function not working, complete is ok

With Ajax and JS/Jquery I'm trying to send a simple Contact form to a Classic ASP (aspemail) and sent a messagem from a page without reload.
<form id="form-submit" action="ASPEmail.asp" method="post">
Name<br>
<input id="name" type="text"><br>
E-mail<br>
<input id="email" type="text"><br>
Message:<br>
<textarea id="msg"></textarea><br>
<input type="submit" id="btn" value="SEND">
<img src="loading.gif" class="loading">
</form>
My ASPEMAIL.ASP is only test asp and I write only:
<%
Response.Write("ok")
%>
And my JQuery Script:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(function() {
$("#form-submit").submit(function() {
var data = $(this).serialize(),
action = $(this).attr("action"),
method = $(this).attr("method");
$(".loading").show(); // show loading div
$.ajax({
url: action,
type: method,
data: data,
success: function(data) {
if(data === "ok")
{
document.location = "final.asp";
}
},
error: function(err) {
// there was something not right...
},
complete: function() {
$(".loading").hide(); // hide the loading
}
});
return false; // don't let the form be submitted
});
});
</script>
I put a redirect on success to test (My objective is a message only) - but nothing happens.
But after send the "LOADING" appears on screen and hide and then the submit and "complete" is working.
Any idea what is wrong?
you have 2 variables named data, try using a different variable here, as I believe you're "confusing" javascript here :)
success: function(dataReturned) {
if(dataReturned === "ok")
{
document.location = "final.asp";
}
},

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

Jquery validation plugin does not send POST data

Update 2: I found out what was wrong! There was a 301 redirect in the .htaccess file. I will post it as an answer once I am allowed to (users under 10 rep have to wait 8 hours).
Update: I have taken Barmar's suggestion and checked the network tab (a tab I'm not too familiar with) and noticed I am receiving a 301 from handle.php See screenshot. I am going to do some searching and post my results.
Original Post: I am using the JQuery validation plugin to validate and send form data via ajax. The problem isn't that the data is being sent, but the form handler is saying there are no elements in the $_POST array. I have tested a few different methods to send ajax, and the data sends, but the form handler does not see any $_POST[] values.
Note: I have to use the JQuery validation plugin so it has to be handled by .validate.submitHandler(). Any $(form).on() won't suffice.
html + js (index.php)
<form action="handle.php" class="sky-form sky-form-modal" id="sky-form-modal" method=
"post" name="sky-form-modal">
<label class="input">
<input name="name" placeholder="Name" type=
"text">
</label>
<label class="input"><input name="company" placeholder="Company" type=
"text">
</label>
<footer>
<button class="button" type="submit">Send request</button>
<div class="progress"></div>
</footer>
</form>
<script>
$("#sky-form-modal").validate({
submitHandler: function(form) {
var $form = $("#sky-form-modal"); //being explicit for testing
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
request = $.ajax({
url: "handle.php",
type: "POST",
data: serializedData
});
console.log('data: ' + serializedData);
request.done(function(response, textStatus, jqXHR) {
console.log("Response: " + response);
});
},
});
</script>
handle.php:
<?php
if(isset($_POST['name'])) {
echo 'we got it';
} else {
echo 'name not set';
}
?>
Okay, so it seems like everything works, check out the console.log after I fill in the username and leave the company blank:
data: name=testtest&company=
Response: name not set
As you can see, serialize works and grabs all the info, but when handled by handle.php it tells me that the $_POST[] is empty. Looping through it on handle.php proves it:
foreach($_POST as $key=>$value) {
echo "$key: $value
\n";
}
Which doesn't return at all.
I have also tried ajaxSubmit() and form.submit() but I get the same exact results.
This one looks right to me, because I have searched and searched stackoverflow and came across that most of the problems with this is including the 'name' attribute on the input tags, which is already done.
Thanks in advance!!
My issue was irrelevant to my code and ended being a few declarations in the .htaccess. It was redirecting me from a .php file to a directory (for prettier URLS). Now, this is a common technique so:
if you are working on someone else's project and your URL's aren't standard with a file extension, check the .htaccess!
Page.html or .php
<form action="/" id="sky-form-modal" method=
"post" name="sky-form-modal">
<input name="name" placeholder="Name" type="text">
<input name="company" placeholder="Company" type="text">
<button class="button" type="submit">Send request</button>
</form>
<div id="result"></div>
<script>
var request;
$("#sky-form-modal").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, input");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "handle.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
$("#result").html(response);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
handle.php
<?php
foreach ($_POST as $key => $value) {
echo "POST Key: '$key', Value: '$value'<br>";
}
?>
I removed your labels and classes for the simple look of the form.
i Guess you missed '(' after validation
$("#sky-form-modal").validate {
$("#sky-form-modal").validate ({

Form Post data using Ajax and jquery

I have a Form
<script type="text/javascript" src="result.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<form name="form" method="POST" id="form">
<input type="text" value="" id="htno" name="htno" Maxlength="12" style="width:165px;" class="bodytext"></input>
<input type="button" value="Submit">
</form>
<div id="result" class="result"></div>
And result.js file is
$("#form").submit(function (event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "url",
type: "post",
data: "htno=" + htno + "&code=2132",
success: function () {
alert("success");
$("#result").html('submitted successfully');
},
error: function () {
alert("failure");
$("#result").html('there is error while submit');
}
});
});
htno is the value the user enters through form
Data to be posted is htno & code
i am unable to get output using this, please can u tell me the fault . . . .
You should know that a form is submitted when the input type is submit.In your code change the type of button to submit.
just change the part
<input type="button" value="Submit" >
to
<input type="submit" value="Submit" >
and in your result.js remove this line
event.preventDefault();
because this line prevent your form from submitting without any reason.
try changing your
$("#form").submit(function(event) {
event.preventDefault();
by
$(document).on('submit','#form',function(e) {
e.preventDefault();
alto, try to alert data
The page you are trying to connect use temporary tokens. You cannot do what you are looking for. You are not allowed to do it. Ask owner of site for kind of API access, he could make you a good price... { this topic should be closed! }

Form submit based on ajax response in jQuery

I'm using jQuery and am preventing the submission of a form, then based on an ajax response will submit the form. The problem I'm finding is that I often have to submit the form twice. The first time, it shows the loader, but it doesn't get seem to call any actions within the ajax's success function. If I click it a second time, it submits (if it's been validated). It also seems to work the first time, after I go through this. So if I try again, it'll work the first time. So maybe it's a cache issue? Here's the javascript I have:
$('#submit_zipcode_frm').submit(function(event){
event.preventDefault();
var self = this;
$(".loader img").show();
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
} else {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
$.ajax({
url: "/ajax/save/zipcode",
type: 'GET',
async: false,
cache: false,
dataType: 'html',
data: {zipcode: $('.zipcode_field').val()},
success: function(data) {
if(data == 'false'){
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}else{
self.submit();
getList();
}
}
});
});
and here's the markup:
<form id="submit_zipcode_frm" class="submit_zipcode" method="post" action="/go" target="_blank">
<div class="zipcode_container">
<span class="loader">
<img src="/assets/img/loader.gif" style="display: none;"/>
</span>
<input type="text" class="zip_input zipcode_field ghost" id="zipcode" name="zipcode" value="Enter your Zip"/>
<div class="start_btn">
<button type="submit">Submit</button>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</form>
Any suggestions or ideas would be really appreciated. Thank you!
EDIT:
Just to clarify the steps here:
User clicks the submit button
JavaScript show's the loader and validates the length and and type of the value entered
If that passes, an ajax lookup is used to truly validate it's a valid USPS zip code
If it is, the form is submitted and a function getList() is called
If it's not, error is thrown

Categories