0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
webberpuma
  • 691
  • 1
  • 6
  • 21
  • If whatever you're clicking redirects, it would probably be a good idea to post what you're clicking, as in the `#button` element ? – adeneo Mar 15 '14 at 10:10
  • @adeneo I could not understand what you mean, could you explain it a bit? – webberpuma Mar 15 '14 at 13:55
  • 1
    Is the `#button`, a submit button on a form? – palanik Mar 16 '14 at 05:06
  • @palanik it is inside a form and also a submit button, is that a problem? – webberpuma Mar 17 '14 at 15:17
  • Yes. What happens here is the form is also getting submitted after you handle the click on the button. You can prevent that on handling the submit event instead. I'll show code as an answer. – palanik Mar 17 '14 at 17:22
  • possible duplicate of [How to prevent buttons from submitting forms](http://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms) – m59 Oct 03 '14 at 06:12

1 Answers1

1

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;
});
palanik
  • 3,601
  • 1
  • 13
  • 10
  • I tried to use your method but the problem persists. it seems the client side javascript was bypassed: I commented out the client side javascript and click the submit button, the form still got submitted and return the data on a new page. – webberpuma Mar 19 '14 at 01:32
  • Hard to know what is happening without seeing your code. But, I created this [jsfiddle](http://jsfiddle.net/7MxYD/) to show how JS code prevents a form from submitting to the server. HTH. – palanik Mar 19 '14 at 02:00