adsense

How to Use Ajax in WordPress





1. Open the header.php file for the theme you use with your WordPress blog. Use a code editor or Notepad to open the file so you can work with the code. Find '
' just above your ending '
' tag and create a new line above the 'wp_head()' function. You should also write a call to 'wp_head()' if it does not already exist.
2. Add a set of script tags where you created a new line above the 'wp_head()' function and set its 'type' attribute to 'text/javascript' if your code is in XHTML or HTML 4. If you do not know, then add the 'type' attribute to be safe. Setting the 'type' attribute will not hurt anything when coding an HTML 5 document, though it is not necessary. Here is an example of the code so far:
// Your AJAX code will go here


3. Start your AJAX code between the script tags. Create a variable on the first line of the code that will hold the XMLHTTP object. The XMLHTTP object handles requests to the server for HTML and XML files, as well as text, PHP and ASP files.
var xmlhttp;

4. Create a conditional 'if-then' statement to check whether the browser is Internet Explorer (IE) 6 versus any other browser, such as Firefox or Chrome. Doing this ensures that IE 6 users can still use your website, though that browser does not support the object 'XMLHttpRequest.'
var xmlhttp;if(window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest();} else {xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');}

5. Write a function to check that the XMLHTTP object is ready. This means the page is loaded and the server returned no errors.xmlhttp.onreadystatechange = function() {if (xmlhttp.readyState == 4 xmlhttp.status == 200) {}}
6. Write your code to grab information from file within the 'if-then' statement that checks for the XMLHTTP object's readiness. You can set a part of your website to get the response text sent by a requested file, for example. Here is an example:document.getElementById('updates').innerHTML = xmlhttp.responseText;The above code will put the contents of the XMLHTTP object inside a pair of HTML tags that have the ID name 'updates.'
7. Write your code to get the content from a particular file. This tells the server where to look for the content you want to place on the page through AJAX. Here is an example:xmlhttp.open('GET', 'myupdates.txt', true);xmlhttp.send();Change 'myupdates.txt' to the file name of the document from where you want to pull your data. In this case, 'myupdates.txt' holds information you want to place on your page. The 'true' tells the server you want an asynchronous request.
8. After writing your JavaScript and AJAX code, save your header.php file and any other files you needed to edit. Upload the files to your server, including any files containing data that your AJAX code references.

Comments

0 Responses to "How to Use Ajax in WordPress"

Post a Comment

Popular Posts

About