Clear input text with javascript - javascript

How can I clear the input tag with javascript in this code?
I've tested many ways but could not.
<div id="center">
<p id="alert">FILL FIELDS</p>
<input id="name"/>
<input id="family"/><br />
<button onclick="SaveData()" type="submit">INSERT</button>
</div>
<script>
function SaveData() {
var name = $('#name').val();
var family = $('#family').val();
$.ajax({
type: "POST",
url: "server.php?p=add",
data: "fn="+name+"&ln="+family,
success: function(msg){
document.getElementById('alert').innerHTML = "SUCCESS SAVE";
}
});
}
</script>

To clear the name input, you can use jquery .val() function to reset to empty string:
$('#name').val('');

Yes, do it in your success function:
success: function(msg){
document.getElementById('alert').innerHTML = "SUCCESS SAVE";
$('#name').val(''); // set the value to blank with empty quotes
$('#family').val('');
}

Related

why AJAX redirects to the new page in PHP

I have a form:
<form class="searchForm">
<div class="box_style_1">
<h4><?= Yii::t("common", "Age"); ?></h4>
<?
echo '<b class="badge">3</b> ' . Slider::widget([
'name'=>'age',
'value'=>'250,650',
'sliderColor'=>Slider::TYPE_GREY,
'pluginOptions'=>[
'min'=>3,
'max'=>21,
'step'=>1,
'range'=>true
],
]) . ' <b class="badge">21</b>';
?>
<br /><br />
<input type="submit" value="Search" class="searchByAge"/>
<br /><br />
</div>
</form>
And want to show the result in console.log:
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
})
and that's my AJAX code. But when I click on Search button it redirects me to the new page and nothing in the console log. I do not know what is wrong in my code.
I return a JSON from the '/age/min_age/max_age' page, but the result shows in the new page.
How can I fix this problem?
change code to below. change input type submit to button
<input type="button" value="Search" class="searchByAge"/>
also wrap your code in $(document).ready();
Make sure to add jQuery library from correct path.
$(document).ready(function(){
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
});
replace your code
$('.searchByAge').on('click', function(e){
e.preventDefault();
with this
$('form.searchForm').on('submit', function(e){
e.preventDefault();
on first code you are preventing your click event instead of submit event thats why form is still submitting

Making textfield greyed out/disabled after saving data to database (ajax/php)

I have the following code:
<input type="text" value="name" id="name" />
<input type="button" id="button" value="Click Me" /></p>
<script>
$( "#button" ).click(function() {
var text = $("#name").val();
$.ajax({
url: 'page.php',
type: "POST",
data: {
text: text
},
success: function(response) {
alert("inserted");
}
});
});
</script>
and everything works fine now, but after clicking the button I get the popup msg (alert) saying the data was inserted. Instead of that I want to grey out the textfield - is it possible?
You can make the text input disabled using prop(). This will also grey it out in most browsers. Try this:
success: function(response) {
$('#name').prop('disabled', true);
}
function disable(){
$("#name").prop("disabled",true);
}
Try this way after ajax success callback,
$("#name").attr('readonly', 'true'); // mark it as read only
$("#name").css('background-color' , '#DEDEDE'); // change the background color

Using JQuery and AJAX to pass data to a PHP script

I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?
HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
JQuery won't serialize a button, use a hidden field instead
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id
Instead of this
$("#friend-request-buttons")
It should be this
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this...
<form id="friend-send">
<button>
tags are not supported by serialize https://api.jquery.com/serialize/
You would need to use an input of some kind. A hidden one would work.
Don't use serialize, create the input data yourself:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data: argument to $.ajax, jQuery will serialize it automatically.
This answer would be if you are set on using the button alone
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});

How to disable an element based on ajax error respond

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

Submitting forms using jquery $.ajax - oly the first submits

I've got a problem with submitting AJAX forms - using this tutorial.
My forms are in div#upform and when I'm trying to submit any of them via $.ajax it submits only the first one, here's the code:
$(function() {
$(".button").click(function() {
var txt = $(".tekst#test").val();
var dataString = 'tekst='+ tekscior;
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
$('#upform').html("<div id='message'></div>");
$('#message').html("<h2>described!</h2>")
.append("<p>thanks!</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='http://artivia-dev2/i/check.png' />");
});
}
});
return false;
});
});
AND Here are my forms:
<!-- ONLY THIS ONE IS SUBMITTED, EVEN WHEN I'M SUBMITTING THE SECOND ONE! -->
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
##UPDATE
Problem, when I submit one form - it's great - but when after this one submit I want to submit the second - the data is submitted correctly, but the success messages are refreshed in both forms, that's the fix, which I've triend to use, but it doesn't work:
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
var mess = $(this).closest('.message');
mess.html("<h2>Described</h2>")
.append("<p>Thanks!</p>")
.hide()
.fadeIn(1500, function() {
mess.append("<img id='checkmark' src='http://ar-dev2/i/check.png' />");
});
}
});
First, you should not use same id to multiple element. Instead of that you may use class or name or data attribute.
$(".button").click(function() {
var upform = $(this).closest('.upform'); // keep reference of upform
var txt = $(this).prev(".tekst").val(); // this will retrieve the value of input
// nearest to the button
var dataString = 'tekst='+ tekscior;
......
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
upform.html();
.....
}
});
});
Problem with var txt = $(".tekst#test"); selector:
It has been started searching from top and when it found a match it stop journey and return the value and you always get the value of first one. If you use
var txt = $(".tekst"); without id, you will face the same problem.
IDs are singular. You can not have the same id on the page more than once!
If you want to repeat identifiers, use name.
You should be using different ids for both the forms. Both your forms have the same id upform

Categories