/    Sign up×
Community /Pin to ProfileBookmark

How to submit form without page reload using Node.js and Express?

I need help figuring out how to submit a form with GET, but also call preventDefault(). Currently I have the following but the page is still being reloaded or redirected:

[code]
<div class=”row”>
<div class=”col-md-3″>
<form method=”GET” action=”/search”>
<div class=”form-group”>
<input type=”text” class=”form-control” id=”term” name=”term” placeholder=”Find”>
<br>
<input type=”text” class=”form-control” id=”location” name=”location” placeholder=”Near”>
</div>
<button type=”submit” class=”btn btn-default”>Submit</button>
</form>
</div>
</div>

<script>
$(function() {
$(‘form’).submit(function(event) {
event.preventDefault();
var $this = $(this);
$.get($this.attr(‘action’), function(data) {
$(‘pre’).text(data);
});
});
});
</script>[/code]

Now in my express code, I have this:

[code]
app.get(‘/search’, function(req, res) {
var apiUrl = getApiUrl(req.query);

var apiData = getApiData(apiUrl, function(statusCode, data) {
// console.log(data);
// res.render(‘api-guide’, data);
res.send(data);
});
});[/code]

I’m also using a templating engine (handlebars), so the form is in its own file, while the jquery stuff is in the main template. Is that why it’s not able to prevent the page from reloading?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@TcobbMay 16.2016 — I am not sure why you are doing this so perhaps the suggestion that follows won't work at all, but if you place the form into an iframe element and set the 'sandbox' attribute of that element correctly you should be able to send the form contents and get the response from the iframe, assuming the reply comes from the same origin as your main page.
Copy linkTweet thisAlerts:
@rootMay 17.2016 — Frameworks like Node and JQuery have a sub forum to JavaScript, this question would be best placed in that forum.
Copy linkTweet thisAlerts:
@TrainMay 17.2016 — Moved thread.
×

Success!

Help @jjwooyoung spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...