Rhys Edwards
Rhys Edwards

Reputation: 791

Passing data from view to express

I'm looking on for some guidance on the following problem. I'm attempting to pass a string to the server from a jade view. The val is being returned on the frontend but when I try to store it in the object I am being returned [object Object].

I believe it's breaking around the parameters variable but I can't work out why.

$(function(){
  $('#search').on('paste', function(){
    console.log('key up');

    setTimeout(function () {
      var linkURL =  $('#search').val();
      console.log(linkURL)

      // EVERYTHING BREAKS HERE
      var parameters = { search: $(this.target).val() };
      console.log('p' + parameters)
      $.get( '/searching',parameters, function(data) {
        $('#results').html(data);
      });
    }, 100);

  });
});

View

extends layout

block content
  .container
    h1 London Plans
    form(method='post' action='/submit', class='plans', id='plans')
      .form-group
        label Do you have a link?
        input.form-control(name='search', id='search' type='text', required='required')

I think the express code is correct, the console.log returns undefined, assuming because the object is broken.

app.get('/searching', function(req, res){
 // input value from search
 var val = req.query.search;
 console.log('val equals =' + ' ' + val);

// testing the route
// res.send("WHEEE");

});

Any pointers in the right direction to debug the object would be greatly appreciated.

Upvotes: 1

Views: 121

Answers (1)

Jarno Argillander
Jarno Argillander

Reputation: 5945

Try replacing var parameters = { search: $(this.target).val() }; with var parameters = { search: $('#search').val() };. The this variable inside setTimeout() refers to different object than this inside on().

You could alternatively replace { search: $(this.target).val() } with { search: linkURL } as you already save the result of $('#search').val() into linkURL.

Also see jQuery API for on() function: http://api.jquery.com/on/

The examples use this pointer "as it is" instead of writing this.target. For example in your case you could write: $(this).val() instead of $(this.target).val(). Move line var linkURL = $('#search').val(); above setTimeout line and change it to var linkURL = $(this).val();. Then replace { search: $(this.target).val() } with { search: linkURL }.

(The this.target is the way to obtain the target element from an event object but here we do not have one.)

Upvotes: 1

Related Questions