display laravel array validation in javascript - arrays

Can anyone please tell me how to display the validation error in javascript? I am sending the request with ajax and want to display the errors.
blade code
$('input[id^="facility_name"]').map(function() {
return this.value;
}).get();
Laravel Validation
'facility_name.*' => 'required|string|min:3|max:255',
display error from js
$('.facility_name_error').html(data.responseJSON.errors.facility_name);
or
$('.facility_name_error').html(data.responseJSON.errors.facility_name[0]);
I attached the output of validation so how can I display this message to html

If your question is how can you access an object attribute with a dot (.) in the name, you can use the array way
data.responseJSON.errors['facility_name.0'][0]

you can access the error as the following:
in this example i will append the errors to li item you can do what you want
$.ajax({
type: 'POST',
url: 'your-url',
data: {your_data},
success: function (data) {
}
}).fail(function (jqXhr) {
var resp = jqXhr.responseJSON;
if (jqXhr.status === 422) {
var errorsHtml = '<ul>';
$.each(resp.errors, function (key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul>';
}
}).always(function () {
});

Related

Getting an error when iterate through json in Jquery?

I am getting this error
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["Asharej Branch","Main Branch","Kanad Hospital Branch","Al Muwaiji Branch","Zakher Branch"]
Return this values from controller.
$stores = [];
foreach($t as $k){
$stores[] = $k['store_name'];
}
return $resultJson->setData(json_encode($stores));
Return Values from controller
[
"Asharej Branch",
"Main Branch",
"Kanad Hospital Branch",
"Al Muwaiji Branch",
"Zakher Branch"
]
Using AJAX call i want to access this value and create a dropdown list.
$.ajax({
url:customurl,
type: 'POST',
contentType: "application/json",
async:false,
success:function (data) { alert(data);
valuesCollection = [];
var wert=[];
/*$.each(JSON.parse(data), function (index, thevalue) {
alert(thevalue);
wert=[];
wert["label"]=index;
wert["value"]=thevalue;
valuesCollection.push(wert);
});*/
alert("T1");
for (var i = 0; i < JSON.parse(data.length); ++i) { alert("T2"+i);
console.log(data[i]);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("There has been an error retrieving the values from the database.");
}
});
I tried .each method and for loop also. But getting the error like above i mentioned. How to fix this?

$http:GET Invalid basic header. No credentials provided

When i tried to access star wars API using $http method . am getting 403 response with message "Invalid basic header. No credentials provided" what am missing here?
$http({
method : 'GET',
url : 'https://swapi.co/api/people/'
}).then(function(success) {
var data = JSON.parse(body);
var result = data.result.filter(function each(r) {
return username == r.name && password == r.birth_year;
});
}, function(error) {
alert('not logged::' + eror)
});
Could you please someone help me to find the issue?
You are using wrongly the data returned by the get call.
You don't need to parse it to JSON, it's already a JSON.
Here's a plunker with a call to the API working. Hope it helps you
https://plnkr.co/edit/WKQfqc7wxmBJIjYUyZKe
angular.module('myApp', []).controller('myAppController', function($http, $scope) {
$scope.callApi = function() {
$http.get('https://swapi.co/api/people/').then(function(result) {
$scope.characters = result.data.results;
}, function(error) {
alert('not logged::' + error)
});
}
});

PUT Request with AngularJS and Express

When I'm performing a put request and console.log(response) of the request I only get a JSON Object like {"res":1} instead of getting the whole json object with its changes in order to update him in a database.
Controller :
$scope.doneEdit = function (components) {
console.log(components);
components.editing = false;
if (components.editing === false) {
$http.put('/propt/' + components._id).then(function (response) {
console.log(response.data);
});
}
}
Express
app.put('/propt/:id', function(req,res) {
console.log(req.body);
testDb.update({_id:req.params.id}, req.body, {}, function(err, numReplaced){
res.statusCode = 200;
res.send(req.body);
})
})
You should pass the data you want to send as a second parameter to put method:
$http.put('/propt/' + components._id, {someValue:components.someValue})
You can find the documentation here: https://docs.angularjs.org/api/ng/service/$http#put

AngularJS reload data after PUT request

Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};

Jquery-Ajax call not working as expected

i'm working on a project like this:
(HTML Forms(AJAX)+ twitter bootstrap)(solo HTML, no JSP,etc..)->Servlets(on Google App Engine-JAVA)->Persistence(Google Cloud SQL).
I'm quite new to jQuery ajax calls, but i understand the process, as i'm used to write the old XHR code.
Below is the function in JS, that does not write to console the expected result..so far most of the times form data is persisted.
My Servlet if fine, and outputs a valid JSON.(calling the URL on a browser always works as expected.)
My answer is why jQuery ajax callbacks(done,fail,always) aren't working properly? They do write to console/display alert().
THANKS, for your time!
$(document).ready(function() {
var myEmail = "";
var myGender = "";
$('#saveButton').click(function() {
$('#myform').submit();
//alert('Handler for .submit() called.');
myEmail = document.getElementById("inputEmail").value;
window.console.log('EMAIL---->' + myEmail);/*ok log!*/
//alert('EMAIL->' + myEmail);
var radioObj = document.forms['myForm'].elements['gender'];
myGender = getCheckedValue(radioObj);
window.console.log('GENDER---->' + myGender);/*ok log!*/
//alert('GENDER->' + myGender);
var jqXHR = $.ajax({
statusCode : {
404 : function() {
alert("404 ERROR - page not found");
}
},
url : "/newuser",
type : "GET",
timeout : 10000,
data : {
email : myEmail,
gender : myGender,
operation : '0'
},
done : function(data, textStatus, jqXHR) {
window.console.log('done -> RESPONSE---->' + data);/*this does not log!*/
alert(data);
},
fail : function(jqXHR, textStatus, errorThrown) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
},
always : function(data, textStatus, jqXHR) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
}
});
});
});
done, fail and always are not properties of the settings object passed to $.ajax, they are callbacks on the jqxhr object returned by the call to $.ajax. They should be configured like this instead:
var jqxhr = $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Check out the API documentation for further usage guidance.

Resources