1

I'm making a webpage with Node JS with dustjs and PostgreSQL. How do I make a search query in the html, so I can pass the value to the app.get Do I need to use JQuery?

app.get('/teachers', function(req, res){
  pool.connect(function(err, client, done){
    if(err) {
      return console.error("error", err);
    }
    client.query('SELECT * FROM teachers', function(err, result){
      if(err){
        return console.error('error running query', err)
      }
      res.render('teacherindex', {teachers: result.rows});
      done();
    });
  });
});



app.get('/teachers/:str', (req,res)=>{
  pool.connect((err, client, done) => {
    if (err) throw err
    client.query('SELECT * FROM teachers WHERE name = $1', [req.query.namesearch], (err, result) => {
      done()
      if (err) {
        console.log(err.stack)
      } else {
        res.render('teacherindex', {teachers: result.rows});
      }
    })
  })
})

This is my JQuery

$("#myBtn").click(function(){
    var str = $("#myInput").val();
    var url = '/teachers/'+str;
    if(confirm('Search Record?')){
        $.ajax({
            url: url,
            type: 'put',
            success: function(result){
                console.log('Searching');
                window.location.href='/teachers';
            },
            error: function(err){
                console.log(err);
            }
        });
    }
});

My HTML

<input type="text" id="myInput" data-id="namesearch">
<button type="button" id="myBtn">Show Value</button>

Thank you!

4
  • At a high level glance, it appears you are doing this correctly. Sending AJAX from the client to your server. Your server retrieves results based upon what the client sent, and responds with those results. Are you getting an error? What prompted you to post this question? Commented Dec 21, 2019 at 16:35
  • Only thing I can see from a high level is if there is an error you aren't responding back to the client, you're just logging the error to console. You should have some type of error handling response, otherwise the browser is most likely just spinning forever waiting for a response from your server. Commented Dec 21, 2019 at 16:37
  • Yes, I'm still getting an error. I cannot retrieve the value from input text box to the server. I'm working on a college project by the way Commented Dec 22, 2019 at 2:44
  • I went ahead and updated my answer with everything that I found. Let me know if you have any questions. Commented Dec 22, 2019 at 17:00

1 Answer 1

1

FINAL ANSWER:

Ok so it turns out the issue you were having was something completely different. You are trying to use server side rendering for this, and I was showing you how to render the retrieved data on the client side.

I have forked, and updated your repo - which can be found at the link below..

Please review my changes and let me know if you have any questions.

Working repo: https://github.com/oze4/hanstanawi.github.io

Demo Video: https://raw.githubusercontent.com/oze4/hanstanawi.github.io/master/fake_uni_demo.mp4

enter image description here




EDIT:

I went ahead and built a repository to try and help you grasp these concepts. You can find the repo here - I tried to keep things as simple and understandable as possible, but let me know if you have any questions.

  • I had to make some minor changes to the paths, which I have commented explanations on the code in the repo.
  • I am using a "mock" database (just a JSON object in a different file) but the logic remains the same.

  • The index.js is the main entry point and contains all route data.

  • The index.html file is what gets sent to the user, and is the main HTML file, which contains the jQuery code.

If you download/fork/test out the code in that repo, open up your browsers developer tools, go to the network tab, and check out the differences.

Using req.params

enter image description here

Using req.query

enter image description here




ORIGINAL ANSWER:

So there are a couple of things wrong with your code and why you are unable to see the value of the textbox server side.

  • You are sending a PUT request but your server is expecting a GET request
  • You are looking for the value in req.query when you should be looking for it in req.params
  • You are looking for the incorrect variable name in your route (on top of using query when you should be using params) req.query.namesearch needs to be req.params.str
  • See here for more on req.query vs req.params

More detailed examples below.

  • In your route you are specifying app.get - in other words, you are expecting a GET request to be sent to your server.. but your are sending a PUT request..
  • If you were sending your AJAX to your server by using something like /teachers?str=someName then you would use req.query.str - or if you wanted to use namesearch you would do: /teachers?namesearch=someName and then to get the value: req.query.namesearch
  • If you send your AJAX to your server by using the something like /teachers/someName then you should be using req.params.str
//  ||
//  \/ Server is expecting a GET request
app.get('/teachers/:str', (req, res) => {
  // GET THE CORRECT VALUE
  let namesearch = req.params.str;

  pool.connect((err, client, done) => {
    // ... other code here

    client.query(
      'SELECT * FROM teachers WHERE name = $1',

      // SPECIFY THE CORRECT VALUE
      namesearch,

      (err, result) => {
        // ... other code here
      })
  })
});
  • But in your AJAX request, you are specifying PUT.. (should be GET)
  • By default, AJAX will send GET requests, so you really don't have to specify any type here, but I personally like to specify GET in type, just for the sake of brevity - just more succinct in my opinion.
  • Again, specifying GET in type is not needed since AJAX sends GET by default, specifying GET in type is a matter of preference.
$("#myBtn").click(function () {
  // ... other code here
  let textboxValue = $("#myTextbox").val();
  let theURL = "/teachers/" + textboxValue;

  // OR if you wanted to use `req.query.str` server side
  // let theURL = "/teachers?str=" + textboxValue;

  if (confirm('Search Record?')) {
    $.ajax({
      url: theURL,
      //     ||
      //     \/ You are sending a PUT request, not a GET request
      type: 'put', // EITHER CHANGE THIS TO GET OR JUST REMOVE type
      // ... other code here
    });
  }
});

It appears you are grabbing the value correctly from the textbox, you just need to make sure your server is accepting the same type that you are sending.

Sign up to request clarification or add additional context in comments.

13 Comments

I have tried your method, but still don't get any result. In your code, what does req.params.str refer to? In your jquery code, there's no str variable. Sorry, I'm still pretty new in node js
The Node code isn't aware/doesn't know about anything jQuery related. Anything jQuery related is running in the persons browser that visits your website. The str refers to the variable in your route. app.get('/teacher/:str)... the /:str part means that is a variable.
I'm still getting no result. But the server doesn't give out any error. What you should I put on the success part of the ajax? success: function(result){ console.log('Searching'); window.location.href='/teachers'; }
I check the chrome console, it says Failed to load resource: the server responded with a status of 404 (Not Found)
I would need to see more of your code to help diagnose something like that - it's sounds like you are still sending PUT using ajax versus using GET.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.