Parse JSON using javascript and get specific value in array - javascript

In my console log the array look like this:
{"userid":"5502","fullname":"My fullname","email":"sample#yahoo.com","user_access":"real"}
Now on my ajax, I have a handle code for the data array that the server sends to the app:
function handleData(responseData) {
var access = responseData;
console.log(access);
if (access == '"real"') {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}
How I can get the specific value of this "user_access":"real" in array and use it in condition.
like this:
if (access == '"real"') { // What should be the format of access variable?
alert("Welcome");
location.href = "home.html";
}

function handleData(responseData) {
var response = JSON.parse(responseData);//assuming you are getting the response as a string
var access = response.user_access;
console.log(access);
if (access == "real") {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}//handleData()
Normally, we want our response to be in json ( or we can say 'object' ) form, so that we can easily access its inner properties. So, if it's already an object, you do not need to use JSON.parse. You can directly access any property like this - responseData.user_access . But if it's in string form, then you have to use JSON.parse() first to parse the string into JSON ( or object ) format.

If it is not surrounded by "" around the {} brackets then just do
function handleData(responseData) {
var access = responseData.access;
if (access === 'real') {
alert("Welcome");
location.href = "home.html";
} else {
alert("Your username and password didn\'t match.");
}
}

Related

JQuery/AJAX call is not hitting Spring MVC controller

I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request.
Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
#Controller
public class ArsController
{
#RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(#RequestParam("uName") String uName ,#RequestParam("secQues")String secQues,
#RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}
Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.
try remove content-type and data-type.
You are not sending a json that should be parsed in a object, you are sending controller's parameters.
The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"

Javascript: User Authentication JSON Error

I'm making a login page for my web application, and I'm using a temporary data storage (I know this is not safe) for user verifiation. I'm trying to compate the username input to the data (only correct email is needed at the moment to get it working), but it's not working at all. I'm not getting an error message, just the alert that the username is not correct. It now displays both the user input and data, so I can see that my input is correct. What's wrong with it?
Thanks in advance!
(The data/object is in a seperate js file)
var count = 2;
function validate() {
var un = document.login.username.value; /* Username Input variable*/
var pw = document.login.password.value; /* Password Input variable*/
var valid = false;
let data = responseData;
for(var account in data.accounts){
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
console.log("Yes");
break;
}
}
if (valid) {
alert("Login was successful. Welcome, " + un + ".")
window.location = "https://www.google.com";
return false;
}
if (count >= 1) {
alert("The correct username is " + item_name + ", you put in "+un);
count--;
}
var responseData = {
authenticatUser: {
"ERR":0,
"RSP":{
"AUTHC":"true",
"USR":{
"ID":"2",
"TJT":"FULL",
"ACTV":"true",
"BO":"1489760664786",
"CONT":{
"FNM":"John",
"LNM":"Doe",
"PHN":"5556667777",
"PHNTP":"NONE",
"EML":"ex#mple.com",
"EMLTP":"NONE"
},
"ADMIN":"false",
"LLOGN":"1489760664786",
"ACCT":{
"ID":"2",
"TJT":"ID"
}
}
}
},
When you write:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
You are initializing a new valid variable that is only seen in that function. When you later access it outside the function you are seeing the original valid you initialized in line 5. This is called shadowing and it's a common source of bugs.
Do this instead:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
valid = true;
Now you should be changing the original valid variable.

How to check if onreadystatechange returns error with Javascript?

So I have a JSON API that I put a variable in at the end, and if the variable is a "valid" username (if the account actually exists) it will return information about it, but if the account isn't valid/doesn't exist it returns {} and in the console of the website I'm accessing the API with it shows an error saying
Uncaught TypeError: Cannot read property 'steamID' of undefined
at XMLHttpRequest.profileCheck.onreadystatechange
So I was wondering how I can check if that error is returned with an if statement? For example something like if(typeError === true) { do code } else { something else};
Here's the code I'm using to access the API (if that's important at all):
function isID64() {
var id64 = document.getElementById("username").value;
var realID64;
var profileCheck = new XMLHttpRequest;
profileCheck.open("GET", "<api im using>" + id64);
profileCheck.onreadystatechange = function() {
if (profileCheck.readyState === 4) {
var profileCheckResponse = JSON.parse(profileCheck.responseText);
realID64 = profileCheckResponse.playerstats.steamID;
...
}
};
profileCheck.send();
}
Any help is appreciated :)
I think this type error is because you are using JSON file to send data from your back end (php or something). if user is not exist it sends either null or a string. but in front end JSON.parse statement expect an json variable. Do following thing in your back end
if(userexist())
//save data into json variable;
else
//save "User Not exist" into your json variable.
then change your code from frontend (Javascript)
if (profileCheck.readyState === 4)
{
var profileCheckResponse = JSON.parse(profileCheck.responseText);
if(profileCheckResponse[0]=="User Not Exist";
//Display Error
else
realID64 = profileCheckResponse.playerstats.steamID;
...
}

jQuery.grep() match URL both www and non www, http/https

I am using jquery to search a json string for the matched url and then fetch all the data inside that object.
I fetch the url with
var url = window.location.href;
However this returns
http://somesite.com/
inside the json string could be any of the following
http://somesite.com/
http://somesite.com
http://www.somesite.com/
http://www.somesite.com https://somesite.com/
etc etc.
My code is to match the url and then do something. How would I go about using jQuery.grep() to take the different style urls in the query? Below is my code so far.
var url = window.location.href;
var json = exampleJsonString;
var js = JSON.parse(json);
var result = $.grep(js, function(e){ return e.url == url; });
if (result.length == 0) {
// not found :(
console.log('Not found');
} else if (result.length == 1) {
// Result matched
console.log(result);
}
else {
// multiple items found
console.log('multiple items found');
console.log(result);
}
What I want to do is check for somesite.com using jquery grep. As in this line it checks if the string is equal.
var result = $.grep(js, function(e){ return e.url == url; });
You can use grep function to filter the records. Here in your case want to check different URL's in the object like 'http://somesite.com/','http://somesite.com' etc, mention all the URL's that you want to consider in grep function. Here is the sample code.
var varObj = jQuery.grep(dataobject, function (a) {
if (a.url == "http://somesite.com/" || a.url == "http://somesite.com" || a.url == "http://www.somesite.com/")
return true;
});

How to pass a variable from View to Controller in ASP .NET

I found similar questions to mine, but in all of those examples, the variable was part of the model. I am trying to pass a variable that is created in javascript, which is not part of the model.
Code:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
#Html.Action("CheckDirectory", "Home", new { email = ???});
}
});
Is there a way to fill in the ??? with the email above?
You can pass your value as a GET parameter in the controller URL:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
window.location.href = '/CheckDirectory/Home?email=' + email;
}
});
To answer your question of
Is there a way to fill in the ??? with the email above?
No. The Razor code is similar to, say, PHP, or any other server-side templating language - it's evaluated on the server before the response is sent. So, if you had something like
#Url.Action("checkdirectory", "home")
in your script, assuming it's directly in a view, it would get replaced by a generated URL, like
/home/checkdirectory
Your code, which uses
#Html.Action("checkdirectory", "home")
actually executes a separate action, and injects the response as a string into the view where it's called. Probably not what you were intending.
So, let's try to get you on the right path. Assuming your controller action looks something like
[HttpGet]
public ActionResult CheckDirectory(string email = "")
{
bool exists = false;
if(!string.IsNullOrWhiteSpace(email))
{
exists = YourCodeToVerifyEmail(email);
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
You could, using jQuery (because XMLHttpRequests are not fun to normalize), do something like
$(function(){
var url = '#Url.Action("checkdirectory", "home")';
var data = { email : $('#email').val() };
$.get(url, data)
.done(function(response, status, jqxhr) {
if(response.exists === true) {
/* your "email exists" action */
}
else {
/* your "email doesn't exist" action */
}
})
.fail(function(jqxhr, status, errorThrown) {
/* do something when request errors */
});
});
This assumes you have an <input /> element with an id of email. Adjust accordingly. Also, the Url helper can only be used within a view; if you're doing this in a separate JavaScript file, replace it with a hard-coded string (or whatever else works for you).
Edit:
Since it seems I didn't entirely get what you were trying to do, here's an example of returning a different view based on the "type" of user:
public ActionResult ScheduleMe(string email = "")
{
if(!string.IsNullOrWhiteSpace(email))
{
ActionResult response = null;
var userType = YourCodeToVerifyEmail(email);
// Assuming userType would be strings like below
switch(userType)
{
case "STAFF":
response = View("StaffScheduler");
break;
case "STUDENT":
response = View("StudentScheduler");
break;
default:
response = View("ReadOnlyScheduler");
break;
}
return response;
}
return View("NoEmail");
}
This assumes you would have 4 possible views: the three you mentioned, plus an "error" view when no email parameter was given (you could also handle that by redirecting to another action). This variation also assumes a user has somehow navigated to something like hxxp://yourdomain.tld/home/scheduleme?email=peter#innotech.com

Categories

Resources