Sanjay Yadav Sanjay Yadav - 3 months ago 16
jQuery Question

How to Print java script error message in my div

Hi this code is working great, i am new in javascript ,what i am trying to do , print js default error message in my div.

<script type="text/javascript">
$(document).ready(function () {
var contranumber = <?php echo json_encode($data); ?>;
debugger;
if(contranumber)
{

$.ajax({
url: ApiUrl+'ActivateUser?contraNumber='+contranumber,
type: 'get',
success: function (data, xhr) {
alert(data.ErrorMessage);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}else
{

}
});
</script>
<div><center>javascript message</center></div>
<center><h3> Check your Email</h3></center>

Answer

A few quick things first:

  • Remove center tags, as it is deprecated. (Official example is "No, really, don't use it.")
  • Remove debugger;, unless you want your browser to stop.
  • Give your elements some sort of identification, be it a class or ID.

$(document).ready(function() {
  var contranumber = '{ "hello": "world" }';
  var message = $('.message'); // the element the message will go in

  if (contranumber) {
    $.ajax({
      url: ApiUrl + 'ActivateUser?contraNumber=' + contranumber,
      type: 'get',
      success: function(data, textStatus, xhr) { // you missed the textStatus parameter
        message.text('it was successful'); // why log an error on success?
      },
      error: function(xhr, textStatus, errorThrown) {
        message.text('Error in Operation:' + errorThrown); // give the actual error text
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="message"></div>
<h3>Check your Email</h3>