11
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 11:44

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


This new version sends all ajax calls to same php page. Then the php page decides which php function to call depending on what was pressed on the html page.
Replace all code with this new.

Index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
title>Untitled Document</title>
<
script type="text/javascript" src="firebug.js"></script>
    <
script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<
script type="text/javascript">
$(
document).ready(function() {
// Form 1 will be processed by form1 php function
$(".button").click(function(event) {
var 
formContent = $("#contact").serialize();
    $(
"#box").load('myserv.php',formContent);
    });
// Form 2 get's sent to same php page but will be processed by diferent php function    
    
$(".button2").click(function(event) {
var 
formContent = $("#other").serialize();
//console.log(formContent2); //used with firebug
    
$("#box").load('myserv.php',formContent);
    });
// when you click on the link, it will go to the same php page, but load a diferent function    
    
$("#mylink").click(function(event){
var 
formContent ="link=1";
//console.log(formContent2); //used with firebug
    
$("#box").load('myserv.php',formContent);
    });
    
});
  
</
script>

</
head>

<
body>
  <
form name="contact" id="contact" action="">
      
Name
      
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
     
Email
      
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
      
Phone
      
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
        <
br />
      <
input type="button" name="button" class="button" id="button" value="Send" />
  </
form>
  
  <
br /><br />
    <
form name="other" id="other" action="">
      
Name2
      
<input type="text" name="name2" id="name2" size="30" value="" class="text-input" />
     
Email2
      
<input type="text" name="email2" id="email2" size="30" value="" class="text-input" />
      
Phone2
      
<input type="text" name="phone2" id="phone2" size="30" value="" class="text-input" />
        <
br />
      <
input type="button" name="button2" class="button2" id="button2" value="Send" />
  </
form>

 <
a href="#" id="mylink">Do you know which cms is the best?</a>

<
br />
<
div id="box"></div>
</
body>
</
html>


myserv.php
<?php
if (isset ($_GET['link'])) {
loadLink();
}
if (isset (
$_GET['name'])) {
loadForm();
}
if (isset (
$_GET['name2'])) {
loadForm2();
}

function 
loadForm(){
echo 
'<span style="background-color:#00CCFF">'.'Name:'.$_GET['name'].' , email:'.$_GET['email'].', phone:'.$_GET['phone'].'</span>';
}

function 
loadForm2(){
echo 
'<span style="background-color:#00CCFF">'.'Name2:'.$_GET['name2'].' , email2:'.$_GET['email2'].', phone2:'.$_GET['phone2'].'</span>';
}

function 
loadLink(){
echo 
'<span style="background-color:#00CCFF">Its XOOPS of course!</span>';
}

//echo 'Name:'.$_GET['name'].' , email:'.$_GET['email'].', phone:'.$_GET['phone'];
?>

12
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 11:47

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


See a demo at my site:

Demo

13
frankblack
Re: Ajax calls directly from Jquery
  • 2009/8/20 12:24

  • frankblack

  • Just can't stay away

  • Posts: 830

  • Since: 2005/6/13


This serialize is nice, but I need some more values, that are not inside a form. How would this be passed?

Like this?
var formContent = $("#selecter").serialize();
$(
"#tvlistresponse").load("'.DEBASER_URL.'/ajaxed.php?gettv=1", { formContentjustanothervar $justanothervar });


This will take me some time to rewrite the whole xajax stuff.

14
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 12:53

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


Frankblack: There are 2 possibilities (probably more..):
1- Create a hidden form field
<input type="hidden" name="gettv" id="gettv" value="1" />

2- pass it in javascript var with concatenation:
var formContent = $("#other").serialize()+'&gettv=1';

3- You could also pass it through $.load() but I haven't experimented with it.

What do you think of jquery compared to xajax?

15
hervet
Re: Ajax calls directly from Jquery
  • 2009/8/20 12:56

  • hervet

  • Friend of XOOPS

  • Posts: 2267

  • Since: 2003/11/4


This is an example from the futur version of Olédrion:
jQuery().ready(function() {
    var 
attribute_id_Value jQuery('#attribute_id').val();
    
jQuery('#ajaxOptions').load('index.php', {op'attributes'action'ajaxoptions'attribute_idattribute_id_Value});

    
jQuery('img.btnremove').live("click", function() {
        if(
confirm(confirmDelete)) {
            var 
optionId jQuery(this).attr('id').replace('btnremove-','');
            var 
formContent jQuery("#frmattributes").serialize();
            
jQuery('#ajaxOptions').load('index.php', {op'attributes'action'ajaxoptions'subaction'delete'optionoptionIdattribute_idattribute_id_ValueformcontentformContent});
        }
    });

    
jQuery('img.btnUp').live("click", function() {
        var 
optionId jQuery(this).attr('id').replace('btnUp-','');
        var 
formContent jQuery("#frmattributes").serialize();
        
jQuery('#ajaxOptions').load('index.php', {op'attributes'action'ajaxoptions'subaction'up'optionoptionIdattribute_idattribute_id_ValueformcontentformContent});
    });

    
jQuery('#attribute_type').change(function() {
        
attributeParameters();
    });
    
attributeParameters();

    
jQuery('img.btnDown').live("click", function() {
        var 
optionId jQuery(this).attr('id').replace('btnDown-','');
        var 
formContent jQuery("#frmattributes").serialize();
        
jQuery('#ajaxOptions').load('index.php', {op'attributes'action'ajaxoptions'subaction'down'optionoptionIdattribute_idattribute_id_ValueformcontentformContent});
    });

    
jQuery('#bntAdd').live("click", function() {
        var 
formContent jQuery("#frmattributes").serialize();
        
jQuery('#ajaxOptions').load('index.php', {op'attributes'action'ajaxoptions'subaction'add'attribute_idattribute_id_ValueformcontentformContent});
 });
});

16
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 13:19

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


Hervet: I see your passing parameters through $.load() which is exactly the one I haven't tested
I've just been reading about $.live() and it's very usefull for when you have new events through ajax and want to bind actions to them.
I like your function "jQuery('img.btnremove')", very handy to provide an alert window "are you sure" then perform an action.
What do you think of Jquery? Are you incorporating more javascript into your modules thanks to it?
I always saw you as a PHP master, now I see you are expanding your realm

17
frankblack
Re: Ajax calls directly from Jquery
  • 2009/8/20 13:23

  • frankblack

  • Just can't stay away

  • Posts: 830

  • Since: 2005/6/13


Quote:
What do you think of jquery compared to xajax?


Short: different! Long: this would save me some bytes, but this also means rewriting a few things and a few more things to learn. I don't know if jquery is faster than xajax. xajax makes it fairly easy, because you do not have to write so much javascript stuff.

@hervet: thx for your snippet. May I get another one from you? What is inside index.php and how do you catch the ajax events there? TIA

18
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 14:22

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


@hervet: I would also like to see your index.php to see how you catch ajax

19
hervet
Re: Ajax calls directly from Jquery
  • 2009/8/20 16:05

  • hervet

  • Friend of XOOPS

  • Posts: 2267

  • Since: 2003/11/4


Quote:

kaotik wrote:
Hervet: I see your passing parameters through $.load() which is exactly the one I haven't tested

It depends of the cases

Quote:

I've just been reading about $.live() and it's very usefull for when you have new events through ajax and want to bind actions to them.

Yes I'm also using it, it is present in my code :
jQuery('img.btnremove').live("click", function() {

It's been a disapointment for me when I decided to use jQuery because with Prototype it's automatic, you don't have to bind your events.
But now it's a core function of the last jQuery version (and not aplugin anymore).

Quote:

I like your function "jQuery('img.btnremove')", very handy to provide an alert window "are you sure" then perform an action.

That's why it is used for

Quote:

What do you think of Jquery?

I've been using Prototype for 2 years but decided to leave it for jQuery, much more plugins, much more updates and more handy to use, but Prototype has some interesting functions for arrays in Javascript

Quote:

Are you incorporating more javascript into your modules thanks to it?

Yes sure !
I never understood why xajax was used when you see the ease of use of AJAX in jQuery or in Prototype.

Quote:

I always saw you as a PHP master, now I see you are expanding your realm

Nowadays you don't have the choice, you use Javascript or your die
I've been subjugated by the code of jQuery.
John Resig is surely one of the best developper in the world.


Quote:

@hervet: I would also like to see your index.php to see how you catch ajax

You will soon see it in the next version of Olédrion (september)

If you want a reference to a good reading :
http://www.jsmag.com/
and it is not expensive.
Concerning jQuery, if you have a bit of money, I recommend you those two books:
http://www.packtpub.com/learning-jquery-1.3/book
http://www.packtpub.com/user-interface-library-for-jquery/book


Here is the part in charge of the Ajax response in the Php script:
if(!isset($xoopsUser) || !is_object($xoopsUser)) {
            exit;
        }
        if(!
oledrion_utils::isAdmin()) {
            exit;
        }
        
error_reporting(0);
        @
$xoopsLogger->activated false;
        
$attribute_id = isset($_POST['attribute_id']) ? intval($_POST['attribute_id']) : 0;
        
$content $class '';
        
$attribute null;
        
$counter 0;
        
$options = array();
        
$delete _OLEDRION_DELETE;
        
$span 4;

        if(!isset(
$_SESSION['oledrion_attribute'])) {
            if(
$attribute_id == 0) {    // Création, rajouter une zone
                
$attribute $oledrion_handlers->h_oledrion_attributes->create(true);
            } else {
                
$attribute $oledrion_handlers->h_oledrion_attributes->get($attribute_id);
                if(!
is_object($attribute)) {
                    return 
null;
                }
            }
        } else {
            
$attribute unserialize($_SESSION['oledrion_attribute']);
        }

        if(isset(
$_POST['formcontent'])) {    // Traitement du contenu actuel
            
$data = array();
            
parse_str(utf8_decode(urldecode($_POST['formcontent'])), $data);
            
$optionsCount = isset($data['optionsCount']) ? intval($data['optionsCount']) : 0;
            for(
$i 0$i $optionsCount$i++) {
                
$name $value $price $stock '';
                
$name = isset($data['name'.$i]) ? $data['name'.$i] : '';
                
$value  = isset($data['value'.$i]) ? $data['value'.$i] : '';
                
$price  = isset($data['price'.$i]) ? $data['price'.$i] : '';
                
$stock  = isset($data['stock'.$i]) ? $data['stock'.$i] : '';
                
$attribute->setOptionValue($i$name$value$price$stock);
            }
            if(isset(
$data['default'])) {
                
$defaultIndex intval($data['default']);
                
$defaultValue = isset($data['value'.$defaultIndex]) ? $data['value'.$defaultIndex] : '';
                
$attribute->setVar('attribute_default_value'$defaultValue);
                unset(
$defaultValue);
            }
        }

        if(isset(
$_POST['subaction'])) {
            switch(
xoops_trim(strtolower($_POST['subaction']))) {
                case 
'delete':    // Suppression d'une option de l'attribut
                    
$option = isset($_POST['option']) ? intval($_POST['option']) : false;
                    if(
$option !== false) {
                        
$attribute->deleteOption($option);
                    }
                    break;

                case 
'add':    // Ajout d'une option vide (à la fin)
                    
$attribute->addEmptyOption();
                    break;

                case 
'up':    // Déplacement d'une option vers le haut
                    
$option = isset($_POST['option']) ? intval($_POST['option']) : false;
                    if(
$option !== false) {
                        
$attribute->moveOptionUp($option);
                    }
                    break;

                case 
'down':    // Déplacement d'une option vers le haut
                    
$option = isset($_POST['option']) ? intval($_POST['option']) : false;
                    if(
$option !== false) {
                        
$attribute->moveOptionDown($option);
                    }
                    break;
            }
        }
        
$_SESSION['oledrion_attribute'] = serialize($attribute);

        
$content .= "<table border='0'>n";
        
$content .= "<tr>n";
        
$content .= "<th align='center'>"._AM_OLEDRION_ATTRIBUTE_DEFAULT_VALUE."</th><th align='center'>"._AM_OLEDRION_ATTRIBUTE_TITLE."</th><th align='center'>"._AM_OLEDRION_ATTRIBUTE_VALUE."</th>";
        if(
oledrion_utils::getModuleOption('use_price')) {
            
$content .="<th align='center'>"._AM_OLEDRION_ATTRIBUTE_PRICE."</th>";
            
$span++;
        }
        if(
oledrion_utils::getModuleOption('attributes_stocks')) {
            
$content .="<th align='center'>"._AM_OLEDRION_ATTRIBUTE_STOCK."</th>";
            
$span++;
        }
        
$content .="<th align='center'>"._AM_OLEDRION_ACTION."</th>n";
        
$content .= "</tr>n";

        
$up _AM_OLEDRION_ATTRIBUTE_MOVE_UP;
        
$down _AM_OLEDRION_ATTRIBUTE_MOVE_DOWN;
        
$defaultValue xoops_trim($attribute->getVar('attribute_default_value''e'));

        
$options $attribute->getAttributeOptions('e');
        
$optionsCount count($options);

        if(
$optionsCount 0) {
            foreach(
$options as $option) {
                
$class = ($class == 'even') ? 'odd' 'even';
                
$content .="<tr class='".$class."'>n";
                
$checked '';
                if(
$option['value'] == $defaultValue) {
                    
$checked "checked = 'checked' ";
                }
                
$content .= "<td align='center'><input type='radio' name='default' id='default' value='$counter$checked/></td>n";
                
$content .= "<td align='center'><input type='text' name='name$counter' id='names$counter' size='15' maxlength='255' value='".$option['name']."' /></td>n";
                
$content .= "<td align='center'><input type='text' name='value$counter' id='value$counter' size='15' maxlength='255' value='".$option['value']."' /></td>n";
                if(
oledrion_utils::getModuleOption('use_price')) {
                    
$content .= "<td align='center'><input type='text' name='price$counter' id='price$counter' size='15' maxlength='10' value='".$option['price']."' /></td>n";
                }
                if(
oledrion_utils::getModuleOption('attributes_stocks')) {
                    
$content .= "<td align='center'><input type='text' name='stock$counter' id='stock$counter' size='15' maxlength='10' value='".$option['stock']."' /></td>n";
                }
                
// Les actions
                
$content .= "<td align='center'>";
                
// Suppression
                
$content .= "<img class='btnremove' alt='$delete' title='$delete' style='border: 0; cursor:pointer;' name='btnremove-$counter' id='btnremove-$counter' src='".OLEDRION_IMAGES_URL."smalldelete.png' />";
                if(
$counter 0) {    // Up
                    
$content .= "<img class='btnUp' alt='$up' title='$up' style='border: 0; cursor:pointer;' name='btnUp-$counter' id='btnUp-$counter' src='".OLEDRION_IMAGES_URL."smallup.png' />";
                } else {
                    
$content .= "<img src='".OLEDRION_IMAGES_URL."blankholder.png' />";
                }
                if(
$counter $optionsCount 1) {    // Down
                    
$content .= "<img class='btnDown' alt='$down' title='$down' style='border: 0; cursor:pointer;' name='btnDown-$counter' id='btnDown-$counter' src='".OLEDRION_IMAGES_URL."smalldown.png' />";
                } else {
                    
$content .= "<img src='".OLEDRION_IMAGES_URL."blankholder.png' />";
                }
                
$content .= "</td>n";
                
$content .= "</tr>n";
                
$counter++;
            }
        }
        
$class = ($class == 'even') ? 'odd' 'even';
        
$content .="<tr class='".$class."'>n";
        
$content .= "<td colspan='$span' align='center'><input type='button'' name='bntAdd'' id='bntAdd' value='"._AM_OLEDRION_ATTRIBUTE_ADD_OPTION."' /></td>n";
        
$content .= "</tr>n";

        
$content .= "</table>n";
        
$content .= "<input type='hidden' name='optionsCount' id='optionsCount' value='$counter' />n";
        echo 
utf8_encode($content);
        exit;

But without its context, it will not give you too much things ...

note, this part is important:
error_reporting(0);
 @
$xoopsLogger->activated false;

20
kaotik
Re: Ajax calls directly from Jquery
  • 2009/8/20 17:13

  • kaotik

  • Just can't stay away

  • Posts: 861

  • Since: 2004/2/19


@Hervet; I've been testing your code:
jQuery('img.btnremove').live("click", function() {}

and WOW! If I had discovered this sooner, I would have saved a LOT of headaches
I'll write another tutorial based on this.

Thanks for the book recommendations, I'm definitely considering buying "learning jquery"

Login

Who's Online

189 user(s) are online (139 user(s) are browsing Support Forums)


Members: 0


Guests: 189


more...

Donat-O-Meter

Stats
Goal: $100.00
Due Date: Mar 31
Gross Amount: $0.00
Net Balance: $0.00
Left to go: $100.00
Make donations with PayPal!

Latest GitHub Commits