Solved

How do I refresh a page following JQuery dialogue form post and display response.

Posted on 2016-10-18
6
124 Views
Last Modified: 2016-10-18
Hi,
I have the following JQuerty dialogue which posts form data to the processing page "save_applicantnote.php" and retrieves  
 the response which is then assigned to the <p> tag with id errors.

This works fine but I can't get the page to refresh and display the response. It either displays the response or refreshes but not both.  Using location.reload(true); reloads the page but then I loose my response from the post.

Is there anyway to reload the page and display any error response returned from the post?

Thank you




      $( "#dialog-window" ).dialog({

        autoOpen: true,
        maxWidth:550,
        maxHeight: 900,
        width: 550,
        height: 900,
        draggable: true,
        modal: true,
        buttons: {
            "Save": function () { 
             $.post("save_applicantnote.php", $("#mainForm").serialize(), function(response)
                  {
                  
                  $("p#errors").html(response);
                               
                  });
              
            $(this).dialog("destroy");
             

            },

            "Cancel": function () {
              $(this).dialog("destroy");
            }
        } 
              
      });

Open in new window

0
Comment
Question by:EICT
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 41848105
You can't refresh and display the response. As soon as you refresh any response from the server is lost.

Why do you want to refresh? Either you are doing AJAX or you are doing a complete Post back - why do you want to mix them?

Theoretically you could get the response - append it to the page URL and refresh the page and have either the server render out the page or use javascript on the page to pull the value from the URL - this is possible but not really practical.

The principle with AJAX is you submit data to the server while keeping the same page - you then update the page (or parts of it) with data the server sends back as part of the AJAX call.

Can you explain why you want to mix the two approaches?
0
 

Author Comment

by:EICT
ID: 41848157
Hi Julian,

I have a page which displays journal notes retrieved from a MYSQL database. At the top of the page is a "Add Note" button which when clicked displayed a modal dialogue box form for users to add a new note.  After clicking save the new note is added to the database.  The dialogue form is part of the same page code and the displayed notes but hidden until the dialogue box is opened.

Basically, after the user clicks "Save" I wanted the page to refresh so the user can see the new note added and for a message to pop up saving "new note added successfully"

The "New note added successfully" is a response from the processing page. In the event of an error an error response is returned.        

Can I not show the new note and also have a message? perhaps I could display the message directly on the page rather than collecting is a response?

Thanks
0
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 41848193
The standard ways of accomplishing what you want to do is

You return the list of notes from the AJAX request and re-populate the list
OR
You append the new note with JavaScript

You can return multiple values from your Server request using JSON

Option 1 above
Send your data to the server with AJAX
Server script processes and adds to the databse
Server script requests list of notes from the server as an array
Then either
On the server render out the list elements with the data retrieved above and send back the already rendered HTML which you can then replace into page
OR
Send back a JSON encoded array and use JavaScript to create each of the list entries for each note

Which you choose is up to you

Option 2
Send the note to the server
Server adds note to database and sends back a status (true / false)
Based on the return the AJAX call back you add the new item to the list leaving the other items intact.

I will try and put some code together to show how it is done.
0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 
LVL 57

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41848259
Sample code
HTML
    <h2>List items</h2>
    <ul id="items"></ul>
    <button class="add-item btn btn-primary" id="option1-server" data-type="serverRender" data-toggle="modal" data-target="#NewItem">Option 1 (Server Render)</button>
    <button class="add-item btn btn-success" id="option1-browser" data-type="serverJSON" data-toggle="modal" data-target="#NewItem">Option 1 (Browser Render)</button>
    <button class="add-item btn btn-default" id="option2-local" data-type="localInsert" data-toggle="modal" data-target="#NewItem">Option 2 (Local Insert)</button>

Open in new window

Dialog
<div class="modal fade" id="NewItem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">New Item</h4>
      </div>
      <div class="modal-body">
        <form id="NewItemForm">
      <label for="note" class="control-label">Note</label>
      <textarea class="form-control" id="newitemdata" name="newitemdata"></textarea>
    </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="SaveItem">Save changes</button>
      </div>
    </div>
  </div>
</div>

Open in new window

jQuery
<script>
$(function() {
  // Stores the button that was clicked
  var target;
  
  // initialise the list
  $.ajax({
    url: 't1729.php',
    data: {action: 'serverRender'},
    dataType: 'JSON',
    type: 'POST'
  }).done(function(resp) {
    $('#items').html(resp.html);
  });
  
  // Set which button was clicked so we know
  // method to use
  $('#NewItem').on('show.bs.modal', function(e) {
    target = e.relatedTarget;
  });
  
  // Called when save button is clicked
  $('#SaveItem').click(function() {
  // Hide the modal
    $('#NewItem').modal('hide')
  
    // Serialize the data from the form
    var data = $('#NewItemForm').serialize();
  
    // Add the action based on the value
    // we saved on form show
    var action = $(target).data('type');
  
    // Save the item we are adding
    var newitemdata = $('#newitemdata').val();
  
    // Clear the textarea for the next time
    $('#newitemdata').val('');
    
    // Add the action to the query
    data += '&action=' + action;
    
    // AJAX the data to the script
    $.ajax({
      url: 't1729.php',
      data: data,
      dataType: 'JSON',
      type: 'POST'
    }).done(function(resp) {
      if (resp) {
        // Server Render so just replace the 
        // html in the list with the server
        // rendered html
        if (resp.action == 'serverRender') {
          $('#items').html(resp.html);
        }
    
        // JSON return - run through
        // the items in the JSON, dynamically
        // create an <li> and append it to the
        // list
        else if (resp.action == 'serverJSON') {
          $('#items').empty();
          for(var i in resp.items) {
            $('<li/>').html(resp.items[i]).appendTo('#items');
          }
        }
    
        // None of the above so add the saved value to the list
        else {
          $('<li/>').html(newitemdata).appendTo('#items');
        }
      }
    });
  });
});
</script>

Open in new window

Working sample here
1
 

Author Closing Comment

by:EICT
ID: 41848477
Thank you Julian this is brilliant. Thanks for your time on this, excellent solution.
0
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 41848506
You are most welcome.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article discusses four methods for overlaying images in a container on a web page
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question