I am new to nodejs and jquery, I just want to get some data from a server and use that data to update a page:
Client side (uses jquery): as you can see, I want the text inside '#info' change to data got from server.
$('#button').click(function(){
$.post("/search", function(data) {
$('#info').text(data);
});
});
Server side (uses express):
app.post('/search', function(req, res){
res.send('hello');
})
The problem is: instead of updating the content of '#info', the content of the whole webpage will be gone and only 'hello' is printed on the webpage.
The client side seems unable to get the data from the server side, but I cannot figure it out why.
As mentioned in my comments, instead of handling button click event, you could handle form submit event and stop the form from submitting.
$('form').submit(function(){
$.post("/search", function(data) {
$('#info').text(data);
});
// This will prevent further processing...
return false;
});
Related
Basically what I wantto achieve is a searchable/filterable listview
so far I'm able to fetch some data from a database and have express with pug render me a page showing the results in a listview.
Now I want to add the functionality of filtering the displayed listview.
Therefore on every keyup event within a textbox I make an AJAX post request to the server sending the query string from the textbox. So far everything works just fine, but when i try to "re-render" the page with the filtered resultset nothing happens in the browser.
My routes look like this:
var rechnungen;
router.get('/', function(req, res) {
connection.query('SELECT * FROM rechnungen ', function(err, result) {
rechnugen = result;
res.render('rechnungen', {rechnungen: result});
});
router.post('/:query', function(req, res) {
console.log("received ajax request");
console.log("with query " + req.params.query);
res.render('rechnungen', {rechnungen: {}});
});
initially the query statement fetches the data and res.render works just fine, when I make the AJAX call everything seems to work as well (the console log output matches my input) but regardless what i try to pass to the view (res.render) in the post route nothing happens.
Is it not possible to "re-render" a view or is there any other conceptional misstake I make?
thanks for your help
AJAX POST call is not a traditional HTTP call.
The rendered page sent from the server will come in the response object of success handler of your AJAX call.
So, either
replace whole HTML with the response HTML, or
make a traditional HTTP form POST, in that case the browser by-default renders the response of the server.
I am asking this question after searching all over the Internet. I do this a lot with a JEE server and jsps. I am trying with with Node and JQuery and having a hard time getting it to work. I have a form that grabs an input, I do an Ajax post to the server and the server responds by rendering a view based on the input. Seems to me that I should not have to worry about a popup attached to a click event on the client. For the life of me I cannot display the page sent by the server in response to the input. Am I missing something here? Any pearl of wisdom on this use case would be greatly appreciated. I tried some related examples and they don't seen to work. Here is the code. Upon return from the server the HTML is not rendered. I just add the javascript that does the AJAX post and processes the response from the server.
script.
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Details",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
$("#OK").click(function() {
var org = $("#name").val();
if (org == '' ){
alert("Please Fill Required Fields");
} else {
alert("about to post "+org);
$.post("/repost",
{name: org})
.done(function(data) {
alert(data);
$("#dialog").html(data);
$("#dialog").dialog("open");
});
$("#form")[0].reset();
}
});
$("#cancel").click(function() {
$("#form").dialog("close"); // To close the form
});
});
Server code:
app.post('/repost', function(req, res) {
console.log("We are called with ", req.body);
res.render('reposub.jade', {org:req.body.name, title: 'Express' });});
sounds like you're looking for help with $.post:
$.post( "ajax/test.html", function( tx_response ) {
//console.dir(tx_reponse) -- does this have ususal stuff like _data_ and _status_? Or is is a raw HTML response?
if (/* some condition like: tx_response.status === 200 */) {
// if the html is a template, and not a redirect to a new url:
$('.result').html(tx_response.data)
// redirect:
window.location.href = tx_response.data
//...
});
If it is neither a redirect nor a template, but rather a whole new http reply with HTML that the client should load, I think you can use document.write but .. this could be engineered better in that case. Arguably the response should be at most a redirect URL, or a template.
In addition to roberto tomás answer, also make sure your server has CORS support enabled. This is particular useful when:
developing something in local, that is not served by a webserver;
whenever your frontend is not located on the same host (thus ip and port combination) of your backend (in your case your nodejs app)
Useful resources:
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
https://github.com/expressjs/cors
So in my case, I had to have a div element that I can run the html method against. So with a div element created in the body of my html page, I was able to do a $("div.listcontainer").html(data); and my page displayed fine.
I know how to send an http request to a server using angular js. With the promise returned, I know how to listen for a response and manipulate the ui thereafter. But this approach cannot be used for what I have in mind.
However, what I cannot figure out, is how to send a request to a website.
I have a server localhost:800/receiveData which receives a POST request and then manipulate the UI and DoM on the angularjs site
app.get('/', function(req,res){
res.sendFile(__dirname+'/index.html')
})
app.post('/receiveData', function(req,res){
var data = req.body.data
// assume data is a boolean
if(data){
//show a view in index.html using angular js or anything else
}else {
//show a different view in index.html
}
});
Any help will be greatly appreciated. I have a need for angular js. Having a SPA is imperative. I am completely open to adding additional stacks if neccessary.
EDIT:
As pointed out by MarcoS, manipulation of dom should ideally not happen from the server side. I am combining IPFS with node js and angular js to develop a single page application. The swarm of nodes set up using IPFS has an open line of communication with my server (by design). Based on packets of data sent via the comm line to my server, I need to convey messages to the user via the index.html.
I think your approach is wrong: on server-side, you should NOT manipulate the UI and DOM...
You should just do server activity (update a database, send an email, ..., return a static page).
Then you can output a result (JSON/XML/... format) for your client-side calling script to read.
Following OP edit, what I do understand is he wants server push to the client.
To get serve side pushes, you should poll on the client.
In a controller:
function getServerState(changeState) {
return $http.get("/receiveData").then(function(res) {
changeState(res.data); // notify the watcher
}).catch(function(e) {
/* handle errors here */
}).then(function() {
return getServerState(changeState); // poll again when done call
});
}
Consuming it this way:
getServerState(function(status) {
$scope.foo = status; // changes to `foo` $scope variable will reflect instantly on the client
});
And, server side:
app.post('/receiveData', function(req, res) {
var data = req.body.data; // assume data is a boolean
res.end(JSON.stringify(data);
});
I load a page from example.com on port 80, then from the loaded page, submit a form to the same server on a different port (as defined in the form action attribute).
(html)
<form id="enabledForm" action="http://example.com:39991/updateEnabled" method="POST">
(javascript)
$('#enabledForm').submit()
This works fine and the data is delivered as expected to the form action url, but the browser is redirected to the address of the POST request instead of staying on the requesting page.
If I use
$('#enabledForm').submit(function (event) {
event.preventDefault();
});
or
$('#enabledForm').submit(function (event) {
return false;
});
then the server receives no data but the page is not redirected.
if I add an alert within the event handler then the alert is not shown.
$('#enabledForm').submit(function (event) {
alert('inside submit event handler');
return false;
});
Clearly I'm soing something wrong but after hours of headbanging and trying everything I can think of I'm stuck.
What to do?
You have two basic options here:
Have the server return a 204 No Content response and forget about using JS entirely
Prevent the submission of the form with JS and send the data to the URL with Ajax instead
No content:
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent.
How you set the HTTP response status code depends on your server side language / framework. For example:
In Catalyst it would be something like:
$c->response->status(204);
In PHP it would be:
http_response_code(204);
There are many Ajax tutorials out there, so I'm not going to provide another one. The jQuery documentation has a detailed section on Ajax.
Note that since you are working across origins (different ports), you will need to circumvent the Same Origin Policy. The standard way to do that is with CORS.
Sending a form would automatically change your browser URL (and refresh view).You should use an Ajax request to send informations to your server and eventually retrieve completion (success, error, informations...).
Extract your inputs' values to an object via Jquery and send your request via Jquery.post or Jquery.get
$('#enabledForm').submit(function (event) {
//Prevent natual post
event.preventDefault();
//Retrieve inputs values
var data = {}
$('#enabledForm input,textarea').each(function(index){
data[$(this).attr('name')] = $(this).val();
});
//Send request
$.post('http://example.com:3999/updateEnabled',data,function(response){
//Parse response if you want to inform user about success of operation
});
});
I don't know if val() is usable with all of yout inputs, but it's easy to adapt...
I have a node.js express application which is trying to make a post request and query the contents of a database. I am trying to execute the post request without have to redirect the user from the form page or reloading the page.
index.jade
form.well(id="newEntryForm", method="post", action="/addEntry")
label Key:
br
input(name="key", id="key", class="new-entry", type="textbox")
br
br
label Value:
br
input(name="value", id="value", class="new-entry", type="textbox")
br
br
button.btn(type="submit") Add Entry
app.js
app.post('/addEntry', function(req, res){
//database query
});
This ends up redirecting me to the URL localhost:3000/addEntry. I know I can add res.redirect("/"); within the callback for the post method, but that will reload the page. How do I accomplish this without reloading the page?
EDIT
I added a javascript method to execute on submitting the form, but it ends up appending the POST request parameters on the URL bar. How do I avoid this?
Javascript method
$(function() {
$('#newEntryForm').submit(function() {
var data = {key: 'a', value: 'b'};
// build a json object or do something with the form, store in data
$.post('/addRule', data, function(resp) {
alert(resp);
console.log("post response: " + resp);
// do something when it was successful
});
});
});
As a comment said, you need to use client side javascript+ajax.
$(function() {
$('#newEntryForm').submit(function(event) {
event.preventDefault(); // Stops browser from navigating away from page
var data;
// build a json object or do something with the form, store in data
$.post('/addEntry', data, function(resp) {
alert(resp);
// do something when it was successful
});
});
});