Home » Php » javascript – Convert code from multiple div's to use Ajax instead

javascript – Convert code from multiple div's to use Ajax instead

Posted by: admin July 12, 2020 Leave a comment

Questions:

How it works is, the <div> content changes depending which <select> option they choose.

Instead of a bunch of <div>‘s I’d like to use ajax.
Unfortunately, I am not very good with ajax, but I want to learn to use it. If somebody could help point me in the right direction, it’d be great.

I’d like to make a general Ajax class, so I can use it anywhere in my framework. Then, if needed, extend another class from it.

You can see my PHP on my previous SO question: Change div according to dropdown boxes selected

JSFiddle

HTML

<form action="" method="post" name="create" target="_top">
    <fieldset>
        <ul class="create">
            <li>
                <label class="label" for="character_name">Character Name:</label>
                <input class="text" type="text" name="character_name" id="character_name" />
            </li>
            <li>
                <label class="label" for="character_gender">Gender:</label>
                <select class="character_gender select" name="character_gender" id="character_gender">
                    <option class="option" value="1">Female</option>
                    <option class="option" value="2">Male</option>
                </select>
            </li>
            <li>
                <label class="label" for="character_race">Character Race:</label>
                <select class="character_race select" name="character_race" id="character_race">
                    <option class="option" value="1">Goblin</option>
                    <option class="option" value="2">Human</option>
                    <option class="option" value="3">Undead</option>
                </select>
            </li>
            <li>
                <label class="label" for="character_class">Character Class:</label>
                <select class="character_class select" name="character_class" id="character_class">
                    <option class="option" value="1">Warrior</option>
                    <option class="option" value="2">Wizard</option>
                </select>
            </li>
            <li>
                <input class="submit-create-character" type="submit" name="create_character" value="Create" />
            </li>
        </ul>
    </fieldset>
</form>
<div class="class-info female-goblin-warrior">
    <div class="avatar-box">
        <img src="Female.Goblin.Warrior.gif" alt="Female Goblin Warrior" />
    </div>
    Goblin description.<br />
    Warrior Description
</div>
<div class="class-info male-goblin-warrior">
    <div class="avatar-box">
        <img src="Male.Goblin.Warrior.gif" alt="Male Goblin Warrior" />
    </div>
    Goblin description.<br />
    Warrior Description
</div>
<div class="class-info female-human-warrior">
    <div class="avatar-box">
        <img src="Female.Human.Warrior.gif" alt="Female Human Warrior" />
    </div>
    Human description.<br />
    Warrior Description
</div>
<div class="class-info male-human-warrior">
    <div class="avatar-box">
        <img src="Male.Human.Warrior.gif" alt="Male Human Warrior" />
    </div>
    Human description.<br />
    Warrior Description
</div>
<div class="class-info female-undead-warrior">
    <div class="avatar-box">
        <img src="Female.Undead.Warrior.gif" alt="Female Undead Warrior" />
    </div>
    Undead description.<br />
    Warrior Description
</div>
<div class="class-info male-undead-warrior">
    <div class="avatar-box">
        <img src="Male.Undead.Warrior.gif" alt="Male Undead Warrior" />
    </div>
    Undead description.<br />
    Warrior Description
</div>
<div class="class-info female-goblin-wizard">
    <div class="avatar-box">
        <img src="Female.Goblin.Wizard.gif" alt="Female Goblin Wizard" />
    </div>
    Goblin description.<br />
    Wizard Description
</div>
<div class="class-info male-goblin-wizard">
    <div class="avatar-box">
        <img src="Male.Goblin.Warrior.gif" alt="Male Goblin Wizard" />
    </div>
    Goblin description.<br />
    Wizard Description
</div>
<div class="class-info female-human-wizard">
    <div class="avatar-box">
        <img src="Female.Human.Wizard.gif" alt="Female Human Wizard" />
    </div>
    Human description.<br />
    Wizard Description
</div>
<div class="class-info male-human-wizard">
    <div class="avatar-box">
        <img src="Male.Human.Wizard.gif" alt="Male Human Wizard" />
    </div>
    Human description.<br />
    Wizard Description
</div>
<div class="class-info female-undead-wizard">
    <div class="avatar-box">
        <img src="Female.Undead.Wizard.gif" alt="Female Undead Wizard" />
    </div>
    Undead description.<br />
    Wizard Description
</div>
<div class="class-info male-undead-wizard">
    <div class="avatar-box">
        <img src="Male.Undead.Wizard.gif" alt="Male Undead Wizard" />
    </div>
    Undead description.<br />
    Wizard Description
</div>

CSS

.class-info {
    display: none
}

Javascript

var buildCharacter = function () {
    var character = {
        properties: {
            gender: '',
            race: '',
            class: ''
        },
        getCss: function () {
            return (this.properties.gender + '-' + this.properties.race + '-' + this.properties.class).toLowerCase();
        }
    };

    for (var prop in character.properties) {
        character.properties[prop] = $('#character_' + prop + ' :selected').text();
    }

    $('.class-info').hide();
    $('.' + character.getCss()).show();
};
buildCharacter();
$('.select').on('change', buildCharacter);

I started making a general Ajax class but I don’t actually think it’ll work for what I want.

Ajax.php

<?php /* /application/modules/Ajax/Ajax.php */

/**
 * Ajax
 *
 * The Ajax Class is used to get data from a Class and return the data.
 *
 */
class Ajax
{
    private $class;
    private $method;
    private $params;

    /**
     * __construct
     *
     * @access  public
     */
    public function __construct()
    {
        $this->params=$_POST;           # Call params
        $call=explode('->', $this->params['call']);

        if(method_exists($call[0], $call[1]))
        {
            $this->class=new $call[0];  # e.g. controller->method
            $this->method=$call[1];
            unset($this->params['call']);
            $this->parse();
        }
        else
        {
            throw new Exception('Method does not exist', E_RECOVERABLE_ERROR);
        }
    }

    public function parse()
    {
        $param=array();

        # Params in any order...
        $ref_method=new ReflectionMethod($this->class, $this->method);
        foreach($ref_method->getParameters() as $p)
        {
            $param[$p->name]=$this->params[$p->name];
        }
        $this->params=$param;

        $result_data=call_user_func_array(array($this->class, $this->method), $this->params);

        return $result_data;
    }
} # End Ajax class.
How to&Answers:

You should create small files like
“female_undead_wizard.html” and “male_goblin_warrior”

Then, either in the client side or the server side, you need to determine which html to load into your div.
It’s usually better to do things like that on the server side, but simpler on the client.

So for example on the client side, you can listen to all of the select changed events, and once you have enough data, you just need to load the html into your div.
Then a simple load (using jquery) can do the trick
So the html code can look something like:

...
<select id=genderSelect>...</select>
...
<div id="displayClassDiv"></div>

And in the script:

var gender= $("#genderSelect option:select").val();
//get all vals and check that exists here
...

var fileName=gender + "_" + race + "_" + class + ".html";
$("#displayClassDiv").load("<some path goes here>/" + fileName);

Answer:

I am not exactly sure what your concrete question is. I understand what you are trying to do, but I’m not sure what you do understand and which parts you don’t understand (yet). So that’s why I’ll try and give a short explanation on how you could go about using ajax in jquery.

You can call your PHP function with ajax and add extra POST or GET data to the request. You can then use that data in PHP to alternate the info you return.

You can use info on this page to see how to setup ajax request in js: http://api.jquery.com/jquery.ajax/
But it will probably look something like this:

j.ajax({
  url: '/ajax.php',
  data: {'characterClass': j('#character_class').val(), 'gender': j('#gender').val() },
  type: 'GET',
  success: function (data) {
      //do stuff to show what you want
  }
});

You can see that I’m sending gender and character class with data.

In your PHP ajax file you have to get this data (, which seems as if you’ve already setup to do so with $_POST) and return the info you want to return. You might want to json_encode it.

In the success function in JS ajax you can then insert the info into the page. You can use the data variable. I like to use console.log(data) to see how data is returned.

in short as a list:

  1. change value in select
  2. pick up change with select in js
  3. setup ajax with js and send form values as data to PHP
  4. get post data in PHP
  5. init desired function/returndata based post data
  6. return info/data
  7. pick up returndata in js ajax success
  8. use data to display info on page

I hope this answers (most or part) of your question.
Good luck!