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 Documenttitle>
<
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
if (isset ($_GET['link'])) {
loadLink();
}
if (isset (
$_GET['name'])) {
loadForm();
}
if (isset (
$_GET['name2'])) {
loadForm2();
}

function 
loadForm(){
echo 
''.'Name:'.$_GET['name'].' , email:'.$_GET['email'].', phone:'.$_GET['phone'].''
;
}

function 
loadForm2(){
echo 
''.'Name2:'.$_GET['name2'].' , email2:'.$_GET['email2'].', phone2:'.$_GET['phone2'].'';
}

function 
loadLink(){
echo 
'Its XOOPS of course!';
}

//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 .= "n";
        
$content .= "n";
        
$content .= ""._AM_OLEDRION_ATTRIBUTE_DEFAULT_VALUE.""._AM_OLEDRION_ATTRIBUTE_TITLE.""._AM_OLEDRION_ATTRIBUTE_VALUE."";
        if(
oledrion_utils::getModuleOption('use_price')) {
            
$content .=""._AM_OLEDRION_ATTRIBUTE_PRICE."";
            
$span++;
        }
        if(
oledrion_utils::getModuleOption('attributes_stocks')) {
            
$content .=""._AM_OLEDRION_ATTRIBUTE_STOCK."";
            
$span++;
        }
        
$content .=""._AM_OLEDRION_ACTION."n";
        
$content .= "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 .=".$class."'>n";
                
$checked '';
                if(
$option['value'] == $defaultValue) {
                    
$checked "checked = 'checked' ";
                }
                
$content .= "$counter$checked/>n";
                
$content .= "$counter' id='names$counter' size='15' maxlength='255' value='".$option['name']."' />n";
                
$content .= "$counter' id='value$counter' size='15' maxlength='255' value='".$option['value']."' />n";
                if(
oledrion_utils::getModuleOption('use_price')) {
                    
$content .= "$counter' id='price$counter' size='15' maxlength='10' value='".$option['price']."' />n";
                }
                if(
oledrion_utils::getModuleOption('attributes_stocks')) {
                    
$content .= "$counter' id='stock$counter' size='15' maxlength='10' value='".$option['stock']."' />n";
                }
                
// Les actions
                
$content .= "";
                
// Suppression
                
$content .= "$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 .= "$up' title='$up' style='border: 0; cursor:pointer;' name='btnUp-$counter' id='btnUp-$counter' src='".OLEDRION_IMAGES_URL."smallup.png' />";
                } else {
                    
$content .= ".OLEDRION_IMAGES_URL."blankholder.png' />";
                }
                if(
$counter $optionsCount 1) {    // Down
                    
$content .= "$down' title='$down' style='border: 0; cursor:pointer;' name='btnDown-$counter' id='btnDown-$counter' src='".OLEDRION_IMAGES_URL."smalldown.png' />";
                } else {
                    
$content .= ".OLEDRION_IMAGES_URL."blankholder.png' />";
                }
                
$content .= "n";
                
$content .= "n";
                
$counter++;
            }
        }
        
$class = ($class == 'even') ? 'odd' 'even';
        
$content .=".$class."'>n";
        
$content .= "$span' align='center'>._AM_OLEDRION_ATTRIBUTE_ADD_OPTION."' />n";
        
$content .= "n";

        
$content .= "n";
        
$content .= "$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

429 user(s) are online (282 user(s) are browsing Support Forums)


Members: 0


Guests: 429


more...

Donat-O-Meter

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

Latest GitHub Commits