I am working on an Node.js-Express.js-Mongoose application.
I want to accept user details (Name and Age) in an html form (EJS file), save into databse (using mongoose) display the added user details on the webpage .
I am using AJAX for the same. The files used are :
userview.ejs (contains the Form) --> frontend.js (uses jquery) --> users.js (router file- calls the add() function defined in the userController) --> userController.js (attached below) --> userService.js (performs DB operations).
Check the image of how the list should look like.
What actually happens is that a new user is created but the name isnt displayed.
A peek into database shows that only IDs of the blank entries are added.
FRONTEND.js
console.log('Frontend Reached');
$(document).ready(function() {
var url = '/users/delete_user';
var user_url = '/users/add_user';
function load_users(e) {
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'html',
data: $('#user_form').serialize(),
success: function(data, textStatus, jQxhr) {
console.log(data);
$('#list').html(data);
//$('#user_form').submit( load_users );
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}
//ADDING A USER
$(document).on('click', '.btn btn-success', function(e) {
e.preventDefault();
var user_name = $("#nameinput").val();
var user_age = $("#ageinput").val();
console.log(user_name);
console.log(user_age);
$.ajax({
url: 'userview.ejs',
dataType: 'text',
type: 'post',
ContentType: 'html',
data: {
'user_name': user_name,
'user_age': user_age
},
success: function(data, textStatus, jQxhr) {
console.log(data);
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
e.preventDefault();
}); //onclick
}); //document ready
This is userController.js
Console logging in this file shows that the record is undefined.
var User = require('../models/usermodel.js');
var userService = require('../services/userService');
var userController = {
add: function(request, response) {
var user_name = request.body.user_name;
var user_age = request.body.user_age;
console.log(user_name); //SHOWS UNdEFINED
var newUser = new User({
name: user_name,
age: user_age
});
console.log(newUser);
//var userName = request.body.user_name;
//var userAge = request.body.user_age;
userService.add(newUser, function(err, added) {
if (err != null) {
response.send(500);
} else {
response.send(200);
}
});
},
delete: function(request, response) {
var userId = request.body.user_id;
userService.delete(userId, function(err, deleted) {
if (err != null) {
response.send(500);
} else {
response.send(200);
}
});
}
};
module.exports = userController;
Send your data using JSON.stringify(),
and specify the content-type to 'application/json' so your server will know to expect a JSON.
var data = {
'user_name': user_name,
'user_age': user_age
},
$.ajax({
url: 'userview.ejs',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(data, textStatus, jQxhr) {
console.log(data);
load_users();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Related
When I try to run the following JQuery ajax, I get an error saying that a parameter is missing and it will not send the data. I can't find any syntax errors. What am I doing wrong?
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: fd,
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
Why not use jQuery native form encoder?
$.ajax({
...
data: $('#illustrationTypeForm').serializeArray(),
...
});
Try This
Here is the javascript with the JQuery ajax code:
function submitAction(actionname) {
if (actionname == "illustrationgenerate.htm") {
var thisForm = document.getElementById("illustrationTypeForm");
var fd = new FormData(thisForm);
$.ajax({
url: "illustrationgenerate.htm",
type: "POST",
data: $('#illustrationTypeForm').serializeArray(),
datatype: "xml",
cache: false,
success: function (result, status, xhr) {
document.getElementById('errorMessage0').value="Success";
},
error: function (xhr, status, error) {
alert(xhr.status);
alert(request.responseText);
}
});
} else {
document.forms[0].action = actionname;
document.forms[0].method = "POST";
document.forms[0].target = '';
document.forms[0].submit();
}
}
To make ajax request using jQuery a type 'POST' you can do this by following code :
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
I am using mvc 4 ,I need to call controller actions using ajax.So I created a new scripts.js file at Scripts folder.In my project there are lot of controllers and I wrote ajax functions for each of them in the same js file.But except the default controller other controllers are not initiated by the ajax code. Scripts.js file contains:
$(document).ready(function () {
//END COUNTRY ................................................................
$("#savecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/SaveCountry',
data: {name: $('#country').val() },
dataType: 'json', encode: true,
async: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
// alert("success");
console.log(jqXHR);
console.log(status);
console.log(data);
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(jqXHR);
//console.log(textStatus);
//console.log(errorThrown);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$("#updatecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/Update',
data: { id:$('#id').val(), name:$('#country').val() },
dataType: 'json', encode : true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$('#cancel').click(function () {
$('input:text').val('');
});
//$('.deleteRow').click(function () {
// alert('ewewrwr');
// $.ajax({
// type: "POST",
// data: { id: $('#id').val() },
// url: "/Country/DeleteCountry",
// dataType: 'json', encode: true,
// async: false,
// cache: false,
// success: function (data, status, jqXHR) {
// alert("success");
// //$.each(data, function (index, customer) {
// // alert(customer.Name + " " + customer.UserName);
// //});
// },
// error: function (jqXHR, textStatus, errorThrown) {
// console.log(jqXHR);
// if (typeof (console) != 'undefined') {
// alert("oooppss");
// }
// else { alert("something went wrong"); }
// }
// });
//});
$("#updateoffer").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Offer/Update',
// contentType: "application/json; charset=utf-8",
data: { id: $('#id').val(), name: $('#offer').val(), description: $('#description') },
dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
});
Here Country is the default controller and ajax call working well.But call to Offer controller Update ajax not working .Page not responding error will result.
You should take project name to baseUrl for call ajax function.
$(document).ready(function(){
var baseurl = "";//your project name
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry', // baserurl+"/controller name/action"
.....
}
The accepted answer has a serious flaw in commercial deployments, so offering alternatives.
Yes, you need the base address of the website, but you do not want to hard-wire it into the code.
Option 1
You can inject a global javascript variable into your master page as a string constant.
e.g. put this at the top of your master page
<script>
window.baseurl = "#Url.Content("~/")";
</script>
then just use window.baseurl prepended to your URLs
e.g
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: window.baseurl+'/Country/SaveCountry',
Option 2
You can inject a data- attribute into the DOM in your master page. e.g. on the body tag
then extract it using jQuery:
e.g.
var baseurl = $('body').data('baseurl');
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry',
Option 3 (I do not advise this one)
Inject the string literal into your Javascript
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("SaveCountry", "Country")",
This is bad for maintenance and debugging as the code must be in a Razor view in order to work.
We used to use option 2 a lot, but now tend to use option 1.
i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});
I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}
yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.
It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>
//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});
I have a javascript function like this :
addGas = function(options){
var working = false;
$(document).ajaxSend(function(event, jqxhr, settings) {
if (settings.url == '/add_gas') {
working = true;
}
});
if(working) {
return;
}
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}
So the way I test this is that I put 10 seconds sleep in my controller, and try to click the button again, and it makes a post request who is waiting, because my server can server one request at a time.
But I wanted not to send a post request if one is already running, alternatively alert a message if the request is already running.
How can I do that?
Create a singleton handling its own state, this way you dont pollute the rest of the code with unused variables
gasHandlerBuilder = function(){
var ajaxInProgress = false;
return {
add_gas: function(options){
if(ajaxInProgress){ return; };
ajaxInProgress = true;
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
ajaxInProgress = false;
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
ajaxInProgress = false;
}
});
}
}
}
var gasHandler = gasHandlerBuilder();
gasHandler.add_gas(options);
You should use some flag, something like this :
var recieved = false;
$.ajax({
url: "http://first.call/",
})
.done(function( data ) {
// Do something with that data and enable the flag
recieved = true;
});
addGas = function(options){
var working = false;
$(document).ajaxSend(function(event, jqxhr, settings) {
if (settings.url == '/add_gas') {
working = true;
}
});
if(!recieved) {
return;
}
$.ajax({
url: options.url,
data: options,
type: "POST",
success: function(data, textStatus, jqXHR){
$(".btn").addClass("added").text(" Added gas ").prepend("<i></i>");
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}