I connected a database to node and am trying to create an HTML page to search the database. I would rather not use EJS. I think I have to use a POST request in the HTML AJAX and connect it with a POST request in node.
Here is what I'm thinking:
app.post("/cities/:city", function(req, res) {
db.hospitalinfo.findAll({
where: { city: req.params.city }
}).then(function (result) {
res.json(result);
console.log("res--->"+result);
console.log("req--->"+req.params.city);
});
});
Here's the HTML:
<form id="author-form" method="POST">
<select id ="dropDownId">
<option value="Opp" >Opp</option>
<option value="Boaz">Boaz</option>
</select>
<input class="SubmitButton" type="submit" id="click" style="font-size:20px;" />
</form>
Now here's where I'm stuck. I need to grab the value from the select statement:
var nameInput = $("#dropDownId :selected");
I don't know how to actually send nameInput to the URL so my post statement will work. I probably don't completely understand how these routes work. This is my first project by myself. I would like to grab the nameInput, send it to the server via AJAX, and search my database with it. Right now it's returning an empty object. Thank you for your help.
You need to make a Ajax call to node server. For that you need to stop the default submit of form.
event.preventDefault();
can be used to stop the normal flow of submitting the form.
Here is an example of ajax call
(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type: "GET", // define the type of HTTP verb we want to use (POST for our form)
url: "http://localhost:5000/example" // the url where we want to POST
data: formData,
dataType: 'json', // what type of data do we expect back from the server
success: function (data) {
console.log(data.result);
// perform required changes
},
error: function (err) {
console.log(err);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
you can refer this site for more details making ajax calls
I have modified the code taken from there.
Related
I feel like I am missing something here.
To start, you have an AJAX call you can do in tag to post data to the backend, which looks something like,
function changeDom(){
console.log('connecting');
$.ajax({
url: '/loadOrders',
method:'POST'
}).done(function(data){
if(data.success){
$('#recentOrders').append(data.message);
changeDom2();
return;
}
}).fail(function(){
console.log('failed');
return;
});
};
And on the backend you receive it with code that looks something like,
app.post('/loadOrders', function(req,response)
{ // code here });
I have seen that it is possible to pass a parameter along an AJAX call, which looks like,
$.ajax({
url: '/loadOrders',
method:'POST',
data: {field1: 'this is data being passed'}
}).done(function(data){}});
But how would I receive that data on the backend? How would that change in syntax look and how would I call the parameter?
You can get it by doing
req.body.field1
I am using ColdFusion 11. I inherited an application which uses the mm_wizard_login ColdFusion feature for their login functionality. Now I have to implement the change password functionality in this application. So if the user logs in and the application finds that this user is logging in for the first time, it should redirect the user to change their initial password.
So I decided to use a jQuery third party modal plugin.
I have added the jQuery plugin functionality in the mm_wizard_login.cfm page. During the authentication process, the scenario where the user needs to change password, the mm_wizard_authenticate.cfc denies the login and redirects them back to the mm_wizard_login.cfm page and then the plugin opens up and allows user to type in their new password. After the user clicks the submit, in jQuery I am intercepting their submit and I am making an AJAX call to another cfc which is accepting the new password and calling a SQL Server stored procedure to change their password. This cfc method returns JSON back to the AJAX call but the returning value is not JSON, it is returning the HTML for the mm_wizard_login.cfm page itself.
Everything is working, except the AJAX call which is expecting JSON.
In Chrome dev tools, I went into the network tab and under response tab, It is returning back the HTML for mm_wizard_login.cfm page. I don't understand this.
Here is my AJAX call below:
var refData = $.ajax({
url: 'testmethod.cfc',
method: 'POST',
dataType: 'json',
data:{
method:'ChangePassword', //Call the method
jsonData: JSON.stringify($(formdata).serializeArray())
}
})
.done (function (d) {
if (d.Result == 'OK')
$("#modal-custom").iziModal('#modal-custom','setTitle', d.message);
$("#modal-custom").iziModal('#modal-custom','close');
else{
changePwd_ErrorHandler(d.message);
}
})
.fail (function (XMLHttpRequest, textStatus, errorThrown) {
changePwd_ErrorHandler(textStatus + '. Please try again');
});
After nothing worked then I just tried a basic AJAX call from my mm_wizard_login.cfm page, here it is below:
var test = $.ajax({
url: 'testmethod.cfc',
method: 'POST',
dataType: 'json',
data:{
method:'MethodTest', //Call the method
}
})
.done (function (d) {
})
.fail (function (XMLHttpRequest, textStatus, errorThrown) {
alert('Unable to change password. Please try again');
});
This is not working either. It is returning the same thing. Not JSON but the HTML content of mm_wizard_login.cfm. Please help.
This is my test cfc function which is being called from the login page.
[Upate] My test cfc method:
<cffunction name="MethodTest" access="remote" output="true" returntype="string" returnformat="json" hint="Adds/Edits User Info .">
<cfset retJSON = '{"Result": "Error","message": "Action Failed", "TotalRecordCount":0}'>
<cfreturn retJSON>
</cffunction>
New to MVC.
Scenario is. Using a 3rd party upload library for images. When a form is submitted, I want to make a call via ajax to submit the data and return the inserted item id. I then use that id for the 3rd party upload library to build folders where the images will be uploaded to.
I have the ajax call working and inserting the data to the database and getting the inserted id. But when the debug returns from the controller, it renders the id as a whole page.
Missing something fundamental here to MVC I think.
cshtml file:
<div class="col-md-8">
<input type="submit" value="Add Item" id="submitItem" />
<script>
$(document).ready(function () {
$("#submitItem").submit(function () {
event.preventDefault();
insertData();
});
});
function insertData()
{
var requestData = {
userID: $("#hdnUserID").val(),
title: $("#title").val(),
typeID: $("#typeID").val(),
description: $("#description").val()
};
$.ajax({
url: '<%= Url.Action("ItemUserDashBoard", "Home") %>',
type: 'post',
data: JSON.stringify(requestData),
dataType: 'json',
success: function (data) {
// your data could be a View or Json or what ever you returned in your action method
// parse your data here
alert(data);
$("#fine-uploader-gallery").fineUploader("uploadStoredFiles");
},
processData: false
});
}
</script>
</div>
HomeController.cs
[HttpPost]
public JsonResult ItemUserDashBoard(ItemAppraise.Models.iaDashBoardModel objItemUserDashBoard)
{
if(ModelState.IsValid)
{
using (dbContext)
{
ia_items iaItem = new ia_items
{
userID = objItemUserDashBoard.iaItems.userID,
typeID = objItemUserDashBoard.iaItems.typeID,
title = objItemUserDashBoard.iaItems.title,
description = objItemUserDashBoard.iaItems.description,
lastUpdate = DateTime.Now
};
dbContext.ia_items.Add(iaItem);
dbContext.SaveChanges();
//objItemUserDashBoard.iaItems.itemID = iaItem.itemID;
return Json(iaItem.itemID.ToString());
}
}
else{
return null;
}
}
Fiddler shows it as having a header of Content-Type: application/json; charset=utf-8.
But the page renders under the control url 'http://localhost:55689/Home/ItemUserDashBoard' with just the item id showing.
How do I get the data back just to use in the success part of the ajax call and not be rendered? Is this Partial Views or something similar?
Any guidance is appreciated.
In standard MVC. Any call made to a controller is handled just like a web request. So if i understand you correctly - the result of your httpPost is being rendered instead of the desired View? This is because you are returning JSON, so the controller assumes that is what you are trying to render. If you want a View to be rendered instead (and somehow use that response data) you could try setting the return type to ActionResult and returning a View("nameofview"); You can pass your response data to that view in a number of ways.
As a side note I think the problem you are facing could be better solved with Web Api instead of MVC. It works well with MVC and could be a simpler way of implementing your desired functionality. Separating your post requests and database interactions from the logic which decides which View to return.
I have an mvc3 application which makes use of an ajaxsubmit to a controller action.
The <form> opening tag in my page appears like this:
<form action="/application/home/Save?Length=0" class="form-horizontal" data ajax="true" data-ajax-method="POST" data-ajax-mode="after" data-ajax update="#jsonResult" enctype="multipart/form-data" id="inputForm" method="post" role="form">
If i submit this form from within the network that the server is based, the post request will always work. But if i submit the form externally, on occasions i get this generic error:
403 Forbidden: You don't have permission to access /application/home/Save on this server.
The above error doesnt always occur. only in particular instances.
Upon analysing the request headers, The only difference i see is Content-length:
They have the following:
The only other difference that i think could be the cause of this issue is in one of the fields in the request payload.
Now one of the fields i pass to the server is in a special code that has tilders and carrot symbols. Here is an example:
------WebKitFormBoundaryvvviIpe8b82tAvOd
Content-Disposition: form-data; name="udfArray"
["1~d^testfield~d^R"]
Whenever the form submit fails, it happens to have the above form data. When it succeeds, the field is set to []
The trouble is, i dont understand why having the code set to ["1~d^testfield~d^R"] should be an issue if it works within the network.
If anyone could point me in the right direction for making this work externally that would be great.
Here is my submit code:
//options for submit action
var options = {
data: {
udfArray: ko.toJSON(self.TempArray()),
title: self.title(),
given_name: self.givenName(),
//... other fields
},
uploadProgress: function () {
},
dataType: "json",
success: function (result) {
//do something
}
};
$('#inputForm').ajaxForm();
$('#inputForm').unbind('submit').submit(function () {
$('#loadingDiv').show();
$(this).ajaxSubmit(options);
return false;
});
I am using trying to use jQuery .change() to create two <select> elements whereby the first <select id="state"> is for generating a list of states and the second <select id="city"> is to generate a list of cities.
The values of states and cities will not be hard-coded but generated from values pass from web services.
The list of options to be generated is supposed to work like this: if user selects state from <select id="state"> the selected value will be pass to a web service to retrieve the list to generate the <select id="city"> for cities.
I'm really not sure how to implement this. Can anyone please advise me?
it should look something like
$(function(){
// populate the states list from Ajax
$.ajax( {
url:"/listStates",
type:"GET",
success:function( data ) {
var statesList = data;
if ( typeof(data) == "string" ){
statesList = JSON.parse(data);
}
$.each( statesList, function( index, state ){
$("#state").append($("<option></option>",{value:state.value, text:state.label});
});
},
error:function( result ) {
console.log(["error getting states",result]);
}
});
// register on state list change
$("#state").change( function(){
// on change dispatch an AJAX request for cities and populate cities
$.ajax({ url : "/listCities",
data : {"state": $("#state").val() },
type:'GET',
success:function( data ) {
var citiesList = data; // assuming list object
if ( typeof(data) == "string"){ // but if string
citiesList = JSON.parse( data );
}
$("#city").empty();
$.each(citiesList, function(index,city){
$("#city").append($("<option></option>", {"value":city.value, "text":city.label}));
}
},
error:function( result ){ console.log(["error", result]); }
})
});
This can get you started however I did not follow lint best practices here.
Walk Through
I register for a "change" event on select with id state.
When a change if fired, I invoke an Ajax request to location "/listCities"
I assume this location is called with a "GET" method
I pass along the state that is currently selected - so the server will know which cities to list.
If the Ajax through an error, I log the error to the console.
If the Ajax was a success, I populate the select with id "city" with options containing values for each city and a label.
I assumed the following things while writing the code
You have a route GET /listCities that expects a state.
The response from that route is a JSON containing a list of values and labels for each city. Something like this :
[{ value : "AM" , label : "Amsterdam" }, .... ]
The only things you may need to read about for this example are :
JQuery Ajax Calls
Best Practice To Populate A List With JQuery
If you have any questions, please comment my response, I will be happy to explain/add/modify
You have to follow some steps achieving this:
first when page load populate the first country list via ajax (my assumption)
then create a .change() event with the country list
This will send a request and returns the states list response as per selected country.
you can try test it this way:
$(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(data){
$.each(data, function(i, v){
$('<option value="'+v.name+'">'+v.text+'</option>').appendTo('#country');
});
}
});
$('#country').change(function(){
$.ajax({
url:your url,
type: 'post',
dataType: 'json', // or your choice of returned data
success: function(states){
$.each(states, function(i, stt){
$('<option value="'+stt.name+'">'+stt.text+'</option>').appendTo('#states');
});
}
});
$('#states').empty();
});
});
Pretty simple - all you'll have to do is have the two dropdowns, one with the full lists of states and the second (empty) city list will contain only one blank disabled option.
As soon as your states dropdown triggers a change event, you extract the state data and send it via an AJAX call to your server or some web service which will return a list of cities in that state.
You'll then populate the second dropdown with the returned city values.