being_resilient
being_resilient

Reputation: 33

Updating an html page using ajax

I am learning ajax stuff. And I have this task that just like some stackoverflow.com where we can add comments just by hitting Add comment button and the comment appears right there without refreshing, I have a page where user will be asked to enter a name and the name must appear added just like described before. I have this code:

<script type="text/javascript">
  $("#add-tournament").click(function() {
    var name = $("#name").val();
    /*var password = $("#password").val();
    var country_code = $("#country_code").val();
    var firstname = $("#firstname").val();
    var lastname = $("#lastname").val();*/
    $.ajax({
      url: '/home/',
      method: 'POST',
      data: JSON.stringify({name: name}),
      success: function() {
        /*console.log(arguments)*/

      },
      error: function() {
        console.log(arguments)
      }
    })
  })
</script>

What should I put under success function?

Upvotes: 0

Views: 37

Answers (2)

Keith Ma
Keith Ma

Reputation: 53

The success section implies that the server which have already received your /home request where the server could send any relevant data to you (if necessary).

Generally speaking, the success section will be What you are going to do next?

success: function(data) {
//the data is sent by the server

//you can either noticing the user for the success submittion
Alert("Success");

//or may be showing the relevant data to user 
Alert("Mr/Ms " + name + ", you still have " + data);
}

Hope this help

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

It depends on what exactly you want to happen, but success needs to have a function parameter, which correlates to the data returned from the request:

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

From here you can go on to display it back to the page with something like:

success: function(data) {
  document.getElementById('x').innerHTML = data;
}

Note that while only the first parameter is required, there are three parameters on success:

  • data: The response from the request
  • textStatus: The success status code
  • jqXHR: The response object

And three on error:

  • jqXHR: The response object
  • textStatus: The error status code
  • errorThrown: The type of error

Hope this helps! :)

Upvotes: 1

Related Questions