0

I am fairly new to Node JS so may be I am asking a too broad/poor question, but pardon me for it. I have been trying to call a nodejs function through AJAX Jquery and then want to show data returned from nodejs on my view but I am always ending up in error block. This is my code, if anyone could guide me through this?

index.jade(Client)

extends layout

block content
    body
        head
            script(src=' https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')

        h1= title
        p Welcome to #{title}
        a(href='' onClick="myFunction1()") Test
        script.
           var myFunction1=function(){
                var url = './checkUser1';
                var message = {userName: "XYZ"};
                var dataType = 'application/json';
                $.ajax({
                    url: './checkUser1',
                    data: '{"data": "TEST"}',
                    type: 'GET',
                    dataType: dataType,
                    success: function (data) {
                        var ret = jQuery.parseJSON(data);
                        console.log('Success: '+ret)
                    },
                    error: function (xhr, status, error) {
                        console.log('Error: ' + error.message);
                    },
                });
            }

index.js

router.get('/checkUser1', function(req, res) {
res.send({'data': 'some data is coming up'});

});

Now what I want is once I get response from this function I want to print a alertbox dispplaying this data

{'data': 'some data is coming up'}

Any idea what wrong I am doing?

1 Answer 1

2

Your problem is the URL you're hitting:

$.ajax({
  url: './checkUser1',
  data: '{"data": "TEST"}',

The period shouldn't be there. Switch it to:

$.ajax({
  url: '/checkUser1',
  data: '{"data": "TEST"}',
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, I tried ur approach but its not working, I am able to reach upto nodejs function but I am not able to throw back some data from nodejs function and to use it in ajax jquery
is ti because of same origin policy?
@Maverick yeah it could be same origin policy try this res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); and then send your data

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.