6

I am trying to call jQuery function when button is clicked. But I am getting the error as follows:

Uncaught ReferenceError: update_question_ajax is not defined

HTML:

<button type="button" class="update-question-<?php echo $i; ?> button" onclick="update_question_ajax(<?php echo $i; ?>)" style="outline: 0 none;"><?php _e('Update') ?></button>

jQuery:

$(function(){
    function update_question_ajax(id)
    {
        var test = $('.edit-question-' + id + ' input[name="translated"]');
        var editedQuestionId = $('#question-id-'+id).val();
        var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
        var modalObj = $('#myQuestionModal');

        $.ajax({
            type: "POST",
            url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
            data:{
                edited_question: editedQuestionObj,
                question: editedQuestionId
            },
            success: function(){
                modalObj.dialog('close');
                modalObj.html('');
            },
            complete: function(){
                //window.location.reload(true);
            }
        });
        return false;
    }
});

I appreciate if you guys help me out about this.

Thank you!

curiozity
  • 108
  • 1
  • 1
  • 7

2 Answers2

11

Seems to be a scope issue. You've defined the function essentially inside another function. You should also try to avoid placing php inside javascript. Technically it works, but isn't really good form.

Removed the inline click handler.

<button type="button" class="update-question button" data-id="<?php echo $i; ?>" style="outline: 0 none;"><?php _e('Update') ?></button>

Then we create a self executing function, pass jQuery in as $ which gives everything inside the ability to use "$" as jQuery. Then define your click handler for the button and use a data attribute to pass the id rather than using PHP mixed in your JS and placing it in the DOM. Just feels a little cleaner. Also, make sure you are loading jquery / other scripts at the bottom of your document, just before the close body. This way you don't need a .ready because your document will already be loaded.

(function($){
    // Define click handler. 
    $('button.update-question').on('click', function(e){
        e.preventDefault();
        var id = $(this).data('id');

        update_question_ajax(id);
    });

    function update_question_ajax(id) {
        var test = $('.edit-question-' + id + ' input[name="translated"]'),
            editedQuestionId = $('#question-id-'+id).val(),
            editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val(),
            modalObj = $('#myQuestionModal');

        $.ajax({
            type: "POST",
            url: "YOURURL",
            data:{
                edited_question: editedQuestionObj,
                question: editedQuestionId
            },
            success: function(){
                modalObj.dialog('close');
                modalObj.html('');
            },
            complete: function(){
                //window.location.reload(true);
            }
        });
    }

}(jQuery));
BenMorel
  • 34,448
  • 50
  • 182
  • 322
xCNPx
  • 605
  • 4
  • 7
  • Such a great explanation! I will accept this as an answer. But I have an issue. Click handler(button.update-question) does not fire the event. – curiozity Mar 29 '14 at 22:55
  • Do you have your JS code loading in the of the document or at the end near the close of the body ? If its in the head, the function is firing before the DOM is loaded, so the element isn't being bound properly to the event handler. Try moving your reference to JQ just above the closing body tag, then put another – xCNPx Mar 29 '14 at 23:02
  • I use MVC pattern and the script is at the end of the view I've been workin on. – curiozity Mar 29 '14 at 23:05
  • Place an "alert(id);" just after "function update_question_ajax(id) {" line. That will let you know if you are at least getting in to that function on click. If not, check the console/firebug for errors, make sure you have jQuery defined above where you are calling this code. ps- make sure to update your ajax url back to what you had before, i just changed it for reference. – xCNPx Mar 29 '14 at 23:23
  • I made console.log() where you indicated it does not get into that function. Interestingly it has no errors on firebug. Yeah I changed my ULR. Locked up! :) – curiozity Mar 29 '14 at 23:28
  • does the click event fire? try adding a console log to that event as well, and double checking your file inclusions. Try using chrome for debugging. Maybe add an alert before the event is bound to see if the self executing function is ever running. working example : http://jsfiddle.net/6hc9b/2/ – xCNPx Mar 29 '14 at 23:51
9

You should move the function definition outside of the document.ready callback ($(function() { ... }):

function update_question_ajax(id) {
    var test = $('.edit-question-' + id + ' input[name="translated"]');
    var editedQuestionId = $('#question-id-'+id).val();
    var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
    var modalObj = $('#myQuestionModal');

    $.ajax({
        type: "POST",
        url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
        data:{
            edited_question: editedQuestionObj,
            question: editedQuestionId
        },
        success: function(){
            modalObj.dialog('close');
            modalObj.html('');
        },
        complete: function(){
            //window.location.reload(true);
        }
    });
    return false;
}

Everything you put inside the $(function() {} is executed when the DOM is ready but is private to its scope.

If on the other hand you want to use unobtrusive javascript, then get rid of this onclick attribute from your markup:

<button type="button" class="button update-question-<?php echo $i; ?>" dtaa-id="<?php echo $i; ?>" style="outline: 0 none;"><?php _e('Update') ?></button>

and then use the document ready callback to unobtrusively subscribe to the .click event of those buttons:

$(function() {
    function update_question_ajax(id) {
        var test = $('.edit-question-' + id + ' input[name="translated"]');
        var editedQuestionId = $('#question-id-'+id).val();
        var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
        var modalObj = $('#myQuestionModal');

        $.ajax({
            type: "POST",
            url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
            data:{
                edited_question: editedQuestionObj,
                question: editedQuestionId
            },
            success: function(){
                modalObj.dialog('close');
                modalObj.html('');
            },
            complete: function(){
                //window.location.reload(true);
            }
        });
        return false;
    }


    $('.button').click(function() { 
        var id = $(this).data('id');
        return update_question_ajax(id);
    });
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Actually that works. But in this case, input.val(); returns undefined or empty string. So I was searching about that and I found something says: "move function definition inside the document.ready." I am really confused so bad! – curiozity Mar 29 '14 at 22:14
  • The reason why you are getting undefined is because you are using an id selector: `$('#question-id-'+id)` but your button doesn't even has an `id` attribute. Make sure that there's a corresponding element in your DOM with this id. – Darin Dimitrov Mar 29 '14 at 22:16
  • Darin Last Question: I use following selector for getting input's value: var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val(); I attempt to trigger this event button onclick. What's the connection between id attribute of my button and the selector? – curiozity Mar 29 '14 at 22:25