fetching user details on successful login - javascript

I don't have hands on the API. I am using the provided URL to check the validity of a user based on its email. If the email and password match the data already present in API, I need to display them. I tried the part that has been commented now. Can someone help me?
$('#checkbutton').on('click',function(){
var self = this;
// var data={
// email: $('#emailer').val(),
// txtpaswrd: $('#paswrder').val()
// }
// var resultElement = $('#resultDiv');
var email = $('#emailer').val();
var txtpaswrd = $('#paswrder').val();
$.ajax({
type: "GET",
data: data,
processData:false,
contentType:false,
dataType:"json",
url: 'http://13.229.164.32/users/user_check.json?email=' + email,
success: function(nData){
alert(nData.password);
alert(nData.email);
if(email == nData.email && txtpaswrd == nData.password ){
//window.location = 'http://13.229.164.32/users.json';
}else{
alert('Password Error');
}
}
});
});

Try this:
$('#checkbutton').on('click', function() {
var email = $('#emailer').val();
var password = $('#paswrder').val();
var $resultElement = $('#resultDiv');
var URL = 'http://13.229.164.32/users/user_check.json?email=' + email;
$.getJSON(URL, response => {
var result = reponse.password == password ? "Password is a match." : "Passwords don't match.";
$resultElement.html(result)
});
});

Related

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

How to make an AJAX call with jQuery?

I'm dealing with the project where I need to collect data from user and display on the same page. I've successfully completed the Ajax call using JavaScript, but now I want using Jquery.
This is my JavaScript Code:
var output1 = document.getElementById("output1");
function saveUserInfo() {
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
var firstName = document.getElementById('firstname').value;
var lastName = document.getElementById('lastname').value;
var email = document.getElementById('email').value;
var dob = document.getElementById('datepicker').value;
var vars = "username=" + userName + "&password=" + password + "&firstname=" + firstName + "&lastname=" + lastName + "&email=" + email + "&datepicker=" + dob;
var ajax = new XMLHttpRequest();
var url = 'register.jsp';
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
output1.innerHTML = (ajax.responseText);
}
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(vars);
}
This is my register.jsp :
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user = request.getParameter("username");
session.putValue("username",user);
String pwd = request.getParameter("password");
String fname = request.getParameter("firstname");
String lname = request.getParameter("lastname");
String email = request.getParameter("email");
String dob = request.getParameter("dob");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info2","root","root");
Statement st = con.createStatement();
ResultSet rs;
//int i=st.executeUpdate("insert into user_info value('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"')");
int i=st.executeUpdate("INSERT INTO `users`(user,pwd,fname,lname,email,dob) VALUE ('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"','"+dob+"')");
%>
Registration is Successfull. Welcome <%=user %>,
Your Password is : <%=pwd %>,
FirstName : <%=fname %>,
LastName : <%=lname %>,
Email : <%=email %>,
and Date Of Birth is : <%=dob %>,
This is a generalized view of a jQuery ajax request.
$.ajax({
url: 'register.jsp',
type: 'POST',
data : {userName : userName,password: password,....},
contentType: 'yourConentType', // ConentType that your are sending. No contentType needed if you just posting as query string parameters.
success: function(response){
// do whatever you want with response
},
error: function(error){
console.log(error)
}
});
If you want to pass your values as object then as follows:
var formData = {userName : userName, password: password,...};
$.ajax({
url: 'register.jsp',
type: 'POST',
data : JSON.stringify(formData),
contentType: 'application/json',
success: function(response){
// do whatever you want with response
},
error: function(error){
console.log(error)
}
});
For more details: jQuery.ajax()
function saveUserInfo() {
var postData = {
username: $('#userName').val(),
password: $('#firstname').val(),
firstName: $('#ss_unit').val(),
lastName: $('#lastname').val(),
email: $('#email').val(),
dob: $('#datepicker').val()
};
$.post(url, postData).done(function(data) {
output1.innerHTML = data;
});
}
$.ajax({
type: "POST",
url: url,
data: data,
dataType: dataType
}).done(function(){
}).fail(function(){
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use jQuery's $.post method with .fail and .done. Then you can also use query's selectors to get the values from all your inputs.
Something like the following:
var output1 = $("#output1");
function saveUserInfo() {
var userName = $('#username').val();
var password = $('#password').val();
var firstName = $('#firstname').val();
var lastName = $('#lastname').val();
var email = $('#email').val();
var dob = $('#datepicker').val();
var data = {userName, passWord, firstName, lastName, email, dob};
var url = 'register.jsp';
$.post(url, data)
.done(function(msg) { /* yay it worked */ });
.fail(function(xhr, status, err) {
output1.text(err);
});
}
I also noticed that you are getting many input fields in your code. If all these input fields are located in a form (for instance with the id of formId, you can use $('#formId').serialize() to create the vars string for you. You can read more about .serialize() here.
You can use ajax call of jquery by using following syntax.
Add this on head section of your page for jquery reference.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For JS:
function saveUserInfo() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "...", // your api or url for fetching data
data: "..", // your data coming from front end in json
dataType: "json",
success: function (data) {
// your action need to perform
},
error: function (result) {
// handle error
}
});
}
However it is not recommended to make your connection or database related information provide on client side. For fetching data from backend it is recommended to make an API or web service for that.
You can use following links for references.
WebService: https://www.c-sharpcorner.com/UploadFile/00a8b7/web-service/
WebAPI: https://www.tutorialsteacher.com/webapi/create-web-api-project
Note: These both are for C# backend. Please mention your language name if anything else you are using.
It is the jQuery syntax of your code
function saveUserInfo() {
var userName = $('username').val();
var password = $('password').val;
var firstName = $('firstname').val;
var lastName = $('lastname').val;
var email =$('email').val;
var dob = $('datepicker').val;
var vars = {'userName':userName ,'password':password ,'firstName':firstName ,'lastName':firstName ,'email':email ,'datepicker':dob }
$.ajax(
{
url:'register.jsp',
data:vars ,
type:'POST'
dataType : "json",
contentType: "application/json; charset=utf-8",
success:function(result)
{
code to use result here
}
});
}

AJAX is not working in macOS WebView

I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});

How do I exit the click function?

So with this example I have form with a hidden field and a button called ban user. When the ban user button is clicked, it submits the value in the hidden field and sends the ajax request to a java servlet. If it is successful, the user is banned and the button is changed to "unban user". The problem is when I click the button once and ban a user and I try to click it again to unban, I'm still inside the click event for the ban user and I get the alert "Are you sure you want to ban the user with the id of ...?". How do I exit the click event to make sure when the button is clicked a second time, it starts at the beginning of the function and not inside the click function? I have tried using 'return;' as you can see below but that doesn't work.
$(document).delegate('form', 'click', function() {
var $form = $(this);
var id = $form.attr('id');
var formIdTrim = id.substring(0,7);
if(formIdTrim === "banUser") {
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(7);
var dataString = $form.serialize();
var userID = null;
userID = $("input#ban"+ trimmed).val();
$("#banButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to ban the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserBan",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#banUser'+trimmed).attr('id','unbanUser'+trimmed);
$('#ban'+trimmed).attr('id','unban'+trimmed);
$('#banButton'+trimmed).attr('value',' UnBan User ');
$('#banButton'+trimmed).attr('name','unbanButton'+trimmed);
$('#banButton'+trimmed).attr('id','unbanButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
else if(formIdTrim === "unbanUs") {
//Stops the submit request
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(9);
var dataString = $form.serialize();
var userID = null;
userID = $("input#unban"+ trimmed).val();
$("#unbanButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to UNBAN the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserUnban",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#unbanUser'+trimmed).attr('id','banUser'+trimmed);
$('#unban'+trimmed).attr('id','ban'+trimmed);
$('#unbanButton'+trimmed).attr('value',' Ban User ');
$('#unbanButton'+trimmed).attr('name','banButton'+trimmed);
$('#unbanButton'+trimmed).attr('id','banButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
});
Try with:
$("#banButton"+ trimmed).off('click').on('click', (function(e){......
I had similar problem and this was solution

i am not able to pass the html textbox values to webservice using jquery

i am not able to pass the html textbox values to webservice using jquery
my jquery is working fine for empty userName and password but it is not working if i add the ajax part. please help me in this issue
my html script
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript" >
$(function () {
$("#ButtonLogin").click(function () {
var username = $("#TextUN").val();
var password = $("#TextP").val();
if (username == "") { alert("fill the username !"); return; }
if (password == "") { alert("fill the password !"); return; }
var str = "{'userName':'" + username + "', 'password': '" + password + "'}";
$.ajax({
type: "post",
url: "http://localhost:4522/AdWebService.asmx/CheckUser",
contenttype: "application/json; charset=utf-8",
data: str,
datatype: "json",
success: function (res) {
try {
var jsondata = res.d;
if (jsondata == "true") {
window.location("http://localhost:5273/");
}
else {
alert("failure")
}
}
catch (e) {
alert(e.ToString());
}
},
failure: function (err) {
alert(err)
}
});
});
});
</script>
my web service method:
[WebMethod]
public string CheckUser(string un,string pass)
{
UserAds u = new UserAds();
u.UserName = un;
u.Password = pass;
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(udao.CheckUser(u));
}
You need to pass correct parameters. As you have defined un and pass as parameter to web service method, you need to use them.
Use
var str = "{'un':'" + username + "', 'pass': '" + password + "'}";
Also you can use JSON.stringify()
var str = JSON.stringify({
un: username,
pass: password
});
The better solution would be to not create a string manually for the data to be posted to your service. Instead use the "serialize" function available in jQuery. You can use something like this:
var data = $('form').serialize();
Thereafter you can pass this data in your ajax call.
var username = $("#TextUN").val();
try
var username = $("#TextUN").text();
Check TextP in you html code.
Else try this syntaxe :
var str = '{"userName":"' + username + '", "password": "' + password + '"}';

Categories