Mysidia Adoptables Support Forum

Mysidia Adoptables Support Forum (http://www.mysidiaadoptables.com/forum/index.php)
-   Programming and Game Development (http://www.mysidiaadoptables.com/forum/forumdisplay.php?f=34)
-   -   Using Ajax with Mysidia (http://www.mysidiaadoptables.com/forum/showthread.php?t=4989)

Hwona 01-20-2016 01:32 AM

Using Ajax with Mysidia
 
Hello, everyone. I've recently been playing with ajax and php - trying to update a database table with values from a form in the template file. However, I everytime I submit the form, the browser returns an alert containing the whole html page - and the database never gets updated. Does anyone know how to work around this?

Kyttias 01-20-2016 03:16 AM

Because of the way the framework works, it's impossible... unless you bypass the framework. Create a new folder called "ajax" to store your php files for your ajax requests, and inside create an .htaccess file just for it containing the following line:

Code:

RewriteEngine Off
This will prevent the framework from rerouting the file through the index and rendering the entire page when a request is made.

Inside here you can have whatever html/php files you want - but you have NO access to Mysidia classes. So either you can have Ajax or you can have Mysidia, but you can't have both.

As example, an item search is going to use the following php file (to be stored in your new framework-free folder):
  Spoiler: PHP 
PHP Code:

<?php

function sanitizeInput($data) {
    
$data trim($data);
    
$data stripslashes($data);
    
$data htmlspecialchars($data);
    return 
$data;
}

function 
searchItems(){
    
$search_itemname sanitizeInput($_POST['search_itemname']);
    
$search_category sanitizeInput($_POST['search_category']);

    
$conditions = array();

    if(
$search_itemname != "") { $conditions[] = "itemname LIKE '%" $search_itemname "%'";   } else {  $conditions[] = "itemname LIKE '%'"; }
    if(
$search_category != "") { $conditions[] = "category LIKE '%" $search_category "%'"; } else {  $conditions[] = "category LIKE '%'"; }


    if (isset(
$_POST['search'])) {
        include(
"../inc/config.php");  
        
$db mysqli_connect(DBHOSTDBUSERDBPASSDBNAME);
       
        if (
count($conditions) > 0){ $stmt "SELECT * FROM `adopts_items` WHERE " implode(' AND '$conditions) . "ORDER BY category DESC"; }
        if (
$result mysqli_query($db,$stmt)){ 
            
$rows mysqli_fetch_object(mysqli_query($db,$stmt));
            if(
count($rows)) {


                
$table "<thead><tr><th align='center' data-sort='string'>item name <i class='fa fa-sort'></i></th><th align='center'>description</th><th align='center' data-sort='int'>price <i class='fa fa-sort'></i></th></tr></thead><tbody>";
                while (
$item $result->fetch_assoc()) {
                    
$table .= "<td style='width: 185px;'>";
                    
$table .= "<img src='../../".$item['category'].".png'> <span class='shadow'>".$item['itemname']."</span>".shop($item['shop']); 
                    
$table .= "</td><td style='width: 60%'>";
                    
$table .= $item['description'] .usage($item['function'], $item['value']); 
                    
$table .= "</td><td align='right' style='width: 48px;'>";
                    
$table .= "$".$item['price']; 
                    
$table .= "</td></tr>";
                }
                
$table .= "</tbody>";
                return 
$table;
            } else { return 
"No results found!"; }
        } else { return 
"Cannot connect to database!"; }
    }
}


function 
usage($i$v){
    switch (
$i) {
        case 
"Click1"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Feed a pet to give them {$v} EXP. </em></sub>"; break;
        case 
"Click2"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Feed a pet to set their EXP to {$v}. </em></sub>"; break;
        case 
"Click3"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Resets today's earned EXP to 0. </em></sub>"; break;
        case 
"Level1"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Raises a pet's Level by {$v}. </em></sub>"; break;
        case 
"Level2"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Sets your pet's Level to {$v}. </em></sub>"; break;
        case 
"Level3"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Makes your pet Level 0 again! </em></sub>"; break;
        case 
"Gender"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>Swaps your pet's gender to its opposite! </em></sub>"; break;    
        case 
"Attire"$usage "<br><i class='fa fa-share'></i><sub><b>use:</b> <em>You can equip this to your pet. </em></sub>"; break;         
        default; 
$usage ""; break;
    } 
    return 
$usage;
}

function 
shop($i){
    if (
$i){ 
        
$shop "<br><span style='float: left; padding-left: 20px;'><sub><b>shop:</b> <a href='../../shop/browse/{$i}' style='font-size: 14px;'>{$i}</a></sub></span>";
    } else { 
$shop "<br><span style='float: left; padding-left: 20px;'><sub><b>shop:</b> <em>n/a</em></sub></span>"; }
    return 
$shop;
}

echo 
searchItems();
?>



And here's the html:
  Spoiler: HTML 
HTML Code:

<!doctype html>

<html lang='en'>
<link href="//cdn.jsdelivr.net/fontawesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<body>

<script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/stupidtable/0.0.1/stupidtable.min.js'></script>
<script type='text/javascript'>
$(function() {

    $('.item_results').hide();
    $('#item_search').click(function() {       
        var itemname = $('#itemname').val();
        var category = $('#category').val();                       
        $.ajax({
            type: 'POST',
            url: '../ajax/search_items.php',
            data: { search : true, search_itemname : itemname, search_category : category },
            beforeSend: function(html) {
                $('#item_results').html('');
          },
          success: function(html){
                $('#item_results').show();
                $('#item_results').append(html);
          }
        });

        return false;
    });
  $('#item_results').stupidtable();
});
</script>

<div class='wrapper'>
<form>
<b>Item:</b> <input type='text' id='itemname'/> 
&nbsp;
<b>Category:</b> <select id='category'>
  <option value=''>All</option>
  <option value='food'>Food</option>
  <option value='toy'>Toys</option>
  <option value='potion'>Potions</option>
  <option value='attire'>Attire</option>
  <option value='chest'>Chests</option>
  <option value='quest'>Quest</option>
</select> 
<button id='item_search'>Search!</button>
</form>
<div class='well'><table border='1' id='item_results'></table></div>
</div>
 

</html>



You have two options, one is to link to an html file in an iframe like this:

PHP Code:

$document->add(new Comment('<iframe style="width: 100%; min-height: 1040px;" src="../../ajax/search_items.html" frameborder="0" scrolling="yes"></iframe>')); 

Alternatively, you CAN actually nix the HTML & iframe altogether. For example, in the existing searchview.php, I replaced the item search function with:

  Spoiler: REPLACEMENT ITEM SEARCH FUNCTION 
PHP Code:

    public function item(){
        
$mysidia Registry::get("mysidia");
        
$document $this->document;
        
$document->setTitle($this->lang->item);

        
$document->add(new Comment("
            <script src='https://cdnjs.cloudflare.com/ajax/libs/stupidtable/0.0.1/stupidtable.min.js'></script>
            <script type='text/javascript'>
$(function() { 
    $('#item_results').stupidtable();
    $('#item_search').click(function() {         
        var itemname = $('#itemname').val();
        var category = $('#category').val();                            
        $.ajax({ 
            type: 'POST',
            url: '../ajax/search_items.php', 
            data: { search : true, search_itemname : itemname, search_category : category },
            beforeSend: function(html) {
                $('#item_results').html('');
           },
           success: function(html){
                $('#item_results').show(); 
                $('#item_results').append(html); 
          }
        }); 
        return false;
    });
});
</script>


<form>
<b>Item:</b> <input type='text' id='itemname'/>  
&nbsp;
<b>Category:</b> <select id='category'>
  <option value=''>All</option>
  <option value='food'>Food</option>
  <option value='toy'>Toys</option>
  <option value='potion'>Potions</option>
  <option value='attire'>Attire</option>
  <option value='chest'>Chests</option>
  <option value='quest'>Quest</option>
</select>  
<button id='item_search'>Search!</button>
</form>
<legend>Results</legend>
<div class='well'><table border='1' id='item_results'></table></div>"
)); 



Which, in essence, just placed all my html into a comment, Mysidia-style.

Note that you WILL need jQuery for this to work. (See also the HTML version before the Mysidia comment version -- I linked to two other resources 'Stupid Table' which will allow you to sort tables numerically and alphabetically at a click of a column name, and 'Font Awesome' which provides fun icons.)

To see this in action, here's the HTML version working alone: http://novul.99webs.org/ajax/search_items.html

And here it is working on my search page: http://novul.99webs.org/search/item

(I also gave my items 'rarity' and included the ability to search by it, but I did not include these additions in the resources above for fear it might break something.)

Hwona 01-20-2016 03:43 AM

*hugs*
Thank you soooooo much! I was racking my brain with this!

Kyttias 01-20-2016 09:15 AM

In case there's confusion, these lines:

PHP Code:

include("../inc/config.php");  
$db mysqli_connect(DBHOSTDBUSERDBPASSDBNAME); 

Don't need to be modified. It's actually retrieving those variables from the included file above it. This means you won't have to add your database info to every single ajax page you need!

Hwona 01-20-2016 08:24 PM

Well, it certainly creates more options for features! :D
I'm excited to try this out!


All times are GMT -5. The time now is 12:31 PM.

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