0

Currently I have a login form that will send JSON data (username and password) to my api server and the server will send back JSON data (username and balance) back to my webpage.

My HTML Code:

<input type="text" name="username" id="username" class="text" maxlength="30" />
<br />
<input type="password" name="password" id="password" class="text" maxlength="30" />
<br />
<input type="submit" name="btnSubmit" id="btnSubmit" />

My jQuery Script:

    $(document).ready(function () {
    $("#btnSubmit").click(function () {
        //collect userName and password entered by users
        var userName = $("#username").val();
        var password = $("#password").val();

        auth(userName, password);
    });
});

//authenticate function to make ajax call
function auth(userName, password) {
    $.ajax
    ({
        type: "POST",
        //SEND TO MY SERVER URL
        url: "http:myserverlocationurl.com",
        dataType: 'json',
        async: false,
        data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
        success: function () {

            //???????????????????????
        }
    })
}

My question has to do with the '??????????' listed above. How do I encapsulate/display the json data that is being sent back from the server and onto my webpage (either as a popup -- but ANYTHING would work as long as I can see it).

Thank you and any help would be much appreciated.

user3196499
  • 11
  • 1
  • 1
  • 3
  • 1
    Depends on what the response looks like.. In generic terms, you could alert the information, or create DOM elements containing the info and add them to the page. As a side note, it's generally not a good idea to build json strings by concatenating strings. Create a javascript object, then call `JSON.stringify()` if you need to. – Jason P Jan 21 '14 at 16:34
  • Can I get an example of how to do that? How to use stringify()? I am new to JSON. Also I want my response to just be simple alert. BUT i don't know how to do that :( – user3196499 Jan 21 '14 at 16:36
  • 1
    In that case, I would start [here](http://learn.jquery.com/ajax/). – Jason P Jan 21 '14 at 16:38
  • ok i will definitely check that out. thanks. But do you have suggestions on how to display the responding json data from the API server? – user3196499 Jan 21 '14 at 16:41
  • If you're only concerned with looking at the data, you could use the network tab of your browser's dev tools, or use `console.log()` to log the response in the `success` callback. There is an example on the second section of the link I posted that shows how to write json to the page. Keep in mind though, that your json structure will almost definitely be different than the example. http://learn.jquery.com/ajax/jquery-ajax-methods/ – Jason P Jan 21 '14 at 16:45
  • The problem is that my login form is for other users (not me). So i dont think i can use the console method. THe idea is for other users to type their info and the info will be sent as JSON object to my server which would then send back JSON object including the users account info. I just need a way to display it for them and allow them to view it. – user3196499 Jan 21 '14 at 16:48

3 Answers3

1
$.ajax
({
    type: "POST",
    //SEND TO MY SERVER URL
    url: "http:myserverlocationurl.com",
    dataType: 'json',
    async: false,
    data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
    success: function (jsonResponse) {

        resp = parseJSON(jsonResponse);

        alert(resp);
    }
})
Gjohn
  • 1,261
  • 1
  • 8
  • 12
0

The success function comes with three parameters, data, textStatus, and jqXHR which are explained in the jQuery API site:

success

Type: Function( PlainObject data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

To see the results from the ajax call, you can use console.log() to view the contents of the arguments:

    success: function (data, textStatus, jqXHR) {
          console.log(data);
          console.log(textStatus);
          console.log(jqXHR);
    }

To add the contents of the JSON response to your site - it depends on how it is formatted. If your response returns something like: {"user": "jsmith", "authentication": "success"}, then you can alert the user:

    success: function (data, textStatus, jqXHR) {
          alert('User: ' + data.user + ' authenticated:' + data.authentication);
    }

Or add it to some DOM element on your page, i.e. a div with an id of login-status:

    success: function (data, textStatus, jqXHR) {
          $('#login-status').html('User: ' + data.user + ' authenticated:' + data.authentication);
    }
rafiki_rafi
  • 1,177
  • 2
  • 11
  • 27
  • Thank you for your reply. So if I use the success function that you mentioned above, will the data show up on the webpage for the user to see?? – user3196499 Jan 21 '14 at 16:38
  • I don't think Console is neccessary because I am 100% sure the server is sending back JSON data. I just need a way to display the JSON data response onto the login-webpage (via Popup/Alert). – user3196499 Jan 21 '14 at 16:43
  • THanks a lot. I will definitely try it out. – user3196499 Jan 21 '14 at 16:50
  • What if its nested JSON object? So something like: {"info": {"user": "","balance": ""},} Would I use: success: function (data, textStatus, jqXHR) { alert('User: ' + data.info.user + ' balance:' + data.info.balance); } I really appreciate the help. I spent almost 5 days thinking and looking for a method. – user3196499 Jan 21 '14 at 16:58
  • Yes, but if the structure of the JSON object were to change, then `data.info.user` and `data.info.balance` would evaluate to undefined variables, resulting in a `ReferenceError` runtime error. I would urge you to read up on [JSON](http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it). – rafiki_rafi Jan 21 '14 at 17:06
  • ok. thanks. just wondering... why would the structure of the json object change? My api server is sending that same structure everytime. – user3196499 Jan 21 '14 at 23:09
  • Just something to think about as you're designing your program - as with any program, you'd like your variables to be readable and reasonably named. In your example, nesting `user` and `balance` under an `info` object seems redundant, but then again, perhaps it may make more sense in the context of your project. – rafiki_rafi Jan 21 '14 at 23:55
  • I see. Thanks a lot for your help. I haven't tested the display JSON yet but it seems to all make sense. – user3196499 Jan 22 '14 at 00:37
  • Another question. If my API server sends me JSON object in this form: {"user": "","balance": ""} and I only want to display the balance. If I use alert('balance:' + data.balance) it would still work and there won't be error? – user3196499 Jan 22 '14 at 17:16
  • You should experiment and test it for yourself :) – rafiki_rafi Jan 23 '14 at 16:12
  • Hello again. I was wondering how I can display the data without using alert. Say I want to display the data.balance on a website. Instead of alert(+data.balance). What can I use? – user3196499 Feb 28 '14 at 05:21
0
function auth(userName, password) {
    $.ajax
    ({
        type: "POST",
        //SEND TO MY SERVER URL
        url: "http:myserverlocationurl.com",
        dataType: 'json',
        async: false,
        data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
        success: function (response) {
          alert(JSON.stringify(response));
        }
    })
}

You can simply alert the data for your self to see it.

gauravmuk
  • 1,606
  • 14
  • 20