4

I apologize if the title is a little unclear. Basically, here is the problem: I have a voting poll form that is generated in a file called poll.php. So if I go to /poll.php, it shows me that poll. I am not including the form code since it doesn't have anything that can possibly lead to this problem, as all it has is radio buttons, text and a submit button. I have configured the form to work with ajax, so when I click submit, it submits the form, queries the database for latest data and displays it in a graph form to the user without refreshing the page.

Here is the javascript code that runs to enable ajax:

$('body').on('submit', '#votePoll', function() {
    $.get("/vote.php", $(this).serialize(), function(data) {
        $("#content").html(data);
    });
    return false;
});

As the code shows, the id of the form is set to "votePoll." As I said earlier, if I simply go to poll.php, select a radio button and hit submit, it will execute the code above and work fine. The problem comes when a second ajax stage is inserted.

The main file that display the webpage in is called index.php.

In index.php, I run the following the javascript code to fetch the form created in poll.php and display it:

$(function() {
    var pollContainer = document.getElementById('pollContainer');

    $.ajax({
        url:"/poll.php",
        type:"POST",
        success:function(msg){
            pollContainer.innerHTML = msg;
        }
    });
})

As you can see, the form is fetched via ajax too. Note: There is a DIV container that exists in index.php in which the form is loaded, as mentioned in the javascript code above. It's named "pollContainer."

Next, when the code executes, the form (which can be seen in poll.php) is shown in the div container inside index.php instead.

Now, the goal is to make it work the same way it worked when I went straight to poll.php, but instead have the ajax work inside the container and update the div content the way it would have done in poll.php.

However, the problem is that whenever I click "submit," not only does the page just refresh and do nothing else, but it also fails to account for the vote and run "vote.php."

Here is part of the poll.php file that generates the form (which is displayed in the div container in index.php):

print "<div id='content'>
    <form method='post' id='votePoll'>
        <span><b>
            {$qTitle}
        </b></span><br>
        <div class='radio'>
            <label>
                <input type='radio' name='option' id='optionsRadios1' value='1'>
                    {$q1}
            </label>
        </div>
        <div class='radio'>
            <label>
                <input type='radio' name='option' id='optionsRadios1' value='2'>
                    {$q2}
            </label>
        </div>
        <div class='radio'>
            <label>
                <input type='radio' name='option' id='optionsRadios1' value='3'>
                    {$q3}
            </label>
        </div>
        <input type='submit' class='btn btn-default'>
    </form>
</div>";

The rest of the code in that file and variables q1 etc. are not included in this code, but their job is to retrieve information from database and display it.

What has left me confused is why the code works perfect when going directly to poll.php and voting but doesn't work when doing it in the form that is presented in index.php.

Please let me know if I made some mistake or forgot to add something.

UPDATE: Both the JS code blocks posted above are in separate files that are referenced to inside the index.php page.

DemCodeLines
  • 1,760
  • 5
  • 38
  • 58
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Barmar Oct 10 '13 at 22:17

1 Answers1

1

I guess the problem is the $(function() {...}); call, which is essentially a shortcut for $(document).ready(function() {...});. When you change the DOM using your Ajax call, the document ready event not fired, so your event handlers won't bind.

Using Event Delegation, you could try $('body').on('submit', '#votePoll', function() {...}); in your index.php instead of your event handler in poll.php. This should bind your event handler to all current and future #votePoll elements inside the body.

TheWolf
  • 1,365
  • 7
  • 15
  • I tried changing it to that, but it didn't make any difference. – DemCodeLines Oct 10 '13 at 22:40
  • Also I tried putting `console.log("HELLO");` inside the `$("#votePoll").submit...` block of code and it didn't print out hello in the log, so yes. The code apparently never reaches that stage. However, the there is no error in the console either. – DemCodeLines Oct 10 '13 at 22:47
  • No, you have "double event handler". In your event handler for the onsubmit event, you're binding an event handler to the onsubmit event. Delete that second handler and put the Ajax call inside the event handler bound here: `$('body').on('submit', '#votePoll', function() {...});` EDIT: Then, update your code again, please. – TheWolf Oct 10 '13 at 22:51
  • So here is the situation now. I put `console.log("HELLO");` inside the `$('body').on('submit')...` block and it printed "HELLO" in the console. – DemCodeLines Oct 10 '13 at 22:56
  • However, it isn't submitting the form and showing the results page. Something is still wrong. – DemCodeLines Oct 10 '13 at 22:56
  • Could it be the `return false` line? – DemCodeLines Oct 10 '13 at 22:58
  • Do you see an Ajax request in your Firebug console when submitting the form? – TheWolf Oct 10 '13 at 22:58
  • I'm using Chrome. I am not sure what the equivalent of the ajax request in Firebug console is in the Chrome console. The console log shows a blank white screen. – DemCodeLines Oct 10 '13 at 23:01
  • You should be able to see new requests (such as Ajax calls) in the Network tab in Chrome's developer console. Check if you can see your first (working) request there and if so, if you can see the second. – TheWolf Oct 10 '13 at 23:03
  • Well it reaches the vote.php file (which it wasn't reaching before) since I set a cookie in that file and the cookie is being set when I hit submit button. Also, on the next refresh button, the container div on the main page shows the results page instead of form (since you already voted). – DemCodeLines Oct 10 '13 at 23:07
  • It just isn't showing that through ajax without having to refresh the entire page. – DemCodeLines Oct 10 '13 at 23:08
  • Great! Could you elaborate a bit on what was the problem so that others can benefit from your experiences? – TheWolf Oct 11 '13 at 07:34