I have used $.ajax to send a PUT request through to my Express server. I can retrieve the information just fine but am having difficulties saving the new changes to my mongo (via mongoskin) database.
From the top, here is my click event on an edit button:
$('#userList table tbody').on('click', 'td a.linkedituser', editUser);
And here the function it calls:
function editUser(event) {
event.preventDefault();
var thisUserID = $(this).attr('rel');
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem._id; }).indexOf(thisUserID);
var thisUserObject = userListData[arrayPosition];
$('#editUserName').val(thisUserObject.email);
$('#editUserEmail').val(thisUserObject.email);
$('#editUserFullname').val(thisUserObject.fullname);
$('#editUserAge').val(thisUserObject.age);
$('#editUserLocation').val(thisUserObject.location);
$('#editUserGender').val(thisUserObject.gender);
$('#btnEditUser').on('click', function() {
$.ajax({
type: 'PUT',
url: '/users/edituser',
data: {
'id' : thisUserID,
'username' : $('#editUserName').val(),
'email' : $('#editUserEmail').val(),
'fullname' : $('#editUserFullname').val(),
'age' : $('#editUserAge').val(),
'location' : $('#editUserLocation').val(),
'gender' : $('#editUserGender').val()
},
dataType: 'json',
success: function(msg) {},
error: function(err) {}
}).done(function(response) {
if (response.msg === '') {
}
else {
}
populateTable();
});
});
};
And finally the router file routes/users.js
router.put('/edituser', function(req, res) {
var db = req.db;
db.collection('userlist').findById(req.body.id, function(err, result) {
result.username = req.body.username;
result.email = req.body.email;
result.fullname = req.body.fullname;
result.age = req.body.age;
result.location = req.body.location;
result.gender = req.body.gender;
console.log(result);
res.send((result === 1) ? { msg: '' } : { msg: 'error: ' + err + "!!!!" });
});
});
Everything is on git should I have missed anything.
It seems like everything should be fine but the results are not saving. When I refresh the page or click the edit button the old values return. I tried 'results.save()' but I get an error that the function does not exist.
Should I not be using findById?
Thanks.
Related
hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me
Hello wenn i want to send a post request to my Controller there is no data.
I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.
Here is my call:
var item = {};
var jsonObj = [];
item["ProductCategoryId"] = i;
item["Name"] = txtName;
item["Description"] = txtDescription;
item["Price"] = txtPrice;
item["Stock"] = txtStock;
item["ProductCategory"] = txtProductCategory;
item["Image"] = await getAsByteArray(txtImage);
jsonObj.push(item);
var jsonString = JSON.stringify(jsonObj);
console.log("jsonString : " + jsonString);
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
}
});
//Here I make a breakpoint but my string is empty
public JsonResult SaveProductToDB(string dataToSend)
{
List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
}
the getAsByteArray
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}
I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.
You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.
Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.
You might want to modify your code to catch errors for debugging, ie:
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
},
error:function (xhr, ajaxOptions, thrownError) {
// Set up whatever error reaction you want, here. ie:
console.log('An error was encountered.');
alert(xhr.status);
alert(thrownError);
}
});
Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.
I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!
I have Seen Similar Questions but I could not arrive at the solution. Please help on this code, I am new to javascript
My JavaScript Code :
function checkId(id_corpus){
var dataSet = {identity_number: id_corpus};
var requestUrl = appBaseUrl+'users/check-id-presence';
alert(id_corpus);
$.ajax({
type: "POST",
url: requestUrl,
data: dataSet,
success: function(result) {
if(result == false){
$('#ino').css('background-color', 'red');
$('#ino').css('color', 'black');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
The Above JS code is called by the following CakePHP view:
$this->Form->input('identity_number', ['style' => 'background-color : black; color : #1798A5;', 'id' => 'ino', 'onkeypress' => 'checkId(this.val)']);
Following is the controller code
public function checkIdPresence()
{
$this->autoRender = false;
$id_corpus = $this->request->data['identity_number'];
$check = $this->Users->find()->where(['identity_number LIKE' => '%'.$id_corpus.'%']);
if((iterator_count($check)) > 0){
echo false; //Corpus Exists
}else{
echo true;
}
}
I am stuck in the "Forbidden Error", I would like to bring it to your notice that similar AJAX is being used by me for Image display(as shown below), it is not showing any error:
function fetch(user_id, photo, photo_dir)
{
var dataSet = {id: user_id};
var requestUrl = appBaseUrl+'users/admin-side-nav-details';
var imageUrl = 'http://localhost/media/images/users/photo/'+photo_dir+'/'+'100x100_'+photo;
$.ajax({
type: "POST",
url: requestUrl,
data: dataSet,
success: function(result) {
$('#display_info').html(result);
var image = "<img src ="+imageUrl+" />"
console.log(image);
$('#display_image').html(image);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
EDIT: My Auth Component setup :
public function initialize()
{
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password']
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login',
],
'authError' => 'Are you sure, you want to enter?',
'logoutAction' => [
'controller' => 'Users',
'action' => 'login',
],
]);
Check https://book.cakephp.org/3.0/en/controllers/components/authentication.html#handling-unauthenticated-requests. "If authenticator returns null, AuthComponent redirects user to the login action. If it’s an AJAX request and config ajaxLogin is specified that element is rendered else a 403 HTTP status code is returned."
It seems to me like you didn't specify any authorization scheme so according to https://book.cakephp.org/3.0/en/controllers/components/authentication.html#using-no-authorization "If you don’t use an authorization scheme, make sure to check authorization yourself in your controller’s beforeFilter or with another component."
You can make actions public (in beforeFilter or initialize) using:
// Allow all actions
$this->Auth->allow();
// Allow only the index action.
$this->Auth->allow('index');
// Allow only the view and index actions.
$this->Auth->allow(['view', 'index']);
A Node.js / Express app with MongoDB, and using Passport, Passport Local and Passport Local Mongoose.
I'm trying allow registered users of my site to update their profiles. My idea was to rehash the signup form and logic, and send the updated data via a PUT request to the server.
The signup uses Ajax to submit the form, and whilst that works OK, when I send a PUT request to update the user, req.body comes back empty and the server throws out an error 500.
The update-form markup and javascript are nearly identical to the signup, so is it because I'm using a PUT request? I'm not even sure if I'm going about this in the right way...
Any pointers would be very happily received!
Edit user form submit logic:
$form.on('submit', function(e) {
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
var ajaxData = new FormData($form.get(0));
if (droppedFiles) {
$.each(droppedFiles, function(i, file) {
ajaxData.append($input.attr('name'), file);
});
}
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
// data: ajaxData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
complete: function() {
$form.removeClass('is-uploading');
},
success: function(data) {
// $form.addClass(data.success == true ? 'is-success' : 'is-error');
// if (!data.success) console.log(data);
window.location.replace('/matches');
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr)
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown); }
});
} else {
var iframeName = 'uploadiframe' + new Date().getTime();
$iframe = $('<iframe name="' + iframeName + '" style="display: none;"></iframe>');
$('body').append($iframe);
$form.attr('target', iframeName);
$iframe.one('load', function() {
var data = JSON.parse($iframe.contents().find('body').text());
$form
.removeClass('is-uploading')
.addClass(data.success == true ? 'is-success' : 'is-error')
.removeAttr('target');
if (!data.success) $errorMsg.text(data.error);
$form.removeAttr('target');
$iframe.remove();
});
};
});
Server Side Edit Route:
// PUT edits
app.put('/users/:_id', function(req, res){
var spokenLangs = req.body.spokenlanguages.split(',');
var learnLangs = req.body.learninglanguages.split(',');
var comms = req.body.commethod.split(',');
var photos = []
req.files.forEach(function(file, i){
photos.push(req.files[i].path.replace('public/', '../'));
});
var updatedUser = new User(
{
username: req.body.username,
firstName: req.body.fname,
lastName: req.body.lname,
age: req.body.age,
gender: req.body.gender,
spokenLanguages: spokenLangs,
learningLanguages: learnLangs,
info: req.body.info,
country: req.body.country,
city: req.body.city,
comMethod: comms,
photos: photos,
lastLogin: Date.now()
}
);
User.findByIdAndUpdate(req.params._id, updatedUser, function(err, user){
if(err){
console.log('error updating user');
console.log(err);
} else {
res.redirect('/matches');
}
});
});
Thank you good people!