disable fields if query is true - javascript

I need to disable fields of a modal if the result of a query is true, I have an idea of ​​how to do it, but I have not been able to specify it, I would appreciate any help or correction within my code:
controller
function evaluarTrabajador(){
$this->load->model("Prwtrabajadores_model");
$idTrabajador = $this->input->post('idEdit');
$this->Prwtrabajadores_model->revisaCertificados($idTrabajador);
}
model
function revisaCertificados($idTrabajador){
return $this->db
->select("a.idprw_estadocertificado")
->from("prw_estadocertificado as a")
->join($this->schemaEmpresas."wom_trabajadores as b")
->where("b.idwom_trabajadores", $idTrabajador)
->where("a.idprw_estadocertificado = 1 || 4 || 5")
->get()->result();
$query = result();
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and the JS from view, now the JS show the data from database, but need block the text fields if the query is true
$(".editarT").on("click", function(id){
var id = $(this).data("idtra");
$.ajax({
url : "<?php echo site_url('/contratista/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('input[name="idEdit"]').val(data[0].idwom_trabajadores);
$('input[name="rutEdit"]').val(data[0].rut);
$('input[name="nombresEdit"]').val(data[0].nombres);
$('input[name="appEdit"]').val(data[0].apellido_paterno);
$('input[name="apmEdit"]').val(data[0].apellido_materno);
$('input[name="cargoEdit"]').val(data[0].cargo);
$('input[name="telefonoEdit"]').val(data[0].telefono);
$('input[name="mutualEdit"]').val(data[0].mutual);
$('#form-modal-editar-trabajador').modal({show:true});
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error obteniendo datos');
}
});
});

Is this what you want?
$(".editarT").on("click", function(id){
var id = $(this).data("idtra");
$.ajax({
url : "<?php echo site_url('/contratista/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#form-modal-editar-trabajador').modal({show:true});
if(data.length > 0){
$('input[name="idEdit"]').val(data[0].idwom_trabajadores).prop('disabled', true);
$('input[name="rutEdit"]').val(data[0].rut).prop('disabled', true);
$('input[name="nombresEdit"]').val(data[0].nombres).prop('disabled', true);
$('input[name="appEdit"]').val(data[0].apellido_paterno).prop('disabled', true);
$('input[name="apmEdit"]').val(data[0].apellido_materno).prop('disabled', true);
$('input[name="cargoEdit"]').val(data[0].cargo).prop('disabled', true);
$('input[name="telefonoEdit"]').val(data[0].telefono).prop('disabled', true);
$('input[name="mutualEdit"]').val(data[0].mutual).prop('disabled', true);
}
else{
$('input[name="idEdit"]').val('').prop('disabled', false);
$('input[name="rutEdit"]').val('').prop('disabled', false);
$('input[name="nombresEdit"]').val('').prop('disabled', false);
$('input[name="appEdit"]').val('').prop('disabled', false);
$('input[name="apmEdit"]').val('').prop('disabled', false);
$('input[name="cargoEdit"]').val('').prop('disabled', false);
$('input[name="telefonoEdit"]').val('').prop('disabled', false);
$('input[name="mutualEdit"]').val('').prop('disabled', false);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error obteniendo datos');
}
});
});

Related

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

javascript works on localhost but fails on hosting server

When i click on add-to-basket button i see an error which appears in my browser console saying :
Here is my basket.js file :
$(document).ready(function() {
initBinds();
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
function removeFromBasket() {
var item = $(this).attr('rel');
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_remove.php',
dataType: 'html',
data: ({ id: item }),
success: function() {
refreshBigBasket();
refreshSmallBasket();
},
error: function() {
alert('An error has occurred');
}
});
}
function refreshSmallBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("An error has occurred");
}
});
}
function refreshBigBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_view.php',
dataType: 'html',
success: function(data) {
$('#big_basket').html(data);
initBinds();
},
error: function(data) {
alert('An error has occurred');
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove from basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add to basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("An error has occurred");
}
});
return false;
});
}
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
// proceed to paypal
if ($('.paypal').length > 0) {
$('.paypal').click(function() {
var token = $(this).attr('id');
var image = "<div style=\"text-align:center\">";
image = image + "<img src=\"/images/loadinfo.net.gif\"";
image = image + " alt=\"Proceeding to PayPal\" />";
image = image + "<br />Please wait while we are redirecting you to PayPal...";
image = image + "</div><div id=\"frm_pp\"></div>";
$('#big_basket').fadeOut(200, function() {
$(this).html(image).fadeIn(200, function() {
send2PP(token);
});
});
});
}
function send2PP(token) {
$.ajax({
type: 'POST',
url: '/mod/paypal.php',
data: ({ token : token }),
dataType: 'html',
success: function(data) {
$('#frm_pp').html(data);
// submit form automatically
$('#frm_paypal').submit();
},
error: function() {
alert('An error has occurred');
}
});
});
I tried to resolve it but couldn't find a proper solution.
Help me with this, I cannot understand the cause of this error.
This is mainly due to Rules of Origins (CORS), for some reason the javascript(browser) sees the request as not residing in the same server. And the reason for that, I believe, is because /home/u919084925/public_html/mod/basket.php is not seen as a valid url on the server, it should start with http://{hostname}/{path}.
It looks like your ajax url is totally wrong and the browser interpret that is cross origin ajax request. Please simply check in browser's address bar if your ajax provided urls are valid.

ajax jquery always running Error;

Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.

Ajax success function not working in jquery mobile

I am trying to validate a basic login form with username and password fields. I need to validate username and password from check.php ajax page. There is no problem in ajax request and response. I am getting proper response from ajax page. But Ajax success function is not working properly.
ajaxrequest.html
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Here i have added my ajax page. This page only validates posted username and password. Finally it returns json object. What am i doing wrong?
serverurl/check.php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
if(isset($_POST['formData']) && isset($_POST['action']) && $_POST['action'] == 'login'){
parse_str($_POST['formData'],$searchArray);
$uname = "arun";
$pwd = "welcome";
$resultArray = array();
if($uname == $searchArray['username'] && $pwd == $searchArray['password'])
{
$resultArray['uname'] = $searchArray['username'];
$resultArray['pwd'] = $searchArray['password'];
$resultArray['status'] = 'success';
}else{
$resultArray['status'] = 'failed';
}
echo json_encode($resultArray);
}
Your code should be
success: function (result) {
console.log("Ajax response");
//don't do this
//res = JSON.stringify(result);
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
After JSON.stringify you are accessing like stringJson.status this will not work. it mast have "parsed" "json object" not stringify.
Don't need to convert your JSON to String.
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
//Don't need to converting JSON to String
//res = JSON.stringify(result);
//directly use result
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
} else {
alert('Fill all fields');
}
return false;
});
});
Your AJAX call is perfect but datatype is not declared in ajax
Try with jSON OR JSONP. You will get success.
$.ajax({
url : 'serverurl/check.php',
type: 'post',
dataType: "json", OR "jsonp",
async: false,
data: {action : 'login', formData : $('#check-user').serialize()},
beforeSend: function() {
$.mobile.loading(true);
alert("beforesend");
},
complete: function() {
$.mobile.loading(false);
alert("complete");
},
success: function (result) {
console.log("Ajax response");
alert(JSON.stringify(result)); // Check response in alert then parse according to that
res = JSON.stringify(result);
if(res.status == "success"){
resultObject.formSubmitionResult = res.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
Under some circumstances your server might not return the response correctly. Have you tried to handle the actual response code (e.g. if your server returns 200) like this:
$.ajax({
url : 'serverurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
....
statusCode: {
200: function (response) {
// do your stuff here
}
}
});

$.ajax not working properly

I want to get a value from php file like below, I can see loader.gif but I cant see avaiable.png or not_avaiable.png Why?
$(document).ready(function()//When the dom is ready
{
$("#inputEmail").change(function()
{ //if theres a change in the username textbox
var inputEmail = $("#inputEmail").val();//Get the value in the username textbox
if (inputEmail.length > 2)//if the lenght greater than 3 characters
{
$("#availability_status").html('<img src="images/loader.gif" align="absmiddle"> Checking availability...');
//Add a loading image in the span id="availability_status"
$.ajax({//Make the Ajax Request
type: "POST",
url: "check_email.php", //file name
data: "inputEmail=" + inputEmail, //data
success: function(server_response) {
$("#availability_status").ajaxComplete(function(event, request) {
if (server_response === '0')//if ajax_check_username.php return value "0"
{
$("#availability_status").html('<img src="images/available.png" align="absmiddle">Yes');
$("#submit_button").css("display", "initial");
$("#inputEmail").attr('data-email','0');
//add this image to the span with id "availability_status"
}
else if (server_response === '1')//if it returns "1"
{
$("#availability_status").html('<img src="images/not_available.png" align="absmiddle">No');
$("#submit_button").css("display", "none");
}
});
}
});
}
else {
$("#availability_status").html('<font color="#cc0000">Username too short</font>');
//if in case the username is less than or equal 3 characters only
}
return false;
});
});
check_email.php is
<?php
echo '1';
?>
if jquery or divs have problem I can't see loader.gif in my div? Where is the problem?
You shouldn't need to use ajaxComplete() when you're inside of the success() method for your AJAX call. Just do your stuff right in the success() method like this:
$.ajax({
type: "POST",
url: "check_email.php",
timeout: 9000,
data: "inputEmail=" + inputEmail,
success: function(server_response) {
if (server_response === '0') {
$("#availability_status").html(
'<img src="images/available.png" align="absmiddle">Geçerli'
);
$("#submit_button").css("display", "initial");
$("#inputEmail").attr('data-email','0');
} else if (server_response === '1') {
$("#availability_status").html(
'<img src="images/not_available.png" align="absmiddle">Geçersiz'
);
$("#submit_button").css("display", "none");
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
Also it could be timing out so I added timeout there.
Try like this:
$.ajax({
type: "POST",
url: base_url,
data: your data,
dataType: "json",
success: function(data)
{
}
});
try this one
formData = {
inputEmail: $("#inputEmail")
}
$.ajax({
type: "POST",
url: "check_email.php",
data: formData,
success: function(server_response) {
$("#availability_status").ajaxComplete(function(event, request) {
if (server_response === '0') //if ajax_check_username.php return value "0"
{
$("#availability_status").html('<img src="images/available.png" align="absmiddle">Yes');
$("#submit_button").css("display", "initial");
$("#inputEmail").attr('data-email', '0');
//add this image to the span with id "availability_status"
} else if (server_response === '1') //if it returns "1"
{
$("#availability_status").html('<img src="images/not_available.png" align="absmiddle">No');
$("#submit_button").css("display", "none");
}
});
}
});

Categories

Resources