Step 5: Using AJAX to Submit & Save Content

Example file: example5.php

AJAX post will send our page’s data to the server using XMLHttpRequest:

let xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
xhr.send(postData);

To simplify our code, we created a script so that you can call an AJAX post with a single line of code. To use the script, we include cms.css & cms.js files:

<link href="assets/cms/cms.css" rel="stylesheet" type="text/css" />
<script src="assets/cms/cms.js"></script> 

In this step we will change our previous FORM method with AJAX post method for submitting content. This allows you to save content without reloading the page.

For more info on AJAX, you may want to check: https://www.w3schools.com/xml/ajax_intro.asp

Then we initialize a UI object. 

var data = {};
data.post_id = <!--?php echo $id; ?-->;
data.post_content = obj.html(); 
data.post_styles = obj.styles();
data.post_js = obj.js();

var ui = new UI();
ui.ajaxPost(data, 'savepage.php');

We need to construct the data first and also prepare another page called savepage.php for saving our page’s data. Our previous sql update (see step 2) is moved to this page. Then we call ajaxPost() method to submit the data to the savepage.php.

Our UI object also has a method for showing info on the screen that can be useful for displaying the ‘Saving..’ status.

ui.showInfo('Saving..');

To hide the info, we’ll use:

ui.hideInfo();

And if you’d like to show the info and auto hide it after 2 seconds, you can use:

ui.showInfo('Your message', 2000);

We use these methods in our example to inform user the status of the saving process. For the complete code and to try the example, please open in your browser example5.php.

http://localhost/mysite/example5.php?edit=y

When saving, you will see the ‘Saving…’ status on the top of the screen.

About | Privacy | Delivery & Return

Copyright © 2021 Insite Mitra Inovindo. All Rights Reserved.