In Sign up form, I wanna make Duplication check.
When is duplicated, A message is shown below the input box.
<div class="form-group">
<label class="col-md-2 control-label"><strong>Email</strong></label>
<div class="col-md-10">
<input type="email" class="form-control" name="usr_Email"
ng-model="usrEmail" ng-keyup="checkDuplicate()">
<span class="help-block"
ng-show="signupForm.$submitted || signupForm.usr_Email.$touched">
<div ng-show="?????" class="text-danger">is duplicated!</div>
</span>
</div>
</div>
to check duplicate, I got counting number from server
$scope.user.usrEmail = $scope.usrEmail;
var req = {
method: 'POST',
url: './api/v1/public/checkDuplication',
dataType: 'json',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: angular.toJson($scope.user)
};
$http(req).success(function(data, status, headers, config){
$log.debug($filter('json')(data));
if(data.number == 0){
???????
}
else{
???????????????
}
I'm very confused about what I should write in '???'
In advance, thanks!
Controller:
if(data.number == 0){
//If email id is duplicate, then show the message in UI
$scope.isDuplicate = true;
} else{
//If email id is not duplicate, then hide the message in UI
$scope.isDuplicate = false;
}
HTML:
<div ng-show="isDuplicate" class="text-danger">is duplicated!</div>
I have used isDuplicate scope variable to show the message.
Related
Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});
When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.
I have an input field and "Add" button to store. While clicking the Add button another input field with the same class name should be created. But before creating there is a validation check. But the validation is only hitting first time. There is no validation check in the second time.
Below is my Code.
$('#add').click(function (e) {
e.preventDefault();
if ($('.js-user-email').val()) {
debugger;
$("#divSpecificToUserError span").text("");
$('#divSpecificToUserError').addClass("d-none");
if (ValidateEmailformat($('.js-user-email').val())) {
//debugger;
$.ajax({
type: "POST",
url: "Stepup.aspx/Exists",
data: JSON.stringify({ emailId: $('.js-user-email').val() }),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response != null && response.d != null) {
var data = response.d;
if (data > 0) {
addDynamicTextboxes();
}
else {
$("#divSpecificToUserError span").text("not a valid user");
$('#divSpecificToUserError').removeClass("d-none");
}
}
},
failure: function (response) {
alert(response.d);
}
});
}
else {
$("#divSpecificToUserError span").text("Please enter email id in valid format");
$('#divSpecificToUserError').removeClass("d-none");
}
}
else {
$("#divSpecificToUserError span").text("No E-mail has been entered ");
$('#divSpecificToUserError').removeClass("d-none");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field form-group form-group-padding">
<label class="col-form-label">User E-mail(s) to Notify:</label>
<input type="text" id="field1" name="userEmail1" class="input form-control js-user-email" placeholder="example#domain.com" autofocus />
<button id="add" class="btn-sm btn-secondary add-more-specific pull-right btn-user-email" title="Add" type="button">+</button>
<div class="col-md-3 d-none alert-danger" id="divSpecificToUserError" style="margin-top: 6px">
<span></span>
</div>
</div>
$('.btn-user-email') if this is multiple elements you need to loop it and add click events to all elements in the jQuery list.
Oh, I see what your problem is.
// Your Add Button Function
// to insert another input here
function add(){
// Your Add Button Code Here
refreshValidate();
}
// Validate Function
function refreshValidate(){
$('.btn-user-email').each(function() {
$(this).unbind();
$(this).click(function (e) {
e.preventDefault();
// Your Validate Code HERE ...
});
});
}
How to display menus list only when the user is logged in to the site.But as of now the user is able to see the menu by giving direct URL.If the user is logged in then only he can be able to see the menu list and all.Can anyone check this.
HTML Code:
<html lang="en" ng-app="accountantApp">
<div class="container jumbotron" ng-init= "getAddressInfo()" ng-controller="AddressInfoController" id="homejumbotron">
<div class="col-sm-12 primary">
<div class="col-sm-2">PERSONALINFO</div>
<div class="col-sm-2">LOGOUT</div>
</div>
Js:
var app = angular.module('accountantApp', ['ui.bootstrap']);
app.controller('AddressInfoController', function($scope,$http,$timeout) {
$scope.submitAddressInfo = function(isValid, user) {
if (isValid) {
console.log("address info::"+$scope.user);
$http({
method : 'POST',
url : '../model/addaddressinfo.php',
headers : {
'Content-Type': 'application/json'
},
data : {'addressinfo': $scope.user, 'action': 'Save'}
}).success(function(data, status, headers) {
console.log("Response data:"+ data.error);
if (data.success != undefined && data.success != '')
{
console.log("inside success");
window.location.href = "income_source.php";
$scope.getTemplate("ADDRESSINFO");
$scope.user = '';
}
else
{
$scope.error = data.error;
}
}).error(function(data, status, headers) {
window.location.href = "error.html";
console.log("Error data::::"+ data);
alert("Error occured while creating address info:"+status);
});
}
else{
$scope.submitted = true;
alert("Fill the form.");
return;
}
};
Question is a bit unclear and the controller code you posted seems to be unrelated.
But assuming that all you want to do is show/hide something depending on whether or not the user is logged in, then you could do it like EuphoriaGrogi said, create a variable that is set to true if the user is logged in and false if not. Something like this:
$http.post('login_url').then(function(response){
if(login_successful){
$rootScope.isAuthenticated = true;
}
else{
//handle error
}
});
when you logout set it to false. In the html use an ng-if on whatever you want to hide:
<div class="col-sm-12 primary" ng-if="isAuthenticated">
<div class="col-sm-2">PERSONALINFO</div>
<div class="col-sm-2">LOGOUT</div>
</div>
I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.
This is my html code:
<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
<label id="name_label" class="control-label col-xs-2">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red" id="name_error"></font>
</div>
</div>
<div class="form-group">
<label id="email_label" class="control-label col-xs-2">Email</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red" id="email_error"></font>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>
</div>
</div>
<div id="dialog"></div>
</form>
This is my registration-newsletter.php
<?php
include('connect.php');
$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";
$result=mysql_query($query);
if(!$result){
echo "Some error Occured..Please try later";
}
else{
echo "Your details have been saved. Thank You ";
}
mysql_close($con);
?>
This is my JQuery code
$(document).ready(function(){
$("#register-newsletter").click(function(){
var name=$("#news_name").val();
var email=$("#news_email").val();
var dataString="name="+name+"&email="+email;
var request;
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString
});
//return false;
});
});
Add a span to your html code for displaying error.
<span id="error"></span>
Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.
$result=mysql_query($query);
if(mysql_affected_rows()>0){ // return the number of records that are inserted
echo "Your details have been saved. Thank You "; // success
}
else{
echo "Some error Occured..Please try later"; // failure
}
exit;
Then you can simply show the echoed message in the span with id error as:
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString,
success:function(response) // response from requested PHP page
{
$('#error').html(response); // set the message as html of span
}
});
$.ajax({
url: 'registration-newsletter.php',
type: 'post',
data: dataString ,
success: function (msg) {
alert(msg);
},
error:function(msg)
{
alert(msg);
}
});
jQuery.ajax({
url: "myfile.php",
type: "POST",
data: dataString,
success:function(response) /* this response is an array which is returning from the myfile.php */
{
$status = response['status'];
if($status == 'success')
{
$('#message').html(response['msg']);
}
else
{
$('#message').html(response['msg']);
}
}
});
The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.
This is what worked for me for form submit (see those 2 parameters to .then function):
<span id="result">Loading...</span>
<div id="form">
<form>
<input id="personId"> <-- put personID here<br>
<input id="submit" type="submit" value="Generate">
</form>
</div>
<script type="application/javascript">
$(document).ready(function() {
var submit = $('#submit');
var res = $('#result');
$('#form').submit(function() {
submit.prop('disabled', true);
res.text("Sending message...");
$.ajax({
url: '/rest/message',
contentType: "application/json;charset=UTF-8",
method: "POST",
data: JSON.stringify({'personId': $('#personId').val()})
}).then(function(result) { // OK
res.text("Message was generated");
submit.prop('disabled', false);
}, function(reason) { // ERROR
res.css('color', 'red').css('font-weight','Bold');
res.text("An error has occurred: " + reason.responseJSON.message);
submit.prop('disabled', false);
});
return false; // prevent default action
});
});
</script>
error: function(xhr) {
alert(xhr.responseText);
}
You can also get the HTTP status code or the generic message sent by your server (such as "Internal Server Error") in this XHR object if needed. More info : https://api.jquery.com/jQuery.ajax/#jqXHR
Is there a way to change my input in order to display a succes or error icon at the input? like : http://getbootstrap.com/css/#forms-control-validation
Much appreciated.
and here's my code :
<script>
$(document).ready(function () {
$('input[name=subdomain]').keyup(subdomain_check);
});
function subdomain_check() {
var subdomain = $('input[name=subdomain]').val();
if (subdomain == "") {
$('input[name=subdomain]');
} else {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain=' + subdomain,
cache: false,
success: function (response) {
if (response == 1) {
$('input[name=subdomain]').html("The URL already exist!");
} else {
$('input[name=subdomain]').html("The URL is Valid!");
}
}
});
}
}
</script>
The HTML code :
<div class="form-group">
<label class="control-label col-md-3" for="install-element-6">
<span class="required">* </span>subdomain</label>
<div class="col-md-6"> //<----- I want it here
<input type="text" class="form-control input-md col-md-6" name="subdomain" placeholder required id="install-element-6"/> // the method.addClass add it here
</div>
</div>
Much appreciated.
It worked now and all by adding the method parent() to get the element div instead of input
if(response == 1){
$('input[name=subdomain]').parent().removeClass("has-success");
$('input[name=subdomain]').parent().addClass("has-error");
}else{
$('input[name=subdomain]').parent().removeClass("has-error");
$('input[name=subdomain]').parent().addClass("has-success");
}