Json query result not getting set - json

I am trying to use a Json request to get data from a login screen. But no matter if the login request is valid or not, I am always getting returned to my home screen. I think I am checking the result incorrectly?
Basically, in my Twitter-Bootstrap enabled site, I have a modal popup that takes the user to a login form.
The values are passed via a json query, to my MVC4 controller. A breakpoint shows I am getting good data.
Here's the scrip that sends the data:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result['success'] == 'true') {
alert("true");
window.location = '#Url.Action("Index", "Home")';
} else {
alert("BAD");
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
And here is the controller method:
[HttpPost]
public JsonResult LoginUser(string username, string password, string rememberMe)
{
string success = "false";
string message = "Not set";
if (username == string.Empty || password == string.Empty)
{
success = "false";
message = "Invalid Username/Password";
}
else
{
if (ModelState.IsValid)
{
var us = new UserService();
var reply = us.Authenticate(username, Security.EncryptText(password));
if (reply == 0)
{
success = "false";
message = "Invalid Username/Password";
}
if (reply != 0)
{
var p = us.GetPerson(reply);
FormsAuthentication.SetAuthCookie(p.Id.ToString(CultureInfo.InvariantCulture), rememberMe == "on");
Session["UserDisplay"] = string.Format("{0} {1} - ({2})", p.Firstname, p.Surname, p.Email);
success = "true";
message = "Login Success";
}
}
}
var result = new { Success = success, Message = message };
var r = new JsonResult
{
Data = result
};
return r;
}
However, I always get the 'BAD' alert. Never the 'true'.
Can I check the result the way I am? Am I attempting to do this the right way? Basically, if I get 'BAD', I don't want the screen to refresh. Infact, I will want to show a message saying what ever is in the 'message' parameter.
Edit: I think 'result' is NULL.

Related

Cannot access data of deserialized json

I'm using ajax to send data to my controller, here's how I do it
var formData = JSON.stringify( $('#SubmitForm').serializeArray() );
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
data: {formData},
url: '{{route("fileController.sendFiles")}}',
success: function(response) {
console.log(response);
},
error: function(response){
console.log(response);
}
});
Here's the route
Route::post('/sendFiles', ['uses' => 'FileController#sendFiles'])->name('fileController.sendFiles');
And the controller
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
return $data['allFiles'];
}
However, I get this error
"message": "Undefined index: allFiles"
When I check the contents of $request, I can see that allFiles array is clearly there, but how do I access it?
P.S. I've tried changing the second param when decoding to false, there's no difference.
$request data array
First of all your request data is simple array of objects. So you cannot index it with "allFiles".
Second since we have multiple objects with attribute name="allFiles[]", what you can do is filter those objects and return the values of it. (I don't know how are you going to use it, but this is how the code looks)
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
//filter all allFiles object
$allFiles = array_filter($data, function($obj){
if(isset($obj->name)){
return $obj->name=="allFiles[]";
}
return false;
});
//get values for all the filtered objects
$allFilesValues = array_map(function($obj){ return $obj->value; }, $allFiles);
return $data['allFiles'];
}
Let me know if this works for you.

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

“Invalid JSON primitive” in Ajax processing MVC

I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks

F5 doesn't work RIGHT on my webapp

i have a strange problem:
we have to make a project in IT, therefore we use AngularJS.
The problem is, when I use F5 for refresh, the page loads, but it is not able to show the right content again. There's just background and my title, everything in my UI-VIEW isn't there.
We have Login-Page with redirecting:
app.run(function($rootScope, $location, sessionFactory) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
let loggedIn = sessionFactory.isAuthenticated();
if (toState.authenticate && !loggedIn) {
event.preventDefault();
$state.go('login');
}
});
});
without this redirecting block, F5 works.
Otherwise I have to go to Login-Page and login again to get it work again.
I'm sorry guys, I'm new at programming. So if there's any code you need, just let me know. Hope someone can help.
UPDATE: this is our authentification_service.js
a group member wrote it. Does it help?
var app = angular.module('TheApp');
/**
* This service manages sessions: Retrieving token from server and storing token data.
*/
app.factory('sessionFactory', ['$http', 'jwtDecoder', function($http, jwtDecoder) {
var sessionFactory = {
sessionData: null
};
sessionFactory.login = function(username, password) {
//todo: encrypt password....
var user = { username : username, password : password};
// returns a POST request, success or error of that request
// must be handled by the caller of the login function
return $http({
method: 'POST',
url: 'rest/auth/login',
data: user
});
};
sessionFactory.logout = function() {
return $http({
method: 'POST',
url: 'rest/auth/logout',
data: this.sessionData
});
}
sessionFactory.deleteSessionData = function() {
this.sessionData = null;
}
sessionFactory.setSessionData = function(sessionData) {
this.sessionData = {
token: sessionData.token,
userData: jwtDecoder.getUserData(sessionData.token) // holds user id, todo: permissions
};
console.log(this.sessionData.userData);
};
sessionFactory.getToken = function() {
return this.sessionData.token;
};
sessionFactory.getUserId = function() {
return this.sessionData.userData.userId;
}
sessionFactory.isAuthenticated = function() {
return this.sessionData != null;
};
return sessionFactory;
}]);
/**
* This service injects authentification token in HTTP requests.
*/
app.factory('tokenInjector', ['$injector', function($injector) {
var tokenInjector = {
request: function(config) {
// cannot use sessionFactory directly, because else Angular will spot a circular dependency -> error
var sessionFactory = $injector.get('sessionFactory');
// if the user is logged in, add an Authorization header (with token) to each http request
if(sessionFactory.isAuthenticated()) {
config.headers.Authorization = 'Bearer ' + sessionFactory.getToken();
//config.url = config.url + "?token=" + sessionFactory.getToken(); // add token to request url
}
return config;
}
};
return tokenInjector;
}]);
/**
* Decodes JWTs received from the server with a JWT deconding lib
* and returns a useable result.
*/
app.factory('jwtDecoder', function() {
var jwtDecoder = {};
// extracts all needed frontend user data from token
jwtDecoder.getUserData = function(token) {
var payload = jwt_decode(token);
var userData = {
userId: payload.userId //,
//groupId: ?,
//permissions: payload.permissions, // is array of perm
};
return userData;
}
return jwtDecoder;
})

reCAPTCHA ajax verification ReferenceError: success is not defined

I am getting an error when I post my ajax call to the reCAPTCHA verification API. I get a "ReferenceError: success is not defined" error on correct input and "ReferenceError: incorrect is not defined" on incorrect insertion of the CAPTCHA. Here is my code:
$.ajax({
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
url: "http://www.google.com/recaptcha/api/verify",
data: {
privatekey: 'XXXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
async: false,
success: function (resp) {
if (resp == "false") {
alert('Please enter captcha words correctly');
reloadRecaptcha();
}
else {
alert('Yeah');
}
}
});
Well I solved my own problem by sending the post data to the page controller.
JS:
$.ajax({
type: 'GET',
contentType: "application/json",
url: "/Register/veriCAPTCHA",
data: {
privateKey: 'XXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
success: function (data) {
if (data == false) {
valiCAPTCHA = false;
ALERT("The CAPTCHA code you entered is invalid. Please try again.");
Recaptcha.reload();
}
else {
valiCAPTCHA = true;
}
}
});
CS controller:
[HttpGet]
public JsonResult veriCAPTCHA(string privateKey, string remoteip, string challenge, string response)
{
string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey, remoteip,
challenge, response);
JsonResult result = new JsonResult();
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
try
{
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
//incase you are using a proxy server
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
jsonResponse = sr.ReadToEnd();
string[] tokens = jsonResponse.Split(new char[] { '\n' });
if (tokens.Length == 2)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}