1

I am new to Ajax/XMLHttpRequest and am trying to understand it.

I am working on an inventory program that basically adds tools to a box. On the main page (MainPage.php, for instance), there a textbox in a form that a user can start to type in the name of the tool in order to add it to the box. I'm playing with XMLHttpRequest right now to search for the tool in a MySQL database with the MySQL LIKE syntax. On the handler page (HandlerPage.php) there is code to search for the tool using SQL Like. The search results are displayed in a HTML DIV on the main page. It works great...

The search results are wrapped in a form and displayed as a link. The location of this wrapper function is in HandlerPage.php:

function createLink($pri_key,$button_name,$file_to_call, $other){    
        $html_str = "<form id='tool_form' action='".$file_to_call."' method='post'>";
        $html_str .= "<input style='display:none;' name='prikey' type='text' value='".$pri_key."' >";
        $html_str .= "<input style='display:none;' name='compt_prikey' type='text' value='".$other."' >";
        $html_str .= "<input  id='view_button' type='submit' value='".$button_name."' class='no_button'>";
        $html_str .= "</form>";
        return $html_str;
}

There is a JQuery event handler waiting for the user to click on the link. However, this event handler is never called. The form is submitted, but the event handler is not called. (Also, there is another form and event handler, both coded into MainPage.php that function as expected.)

$("#tool_form").submit(function(){
    //some code
    return true;
});

Where is the form submitted, or better yet, on what page is the event triggered? In HandlerPage.php or MainPage.php? I'm assuming it is being triggered on HandlerPage.php, but I don't understand why....

Also, as a side question, is there going to be a problem with multiple search results having the same id? Should I use an event handler with a class instead?

RonyLoud
  • 2,408
  • 2
  • 20
  • 25
devo96
  • 43
  • 1
  • 6
  • `Where is the form submitted` by clicking `submit` the form uses the `method` specified, in this case `post` , to the location specified in `action` - this is how forms work - you can prevent the default action of a submit button by using the event `preventDefault` method in the `submit` handler – Jaromanda X Dec 23 '16 at 09:49
  • The inputs to the form are hidden. The form's input "button" is styled in CSS to look like a normal link...you think you're clicking a link when, in fact, you are submitting a form. The problem i'm having is that when the form is submitted, it doesn't trigger the appropriate event, but it looks like that's because I'm not setting up the event properly for dynamic html code. – devo96 Dec 23 '16 at 18:49

1 Answers1

1

If I undestand correctly your explaination :

The JavaScript code in your MainPage.php make an AJAX call to HandlerPage.php that return an HTML code which is displayed on MainPage.php (right?).

In that case, the event listener should be initiate on your Mainpage.php

BUT, you must bind the listener AFTER the code is added to the DOM in order for it to work.

I often create HTML form on the fly in response of an action intercept by JavaScript, here is how I usually organize my code :

1 - the action that trigger to "dynamic" form is called 2 - a specific function generate the dynamic form -> add dynamic form to the DOM -> THEN call a dedicated function that unbind deprecated event(s) (if needed) -> THEN call a dedicated function that bind event(s) to the new created form(s))

Does it make sense?

And to answer you question regarding ids vs css: an id must be always unique, so either you use classes or unique ids

Here is an example:

$(document).ready(function() {
  $('#btn-add-item').click(function(event) {
    event.preventDefault();
    addItem();
    return false;
  });
});


    function addItem() {
      var $container = $('#items-list');
      var index = $container.children('.item').length + 1;
      // create new item from 'template'
      var newContent = $('#item-prototype').attr('data-prototype').replace(/__name__/g, index);
      // add item to DOM
        $container.append(newContent);
      // Unbind previous events to items (to reset)
      itemsUnbindActions();
      // Bind events to items (to reinitialize actions handling for all items: olds/new)
      itemsBindActions();
    }


    function itemsUnbindActions() {
      $('.item-form').unbind('submit');
    }


    function itemsBindActions() {
      $('.item-form').submit(function(event) {
        event.preventDefault();// prevent 'normal' form submission
        // call a function or do whatever you need (ajax call or something)
        exampleFunction($(this).attr('rel'));
        return false;// prevent 'normla' form submission (old broawsers)
      });
    }

    function exampleFunction(form_index) {
      var alert_message = "value1: " + $('#my-value-1-' + form_index).val()
                        + "\nvalue2:  " + $('#my-value-2-' + form_index).val();
      console.log(alert_message);
    }
/* we don't need item-prototype to be visible */
    #item-prototype {
      display: none;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="container">
      <a href="#" id="btn-add-item">add an item</a>
      <div id="items-list"></div>
     </div>

    <!-- This div is used to provide duynamic form template: __name__ will be replace by an unique value (counter) -->
    <div id="item-prototype" data-prototype='<div class="item" id="item-__name__">
     <form action="" method="POST" class="item-form" rel="__name__">
      <input type="text" name="my_value_1[__name__]" id="my-value-1-__name__">
      <input type="text" name="my_value_2[__name__]" id="my-value-2-__name__">
      <input type="submit" class="btn-item-submit" value="submit">
     </form>
    </div>'></div>
Dexter0015
  • 1,029
  • 9
  • 14
  • That makes total sense...thank you for the detailed explanation! – devo96 Dec 23 '16 at 18:51
  • Now that I know what i'm looking for, [link]http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – devo96 Dec 23 '16 at 19:03