Sparatan117
Sparatan117

Reputation: 138

jQuery Ajax passing array with pre-defined vars

I've set up a function to collect a form's contents and submit it to a Php page and then have the php page process it and return a success message. Only problem is that when I'm sending this via POST (or get for that matter) nothing is actually getting to the PHP page... at all.

function add_new_customer(){
    $('.new-customer-con .submit-new-customer').click(function(){
        search_path = $('.search-rel-path').val()+'insert/insert_new_customer';
        var textinput = [];
        $('.new-customer-con input:text').each(function(e){
            if($(this).length > 0){
                textinput[$(this).attr('name')] = $(this).val(); 
            }
        });
        $('.new-customer-con textarea').each(function(e){
            if($(this).length > 0){
                textinput[$(this).attr('name')] = $(this).val(); 
            }
        });
        var call_back_btn = $('.new-customer-con button[name=call_back]');
        if(call_back_btn.text().toLowerCase() === 'no'){var call_back = 'false'; } else{var call_back = 'true'; }
        textinput[call_back_btn.attr('name')] = call_back;
        var shipping_method = $('.new-customer-con select');
        textinput[shipping_method.attr('name')] = shipping_method.children('option:selected').val();
        $.ajax({
                    url: search_path,
                    type: 'POST',
                    dataType: 'html', // in html mode for debugging

                    data: { data: textinput }
                })
                .done(function(data) {
                    console.log(data);
                    if(data['success']){
                        $('html, body').animate({scrollTop: $('.new-customer-con').offset().top }, 500);
                        $('.new-customer-con .alert-message').addClass('alert-success').hide().fadeIn('slow').text("Successfully inserted "+textinput['customer_name']);
                        var timeout = setTimeout(function(){$('.new-customer-con .alert-message').fadeOut('fast').text('').removeClass('alert-success');},2000);
                    }   
                })
                .fail(function() {
                    console.log("error");
                })
                .always(function() {

                });

    });
}

Not sure what I'm doing wrong, but is there a better way to send the array or do I have to format it differently? Sorry I generally know what I'm doing with PHP but arrays in javascript kinda make my head hurt.

Upvotes: 0

Views: 187

Answers (2)

Sim0n222
Sim0n222

Reputation: 104

Try this data: textinput instead of data: { data: textinput }

Upvotes: 2

unloco
unloco

Reputation: 7320

Declare textinput as object instead of an array
var textinput = {};
then use data: textinput instead of data: { data: textinput }

Upvotes: 0

Related Questions