Disabled submit button if inputs are empty - javascript

What I have here is a ajax checking the availability of information in database. But what my problem is I want to disabled the submit button if the others inputs/textboxes are empty. I add the disable function in my ajax but when one of the textbox has a value the disabled isn't working. Any help will appreciate.
Index.php
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="text"]').change(function()
{
var pr = $("#pr").val();
var msgbox = $("#status");
var txtbxs = $('.inputs').val();
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK' && txtbxs !== '')
{
msgbox.html('<img src="css/available.png" align="absmiddle">');
$("#save").prop("disabled",false);
}
else
{
$("#save").prop("disabled",true);
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
<tr>
<td>PR #</td>
<td><input type="text" name="pr" id="pr" autocomplete="off"></td>
</tr>
<tr>
<td></td>
<td><span id="status"></span></td>
</tr>
<tr>
<td>Date1</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<tr>
<td>Date2</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<input type="button" value="Save" id="save">
Check_ajax.php
<?php
if(isset($_POST['pr']))
{
$pr = $_POST['pr'];
$sql = $mysqli->query("select id, pr from pr_list where pr='$pr'");
if(($sql->num_rows)>= 1)
{
echo '<STRONG>'.$pr.'</STRONG> is already in use.';
}
elseif($pr == '') {
echo 'Fund is Empty';
}
else
{
echo 'OK';
}
}
?>

ajaxcomplete isn't really the right thing to use here, ajaxcomplete adds an event listener for every ajax call you make but you only need to check the message when this ajax call is successful.
It would still work though but for the msg variable having no scope whithin the ajaxcomplete function. Here is one way I would do it.
<script type="text/javascript">
$(document).ready(function()
{
// I've moved these variables here to give them global-ish scope
// I've also added a variable to assign your save button to
var msgbox = $("#status"),
saveButton = $("#save");
$('input[type="text"]').change(function()
{
var pr = $("#pr").val(),
txtbxs = $('.inputs'),
empty = true;
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
// loop through the txtbxs and check for emptiness :)
$.each(txtbxs, function(key, box) {
if (box.val() != "") {
empty = false;
} else {
empty = true;
}
});
if(msg == 'OK' && !empty) {
msgbox.html('<img src="css/available.png" align="absmiddle">');
saveButton.prop("disabled",false);
} else {
saveButton.prop("disabled",true);
msgbox.html(msg);
}
} // END OF SUCCESS FUNCTION
});// END OF AJAX CALL
});
});// END OF DOCUMENT READY
Another thing I'm not sure about is that when you do your if statement and have txtbxs != '' are you trying to check that the boxes aren't empty or that the variable is not empty.
The way you have it set that the you are checking for the variable to be empty, if you are wanting to check that the txtbxs have a value then you want a some different code

Related

Ajax not Writing to Database

I have an HTML form that I'm trying to read data from and write into a database. A sample of the HTML for the form is shown below:
<div id="form">
<div class="container-tabby1">
<div class="wrap-tabby1">
<form class="tabby1-form validate-form">
<span class="tabby1-form-title">
New Form
</span>
<div class="wrap-inputtabby validate-input bg1" data-validate="Internal Error">
<span class="label-inputtabby">Change Request Number</span>
<input id="ChangeRequestNo" class="inputtabby" type="text" name="ChangeRequestNo" onload="onLoad" readonly>
</div>
<div class="container-contact100-form-btn">
<input id="submitRequest" type="button" class="contacttabby-form-btn" value="Submit Request" onclick="SaveChangeRequest()"/>
</div>
The ajax used to write this to the database is as follows:
function SaveChangeRequest() {
var o = form.getData();
var errorMsg = "";
msg = mini.loading("Submit...");
var jsonform = mini.encode(o);
debugger;
$.ajax({
url: urlCR,
type: "post",
data: { CR: jsonCR },
cache: false,
success: function (text) {
debugger;
if (text != null && text != '') {
mini.hideMessageBox(msg);
onOk();
}
else {
jAlert("Submit failed", "Error Message");
}
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
})
Every time I attempt to submit to the database I get the "Submit failed" error message. I have another form as shown below that works perfectly fine:
<div id="form" style="margin-left:5px;margin-right:5px;">
<table width="100%;" align="center">
<tr>
<td width="100px;"><label>Applicant:</label></td>
<td width="300px;"><input id="ApplicantEmail" name="ApplicantEmail" class="mini-textbox" allowinput="false" style="width: 290px;" /></td>
<td align="center">
<input type="button" class="searchsubmit" value="Submit" onclick="SaveForm()" style="width:120px;" />
<script type="text/javascript">
mini.parse();
SecurityLog_PageLoad();
var urlPersonInfo = "data/AjaxSecurityService.aspx?method=Sec_CurUserLoginInfo";
var urlFormGetItem = "Data/ajaxservice.aspx?method=CSC_Form_GetWholeFormo&FormID=";
var urlFormUpdateWithNotice = "Data/ajaxService.aspx?method=CSC_Form_UpdateChanges";
var form = new mini.Form("#form");
var searchGrid = mini.get("dgSearchResult");
var applyGrid = mini.get("dgApplyResult")
function SaveForm() {
var o = form.getData();
form.validate();
if (form.isValid() == false) return;
var errMsg = '';
if (o.RequestComments == null || o.RequestComments == '')
errMsg=".Justification is empty.\n";
if (applyGrid.data.length < 1)
errMsg+= ".At least apply one report before you submit.\n";
if (errMsg != '')
{
jAlert(errMsg, "Validate Error");
return;
}
$.ajax({
url: urlFormUpdateWithNotice,
type: "post",
data: { dataForm: jsonClaim, dataList: jsonList },
cache: false,
success: function (text) {
var impactID = mini.decode(text);
if (impactID != null && impactID != "") {
SecurityLog_Submit('Submit',impactID);
CloseWindow("ok");
};
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
});
</script>
Why does the latter form work while the first form does not?
This is not a answer as such at this stage, but a few points of note that might help reach an answer:
the code that displays the "Submit failed" message is actually in the success response section. It shows the message if there is a non-null, non-empty string returned by the AJAX call. It would help if the string was output to help debug if it's an actual failure to save the data, or not
following on from the above, check if the data submitted has been saved or not - that will help establish what is actually happening
In the second form, we can see the URL (urlFormUpdateWithNotice) but in the first we can't, so it's hard to tell if that is a problem (e.g. there could be a typo in the URL)
Ideally you need to include as much detail as possible, including any critical data, so that diagnosing the problem is easier and quicker.
In any case the best place to start is to see what text is in success: function (text) {... and take it from there.

laravel update status to 0 or 1 when button is toggled in a single row using ajax

I'm relatively new to Laravel. I'm trying to update the 'is_active' column in mysql when the button is toggled without reloading the page. Each row of the table will have the button. I'm also trying to display a pop out message when button is toggled by having the same effect as bootstrap delete confirmation modal.
What i have up to until now is making the toggle button work, but when i tried to toggle the button, there is no changes made to the database. I'm thinking whether should i use a form for the checkbox
UPDATED
This is how my button looks like in html
#foreach($system_functions as $function)
<input type="hidden" id="id_input" value="{{$function->id}}" >
#if($function->group_id == 1)
<tr>
<td>{!! $function->name !!}</td>
<td><input class="toggle_status" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" value="on" data-toggle="toggle"></td>
</tr>
#endif
#endforeach
I also have an update function in controller
public function update(Request $request, $id)
{
$function=SystemFunction::where('id',$id)->first();
if($request->get('is_active')==='on'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]);
return redirect('admin/system-functions')->with('status','SUCCESSFUL');
}
and i'm calling this in my route
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'staff'), function () {
Route::post('/system-functions', 'SystemFunctionController#update')->name('system-functions');
}
and my js looks like this in my view
#section('script')
<script type="text/javascript">
$(document).ajaxStop(function () {
$('.toggle_status').on('click', function (e) {
var is_checked = false
if ($(this).is(':checked')) {
is_checked = true;
}
$.ajax({
type: 'POST',
url: '{{ route('admin.system-functions') }}', // use proper route to system-functions here
async: true,
data: {
is_checked: is_checked,
id: {{ $function->id }}
},
success: function (result) {
alert('Toggle successfull'); // use proper alert message here
e.stopImmediatePropagation();
return false;
}
});
});
});
</script>
#endsection
console error
console error
html
<tr>
<td>{!! $function->id !!}</td>
<td>{!! $function->name !!}</td>
<td><input class="togglefunction" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" value="on" data-toggle="toggle" data-fid="{{$function->id}}"></td>
</tr>
Route
Route::post('/system-functions', 'SystemFunctionController#update')->name('update-system-function');
In Model
public function toggleIsActive()
{
$this->is_active= !$this->is_active;
return $this;
}
then use like
public function update(Request $request)
{
$function=SystemFunction::where('id',$request->id)->first();
$function->toggleIsActive()->save();
return redirect('admin/system-functions')->with('status','successful');
}
javascript :
$('.togglefunction').on('click',function(){
//send value by ajax to server
$.ajax({
url:'{{route('update-system-function')}}',
type:'GET',
data:"{id:$(this).data('fid')}"
}).done(function(response) {
//success
}).fail(function(error){
//failure
})
});
You will have to do ajax call on each click on a checkbox to update database record.
Your js code will be like this:
$('#somecheckbox').on('click',function(){
//check the checkbox status
var is_checked = false
if($(this).is(':checked')){
is_checked = true;
}
//send value by ajax to server
$.ajax({
url:'url_here',
type:'GET',
data:"{is_checked:is_checked}"
}).done(function(response) {
//success
}).fail(function(error){
//failure
})
});
I Like javascript code of #DejavuGuy's Answers to imporove backend code I would like to suggest you to use something like this:
public function update($value,$id)
{
$function=SystemFunction::where('id',$id)->first();
$function->is_active = !$function->is_active;
$function->save();
echo 'Successfully!'
}
Good luck
$(document).ready(function() {
$("#is_active").click(function() {
var checkBoxe = $("#is_active");
checkBoxe.prop("checked", !checkBoxe.prop("checked"));
});
var checkedValue = $('#is_active').val();
var id = $('#id_input').val();
var xhr = new XMLHttpRequest();
xhr.open("GET", '{{url('system-functions')}}'+'/'+checkedValue+'/'+id, true);
xhr.setRequestHeader('Content-Type', '');
xhr.send();
xhr.onload = function() {
alert(this.responseText);
}
});
and your route here...
Route::get('/system-functions/{value}/{id}', 'SystemFunctionController#update');
your server method here...
public function update($value,$id)
{
$function=SystemFunction::where('id',$id)->first();
if($value==='checked'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]);
echo 'Successfully!'
}

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

How to get checkbox value and send that to backend?

This is front end,
<div class="uk-width-1-4 ">
<table class="uk-table uk-table-striped uk-table-hover" id="tabledata">
<thead>
<tr>
<th><input type="checkbox" ></th>
<th>Site ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="chkall" value="<%= d.siteid%>">
</td>
<td><%=d.siteid%></td>
</tr>
<% });
} %>
</tbody>
</table>
</div>
This is backend,
var user_id=req.query.user_id;
var siteid=req.query.chkall;
console.log("chkall =="+siteid);
sql="UPDATE site SET userid='"+user_id+"' WHERE siteid IN('"+siteid+"')";
}
getSQLData(sql, function(resultsets){
console.log("user...sql"+sql);
userresults = resultsets;
});
You can use it like this:
$("input[type='checkbox']").val();
Hope will help you.
If you are doing form submit, and if the check-box un-checked the false value will not go to the back-end. You should have some hidden value if check box un-checked.
If it is ajax call, you can get checkbox value as like below
$("input[type='checkbox']").val();
or
$("#checkboxid").val();
If you submit form then write name tag. And if you send data from ajax then get value by element id then send to server.
You do like this..
var chk = document.getElementById(checkboxid).checked;
if (chk == true) {
var chkval=$("#checkboxid").val();
}
If you have in list then do loop and add to a global variable and use that variable.
//check box
<asp:CheckBox ID="chkpermission" runat="server" onclick="checking(this.id);" Checked='<%# Convert.ToBoolean(Eval("permission")) %>' />
<script type="text/javascript">
function checking(id) {
$('#ctl00_ContentPlaceHolder1_lblresponce').val('');
if (id) {
ids = id.split('_');
var chkval = document.getElementById(id).checked;
var TitleId = "ctl00_ContentPlaceHolder1_grdpermissions_" + ids[3] + "_hdntitleid"; //here i am getting the value from the grid
var pagePath = window.location.pathname;
var param = JSON.stringify({ "TitleId": itleId,"chkval":chkval });
$.ajax({
type: "POST",
url: pagePath + "/updatevalue",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var result = data.d;
$('#ctl00_ContentPlaceHolder1_lblresponce').text('Updated successfully');
}
},
error: function () {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
}
</script>
in the back end code
[WebMethod]
public static Boolean updatevalue( string TitleId, string chkval)
{
Boolean flag = false;
if ( TitleId != "" && chkval !="")
{
//Update your your query here with single id...
flag=true;
// return flag if updated
}
return flag;
}
I hope it works in your case.

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}

Categories

Resources