vb.org Archive

vb.org Archive (https://vborg.vbsupport.ru/index.php)
-   vBulletin 3 Articles (https://vborg.vbsupport.ru/forumdisplay.php?f=187)
-   -   Intergrating AJAX Technology Into Your Modifications (https://vborg.vbsupport.ru/showthread.php?t=93249)

Zero Tolerance 07-30-2005 10:00 PM

Intergrating AJAX Technology Into Your Modifications
 
This How-To will show you how to use the defined AJAX functions within vBulletin so developers can see how easily it is to intergrate AJAX technology into modifictions. Please note this tutorial is aimed at developers with some javascript knowledge.

Step 1 - Understand AJAX:

As many of you will know, AJAX gives the ability to pass data through a stream and recieve any data returned with no reloading, so if you're thinking of intergrating AJAX then you must first have a scenario where you wish to push data and recieve it, recieval is not required however is probably the best part of AJAX in a users opinion due to the dynamic changes that occur to present the recieved data.

Step 2 - Setting Up AJAX:

Okay, so you want to set up AJAX, real easy, the first step is to create an AJAX Object, this can be done with ease using the vBulletin set-up, an example is below:
Code:

My_AJAX_Object = new vB_AJAX_Handler(true);
You'll notice the one and only passive variable here for the function 'vB_AJAX_Handler' is set to 'true', this determines wether to use asynchronous or not, set to false if you do not desire to use it, if you're unsure leave this set to true.

So now you have your AJAX Object set up, before firing data you'll need to to set the object to respond to a function for when it recieves data, an example is below:
Code:

My_AJAX_Object.onreadystatechange(My_AJAX_Reciever);
Here the parameter is not so much a variable, but infact a function name, in this case i put 'My_AJAX_Reciever', so that function must exist, an example function is below:
Code:

function My_AJAX_Reciever()
{
        if (My_AJAX_Object.handler.readyState == 4 && My_AJAX_Object.handler.status == 200 && My_AJAX_Object.handler.responseText)
        {
                alert('Data recieved successfully\n\n' + My_AJAX_Object.handler.responseText)
        }
}

This function pretty much checks the stream has loaded and sent data back to the browser, upon success it will alert you to say it was successful, and the data it recieved. How you handle the data is upto you.

Step 3 - Firing And Recieving Data:

So now you want to fire some data through AJAX, and get some back, let's first look how we fire data:
Code:

My_AJAX_Object.send('myfile.php', 'do=ajax&pagevar=text');
Let's take a quick overlook at the parameters used here:

Parameter 1 - The file you want to send the data to.
Parameter 2 - Post variables you want to send through.
In most cases your post variables (parameter 2) would fluxuate, and you may want to send some variables that users have inputted, if so you may want to take advantage of vBulletin's javascript emulation of urlencode(), first off you'd parse the variable in javascript before firing off, as shown below:
Code:

My_Variable = PHP.urlencode(My_Variable);
This makes the variable safe for the stream to send the data, however some characters will be broken, to fix these in your php when collecting the variable you would parse it like so:
PHP Code:

$My_Variable convert_urlencoded_unicode($My_Variable); 

Okay, so you've now fired data off to 'myfile.php', with the variables: do (ajax) and pagevar (text). Now comes the PHP part, where you handle the data and output some back to be recieved:
PHP Code:

if ($_POST['do'] == 'ajax')
{
    echo 
$_POST['pagevar'];
    exit;


Simple as that? Pretty much, ofcourse the desired data to be sent back due to the data sent is completely up to you, if you've set the javascript up with the examples used above you should get a message saying:
Quote:

Data recieved successfully

text
So if you're not sure, what the PHP outputs AJAX grabs, and just to ensure the script ends there it's best to make PHP stop execution of any code underneath by using exit;, this ofcourse it not required, just likely in most situations :)
Remember, to grab using AJAX what PHP outputted, the code is My_AJAX_Object.responseText

Final Line - Handling Data and Dynamics:

So you've managed to successfully fire some data off, and got some back, now you want to fiddle with it in Javascript and make changes to your page?
Then i'm afraid you're on your own for that job, how you handle the recieved data is completely upto you and the scenario you're using AJAX in.

If you wish to see more information on AJAX, i suggest you look at this tutorial i wrote a while ago for vBulletin.org, it includes more information on AJAX than posted here :)

https://vborg.vbsupport.ru/showthread.php?t=81626

Any questions/problems reply here and i'll try to resolve them for you, the code above is all written off the top of my head, but i don't see any errors myself, feel free to report them to me though :)

- Zero Tolerance

Christine 07-31-2005 01:00 AM

Thank you!! :)

calorie 07-31-2005 01:02 AM

Yep, thanks for the toot. :)

Brad 08-03-2005 09:23 AM

Quote:

Originally Posted by Zero Tolerance
You'll notice the one and only passive variable here for the function 'vB_AJAX_Handler' is set to 'true', this determines wether to use asynchronous or not, set to false if you do not desire to use it, if you're unsure leave this set to true.

Just to add to this:

Asynchronously:

Processing is done in the backround and allows the user to use do other things on the page while the request is begin made and returned. You should use this is most cases

Synchronously:

Page is 'locked' until request is made and data is returned to the browser. This should not be used often because if there is a connection timeout or other issues the user will be left with a page that will not function.

yoyoyoyo 08-03-2005 10:12 AM

excellent info! thanks

TCM 08-07-2005 05:11 AM

This helps a lot, thanks!

Logikos 08-23-2005 09:59 PM

I have a question/problem. I've read this over and over untill my eyes hurt, and I can't seem to get it to work. Here is the code I'm using:


test.js includes:
Code:

My_AJAX_Object = new vB_AJAX_Handler(true);
My_AJAX_Object.onreadystatechange(My_AJAX_Reciever);

function My_AJAX_Reciever()
{
        if (My_AJAX_Object.readyState == 4 && My_AJAX_Object.status == 200 && My_AJAX_Object.responseText)
        {
                alert('Data recieved successfully\n\n' + My_AJAX_Object.responseText)
        }
}

My_Variable = PHP.urlencode(My_Variable);
My_AJAX_Object.send('test.php', 'do=ajax&pagevar=text');

My PHP file contains:
PHP Code:

<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT''test');

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array();

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
require_once('./global.php');

$My_Variable convert_urlencoded_unicode($My_Variable);  

 if (
$_POST['do'] == 'ajax')
{
     echo 
$_POST['pagevar'];
    exit;
}  

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" lang="en">
<head>
<script type="text/javascript" src="clientscript/test.js"></script>
    <title>Test</title>
</head>
<body>

What Do I place here??????


I don't understand what I place in the HTML part? Could you please show some code example. The PHP/Java/HTML. :) Thanks

Zero Tolerance 08-27-2005 09:49 PM

Code:

My_Variable = PHP.urlencode(My_Variable);
No doubt you'll get a JS error on that line, because "My_Variable" is undefined, you can remove that line.

Also the HTML would just include the JS file, ie:
HTML Code:

<script type="text/javascript" src="clientscript/test.js"></script>
As I stated in the main post, getting the JS to change the html on the page dynamically is up to you, it is recommended you know Javascript really. If you would like to look at a working example i'd suggest looking at my vBShout for 3.5 really.

- Zero Tolerance

Logikos 08-27-2005 11:20 PM

Thanks Scott, I've been reading alot of tutorials, and I've been studying your code with your shoutbox hack. I'm slowly getting the hang of it, but it is going to take alot of time.

I'm in the middle of a project and I am making the core of the project all ajax. I've figured out how to do a few things; one thing I?m trying to do is open new pages without reload. I see GMail does that, and I believe it has to do with Iframes, but I?m not sure. I'll get it eventually, I've pored many late nights reading so, I better get it soon! :p

jugo 08-28-2005 01:31 AM

Quote:

Originally Posted by Live Wire
I see GMail does that, and I believe it has to do with Iframes


LiveWire

i think it has more to do with DIVs than iFrames....but i could be wrong.

Akex 09-03-2005 09:44 PM

First, thank you for this tutorial, very helpful.

You forgot to put one key world in your javascript code : handler

So this code :

Code:

function My_AJAX_Reciever()
{
        if (My_AJAX_Object.readyState == 4 && My_AJAX_Object.status == 200 && My_AJAX_Object.responseText)
        {
                alert('Data recieved successfully\n\n' + My_AJAX_Object.responseText)
        }
}

Becomes

Code:

function My_AJAX_Reciever()
{
        if (My_AJAX_Object.handler.readyState == 4 && My_AJAX_Object.handler.status == 200 && My_AJAX_Object.handler.responseText)
        {
                alert('Data recieved successfully\n\n' + My_AJAX_Object.handler.responseText)
        }
}

;)

harmor19 10-02-2005 02:04 AM

I did the code above but it didn't work at first.
I changed the $_POST to $_GET then I passed test.php?do=ajax&pagevar=rrr in the address bar and it worked.
But using $_GET is insecure.

Can someone make a small working example like a simple chat?

Jenta 10-02-2005 02:38 AM

look at vbshout
its like a simple chat

DaFire 12-26-2005 01:46 PM

the missing .handler. should really added to the first posts example ;)

PennylessZ28 12-26-2005 10:47 PM

this was very useful, thanks

DaFire 12-28-2005 06:06 PM

yes ;) it's great start to integrate own ajax things.. I used rico.js but looks like it creates problems with some vb javascript so I change everything to vb-ajax now :)

MP3 06-25-2006 07:33 PM

For the JavaScript written in post 7 by " LiveWire " how can we add auto refresh so every 5 min it will check certain variables in a PHP file if its exist then small popup will shown if no nothing will happen and all of this will happen without the manually refresh.

rogersnm 07-02-2006 01:49 PM

so for the:
PHP Code:

if ($_POST['do'] == 'ajax')
{
    echo 
$_POST['pagevar'];
    exit;


could i change it to:
PHP Code:

if ($_POST['do'] == 'ajax')
{
    echo 
$_POST['$variable'];
    exit;


if $variable is defined in the global_start?

akanevsky 07-02-2006 02:44 PM

Yes.

rogersnm 07-02-2006 02:53 PM

PHP Code:

if ($_POST['do'] == 'ajax')
{
    echo 
$_POST[$i] . '|||';
    echo 
$_POST[$really] . '|||';
    echo 
$_POST[$suck] . '|||';
    exit;


So once i have done that can i just put $suck in a template and it will automatically refresh when the user clicks a link?

What should i use for onclick?: eg <a href='#' onclick='return Who knows'>Refresh</a>

DOES ANYONE HAVE A WORKING EXAMPLE OF THIS?

Andrew Green 08-02-2006 05:02 PM

Quote:

Originally Posted by rogersnm
DOES ANYONE HAVE A WORKING EXAMPLE OF THIS?


ok, here is a VERY stripped down demo as a standalone file, just put it in your main forum folder (ex. "forum") and name it "ajax.php"

All it does is give you the current time on a 1 sec refresh. Not something particullarly useful as there are far better ways to do this, but hopefully it helps.


PHP Code:

<?php
    
require_once('global.php');

if(
$_POST['do']=="time")
{
    echo 
date('h:i:s A');
        exit;
}
else if(
$_POST['do']=="time24")
{
    echo 
date('H:i:s');
    exit;
}
else
{
echo
"

<html>
<head>
<script type=\"text/javascript\" src=\"clientscript/vbulletin_global.js\"></script>
<script type=\"text/javascript\" src=\"clientscript/vbulletin_menu.js\"></script>

<script language='javascript'>

function starttimer()
{
loadurl();
timer=setTimeout(\"starttimer()\",1000);  // Sets the time out in milliseconds, 1000 = 1 second
}

function stoptimer()
{
clearTimeout(timer);
}

function loadurl() 

    xmlhttp = new vB_AJAX_Handler(true);

    xmlhttp.onreadystatechange(triggered);

    xmlhttp.send('ajax.php', 'do=time');
    // switch to 'do=time24' to change to 24 hour clock
    


function triggered() 


    if (xmlhttp.handler.readyState == 4 && xmlhttp.handler.status == 200 && xmlhttp.handler.responseText)
    {
        document.getElementById(\"output\").innerHTML = xmlhttp.handler.responseText; 

        // If you where adding to a page, as in a chat room you could try something along these lines
        // document.getElementById(\"output\").innerHTML += \"<br>\" + xmlhttp.handler.responseText; 

    }
}
</script>


</head>

<body onload='starttimer()' onunload='stoptimer()'>
    
     <div id='output'></div> 
 
</body>
</html>

"
;
}
?>


rogersnm 08-02-2006 07:08 PM

i did get it to work since whenever i posted that which was a month ago today..

Andrew Green 08-02-2006 08:17 PM

Well maybe someone else will find it useful then :)

rogersnm 08-03-2006 06:09 AM

the timer thing is useful though :)

Andrew Green 08-03-2006 12:51 PM

Quote:

Originally Posted by rogersnm
the timer thing is useful though :)


And as a side note on that, timers on main pages can be dangerous, especially with low timeouts. Server load goes up.

Renmiri 08-05-2006 11:11 PM

Great tutorial, thanks!

rogersnm 08-06-2006 03:40 PM

not if you set it for 15 seconds (well, not as much.)

HaMaDa4eVeR 08-18-2006 12:59 PM

great topic :)

what's the better way to pick the members list throgh AJAX,
example: if I've in my hack's field require to input members username, what I should to do to bring the similer username,

HaMaDa4eVeR 08-27-2006 06:54 AM

Up

are you there

Wongod 09-29-2006 06:25 AM

Is there anything special that you need to do to get ajax working on non-forum pages? Does vbulletin has some kind of security that prevents it from giving responses to files outside the forum directory? Because I have not been able to get it to work from my root directory. It will send out but never come back with a response.

rogersnm 10-27-2006 09:48 AM

Are you sure it sends out did you include the JS file which homes the ajax wrapper? You could of course just code your own ajax wrapper.

mrpaint 10-27-2006 11:57 AM

HTML Code:

function doTheTask() {
        do_box = new vB_AJAX_Handler(true)
        do_box.onreadystatechange(do_box_Done)
        do_box.send('url','&var1=1&var2=2')
                               
        do_button = new vB_AJAX_Handler(true)
        do_button.onreadystatechange(do_button_Done)
        do_button.send('url')                                                       
}                       
function do_box_Done() {
        if (do_box.handler.readyState == 4 && do_box.handler.status == 200) {
                ....
        }       
}
function do_button_Done() {
        if (do_button.handler.readyState == 4 && do_button.handler.status == 200) {
                ....
        }                       
}

I added this script but I have got this error message:
Quote:

Error: do_box is not defined
Line: if (do_box.handler.readyState == 4 && do_box.handler.status == 200) {
And this one
Quote:

Error: do_button is not defined
Line: if (do_button.handler.readyState == 4 && do_button.handler.status == 200) {
Anybody help me?

PS: I posted this question here (https://vborg.vbsupport.ru/showpost....7&postcount=17) but no body answered....

IdanB 07-08-2009 04:25 PM

Thank you !!
Excellent tutorial guide, very useful information :)

mokujin 01-13-2013 07:13 PM

Hi, have anychange for vBb 4.2 or it's just for vbb 3.x?
Thank you


All times are GMT. The time now is 06:05 PM.

Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2024, vBulletin Solutions Inc.

X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.01483 seconds
  • Memory Usage 1,851KB
  • Queries Executed 10 (?)
More Information
Template Usage:
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (9)bbcode_code_printable
  • (2)bbcode_html_printable
  • (7)bbcode_php_printable
  • (7)bbcode_quote_printable
  • (1)footer
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (6)option
  • (1)post_thanks_navbar_search
  • (1)printthread
  • (34)printthreadbit
  • (1)spacer_close
  • (1)spacer_open 

Phrase Groups Available:
  • global
  • postbit
  • showthread
Included Files:
  • ./printthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/class_bbcode_alt.php
  • ./includes/class_bbcode.php
  • ./includes/functions_bigthree.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • printthread_start
  • bbcode_fetch_tags
  • bbcode_create
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • printthread_post
  • printthread_complete