3

I've been trying to POST data back to a controller from a lightbox using ajax but of course it doesn't work.

I have two select lists, both populated from the default controller. When I select a value and click the submit I have the error box briefly flash up the disappear again.

Using the firebug network tab I can see the POST request however under the post tab there's no data. I must be doing something wrong in the javascript itself but to me it looks ok and all my googling didn't suggest an alternative that worked.

Here's my code...

<body style="background-color: #f0f0f0;">
<div style="margin: 5px;">

<div id="ajax-login-register">

    <div id="login-box">
        <div style="text-align: center; font-weight: bold; font-size: 20px; margin: 10px 0 20px 0; border-bottom: #ccc 2px dashed; padding-bottom: 12px;"><?=lang('login')?></div>
        <form id="login-form">

        <select name="currency_sel" id="brand_country" class="form_select_200px">

            <option value="0" selected><i>Select your preferred Currancy</i></option>
                <?php foreach($currencies as $currency): ?>
                <option value="<?php echo $currency['currency_id']; ?>"><?php echo $currency['currency_name']; ?></option>
                <?php endforeach; ?>
            </select>
        </form>
  </div>

    <div id="register-box">

        <div style="text-align: center; font-weight: bold; font-size: 20px; margin: 10px 0 20px 0; border-bottom: #ccc 2px dashed; padding-bottom: 12px;"><?=lang('meta_description')?></div>
        <form id="register-form">            

            <select name="language_sel_1" id="brand_country" class="form_select_200px">                 
            <option value="0" selected>Select your preferred Language</option>
                <?php foreach($languages as $language): ?>
                <option value="<?php echo $language['language_id']; ?>"><?php echo $language['language_name']; ?></option>
                <?php endforeach; ?>
            </select>

            <select name="language_sel_2" id="brand_country" class="form_select_200px">                 
            <option value="0" selected>Select your preferred Language</option>
                <?php foreach($regions as $region): ?>
                <option value="<?php echo $region['country_id']; ?>"><?php echo $region['country_name']; ?></option>
                <?php endforeach; ?>
            </select>

            <div class="line">&nbsp;</div>
        </form>

    </div> 
        <div>
            <form>
                <button id="ajax-submit-button" style="font-size: 14px;"><?//=lang('register')?>Submit</button>
            </form>
        </div>
</div>

</div>

<script type="text/javascript">

$(document).ready(function(){

$('#ajax-login-button').button({
    icons: {
        primary: "ui-icon-check"
    }
});

$('#ajax-submit-button').click(function(){

    var error = false;

    if(error){
        return false;
    } else {
        $.ajax({
            url: "<?=site_url('locale/set_ui_lang')?>",
            type: "POST",
            dataType: "json",              
            data: ({
                'currency_sel'      : $('#currency_sel :selected').val(),
                'language_sel_1'        : $('#language_sel_1 :selected').val(),
                'language_sel_2'        : $('#language_sel_2 :selected').val()
            }),
            success: function(data){
                    parent.$.colorbox.close();
                    parent.location.reload();
                },
            error: function(xhr, ajaxOptions, thrownError){
                 alert("ERROR! \n\n readyState: " + xhr.readyState + "\n status: " + xhr.status + "\n thrownError: " + thrownError + "\n ajaxOptions: " + ajaxOptions);
                }            
            });                
        }
    });
});
</script>

</body>

When the error notice flags up the ready state and status both come up 0, thrownerror is just error.

Also the receiving controller is currently only just a print_r(&_POST) to test.

I don't seem to be able to get past this myself, if anyone can help it is much appreciated.

Thanks

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Peter Donoghue
  • 161
  • 2
  • 10
  • Have you tried dumping the entire object passed to the ajax() call to spot any errors? (See ["How can I print a JavaScript object?"](http://stackoverflow.com/questions/957537/how-can-i-print-a-javascript-object)) – Tomas Creemers Aug 08 '13 at 00:43
  • Thanks for that Tomas, I tried using it in the error catch with no results, can you advise me on where I should use it? – Peter Donoghue Aug 08 '13 at 01:24
  • Replace your $.ajax() call with: tempObj = { url: "=site_url('locale/set_ui_lang')?>", type: "POST", // and the rest of the settings object... } Console.Log(tempObj); – Tomas Creemers Aug 08 '13 at 01:31
  • Ok, console gives me the object info in firebug. when I click on this it jumps to the DOM tab and tells me "There are no properties to show for this object". Does this point to issues capturing the select values? Again thanks for your help Tomas! – Peter Donoghue Aug 08 '13 at 02:25

5 Answers5

1

The keys of your data object should not be in quotes.

It should work (provided the jQuery calls for the values work) when you change it to:

data: {
    currency_sel: $('#currency_sel :selected').val(),
    language_sel_1: $('#language_sel_1 :selected').val(),
    language_sel_2: $('#language_sel_2 :selected').val()
},

Source: jQuery.ajax() documentation

Tomas Creemers
  • 2,645
  • 14
  • 15
  • http://stackoverflow.com/questions/4348478/what-is-the-difference-between-object-keys-with-quotes-and-without-quotes – Ben Aug 08 '13 at 00:15
  • I've done this both ways with the same result. As the apps gone from dev to dev over time some of the ajax stuff has them some don't. Even following their lead I still cant get this running right. Thanks for suggestions. – Peter Donoghue Aug 08 '13 at 00:35
1

Is it just me or are you making the click event return false instead of firing off AJAX?

var error = false;

    if(error){
        return false;
    }
Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
  • I had error checking code in there which I cut out for posting up here, error is always false unless its true..which then returns false. I still facepalmed when I read this though but the problem persists. – Peter Donoghue Aug 08 '13 at 00:22
  • @ben-racicot equivalent to `if (false) { return false; }`. That never gets called. (not sure why it's there) – Ben Aug 08 '13 at 03:43
1

You can't multiple IDs with the same name and you selectors are wrong.

$('#currency_sel :selected').val() should be $('select[name="currency_sel"] option:selected').val() and same for the others.

EDIT

Remove parenthesis of data, it should be

data: {
                currency_sel : $('select[name="currency_sel"] option:selected').val(),
                language_sel_1 : $('select[name="language_sel_1"] option:selected').val(),
                language_sel_2 : $('select[name="language_sel_2"] option:selected').val()
            },
L105
  • 5,379
  • 3
  • 18
  • 23
  • Amended, id's now match the names for each select. $('select[name=""] doesn't make a difference though. Thanks for chipping in – Peter Donoghue Aug 08 '13 at 02:29
  • You added option:select too? – L105 Aug 08 '13 at 02:46
  • Progress, This in combination with Ben's suggestion has moved this issue on a bit. I still get the json parser error but the parameters now show in the debuger and the controller will execute the print_r($_POST); I'll answer this question to acknowledge both answers. Many thanks! – Peter Donoghue Aug 08 '13 at 13:11
1

Your ajax call is in a click handler for a button inside a separate form.

Here's what's happening..

When you click the button, you trigger an ajax call.

The click handler then returns normally and the form that contains the button is submitted.

When that happens a new page loads, and the browser cancels any pending ajax request, which triggers your error. (after you click ok in the error alert, you should notice a normal page load)

To prevent that you can either return false; after your ajax call, or call preventDefault() on the event object:

$('#ajax-submit-button').click(function(e){

    e.preventDefault();

    /* Rest of the code */

});

This should fix your problem.

*Edit: * note the e parameter on the function definition

Ben
  • 20,737
  • 12
  • 71
  • 115
  • This has made a difference now giving this error readyState: 4, status: 200, thrownError: SyntaxError: JSON.parse: unexpected character, ajaxOptions: parsererror wheras before this error was just flashing up unpopulated. Thanks for giving me this Ben – Peter Donoghue Aug 08 '13 at 12:45
  • @PeterDonoghue That means the connection is working, but there's now a problem with the JSON data you post back to your ajax request.. check how your output is generated. If you can't work it out, post another question with the relevant output... – Ben Aug 08 '13 at 23:07
0

Fixed this in combination of Ben & L105. For anyone else with a similar problem here's the working code. div names etc are a bit sketchy, this is still a prototype build...

<body style="background-color: #f0f0f0;">
<div style="margin: 5px;">

<div id="ajax-login-register">

    <div id="login-box">
        <div style="text-align: center; font-weight: bold; font-size: 20px; margin: 10px 0 20px 0; border-bottom: #ccc 2px dashed; padding-bottom: 12px;"><?=lang('login')?></div>
        <form id="login-form">

        <select name="currency_sel" id="currency_sel" class="form_select_200px">

            <option value="0" selected><i>Select your preferred Currancy</i></option>
                <?php foreach($currencies as $currency): ?>
                <option value="<?php echo $currency['currency_id']; ?>"><?php echo $currency['currency_name']; ?></option>
                <?php endforeach; ?>
            </select>
        </form>
  </div>

    <div id="register-box">

        <div style="text-align: center; font-weight: bold; font-size: 20px; margin: 10px 0 20px 0; border-bottom: #ccc 2px dashed; padding-bottom: 12px;"><?=lang('meta_description')?></div>
        <form id="register-form">            

            <select name="language_sel_1" id="language_sel_1" class="form_select_200px">                    
            <option value="0" selected>Select your preferred Language</option>
                <?php foreach($languages as $language): ?>
                <option value="<?php echo $language['language_id']; ?>"><?php echo $language['language_name']; ?></option>
                <?php endforeach; ?>
            </select>


            <div class="line">&nbsp;</div>
        </form>

    </div> 
        <div>
            <form>
                <button id="ajax-submit-button" style="font-size: 14px;"><?//=lang('register')?>Submit</button>
            </form>
        </div>
</div>

</div>

<script type="text/javascript">
$(document).ready(function(){
    $('#ajax-login-button').button({
        icons: {
            primary: "ui-icon-check"
        }
    });

    $('#ajax-submit-button').click(function(e){
        e.preventDefault();
        $.ajax({
                url: "<?=site_url('locale/set_ui_lang')?>",
                type: "POST",
                dataType: "json",              
                data: {
                    currency_sel:$('select[name="currency_sel"] option:selected').val(),
                    language_sel_1:$('select[name="language_sel_1"] option:selected').val()
                },
                success: function(data){
                        parent.$.colorbox.close();
                        parent.location.reload();
                    },
                error: function(xhr, ajaxOptions, thrownError){
                     alert("ERROR! \n\n readyState: " + xhr.readyState + "\n status: " + xhr.status + "\n thrownError: " + thrownError + "\n ajaxOptions: " + ajaxOptions);
                        }            
                });                
        });
    });

Peter Donoghue
  • 161
  • 2
  • 10