Ernest Poldrige
Ernest Poldrige

Reputation: 429

How to use message from server as text in jquery dialog

I am a beginner in jquery and I have a problem on how to use a message from server as text in jquery dialog.

I know a basic usage of jquery dialog is like:

 $( function() {
    $( "#dialog" ).dialog();
  } );

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

but my current code is like:

$.ajax({
  url: "/rest/data,
  method: "GET",
  dataType: "json"
}).complete(function(response) {
    $('#tabledata').html(''); //clean table data
    if (response.status == 400){
        // here I want to do something like
        show_jquery_dialog('my message');
    }

if I got an error I would like to use the api as shown. Is it possible ? How ?

thanks

Upvotes: 0

Views: 39

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

I understand that you want to use a dialog to show the error message from an Ajax request.

See comments within the code below... And have a look at dialog's documentation.

$( function() {
  // The dialog instantiated
  $( "#dialog" ).dialog();

  // A timeout for you to see the "default" dialog opened 2 seconds...
  // Then, attempt an Ajax request.
  setTimeout(function(){
  
    // Close the dialog
    $( "#dialog" ).dialog("close");
  
    // An Ajax request that WILL fail for sure
    $.ajax({
      url: "https://some-bad-domain.com/some-bad-URL.php",
      method: "GET",
      dataType: "json",
      
      success: function(){
        // success code here
        
      },
      error: function(xhr,status,error){
        // error code here
        
        // Set the dialog's text
        $( "#dialog p" ).text( JSON.stringify(xhr) );
        
        // Open the dialog
        $( "#dialog" ).dialog("open");
      }
    });
  },2000);

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

Upvotes: 0

Rohit Shetty
Rohit Shetty

Reputation: 504

Yes it is possible. Give an id to the p tag,

<div id="dialog" title="Basic dialog">
  <p id="message">This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

and then add text to it dynamically

show_jquery_dialog(message){
  $("#message").text(message);

  //add code to show the dialog
}

Upvotes: 1

Related Questions