Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Post Form Data in Json Format Via Ajax With JQuery

Tags:

jquery

ajax

as the title says I'm sending some post data via ajax. but I keep on getting errors, can anyone take a look at the code and explain why my ajax call keeps failing?

submitForm(jQuery('#priceCalc'), {name: 'thingdoto', value: "true"});

function submitForm(form, data) {
        var postData = form.serializeArray(),
            formURL = form.attr("action");

        postData.push(data);
        console.log(postData);
        jQuery.ajax({
                url : formURL,
                type: 'POST',
                dataType : "json",
                data: postData,
                success:function(data)
                {
                        jQuery('#priceTotal').html(data);
                },
                error: function()
                {
                        jQuery('#priceTotal').html('error');
                }
        });
}

EDIT: The ajax call returns the error, so it's just not succeeding. Don't know why.

like image 993
Spittal Avatar asked Dec 19 '22 21:12

Spittal


1 Answers

You're sending data as an array, not a JSON string.

You want to do something like this.

$("form#ID").submit(function(e){

    e.preventDefault();

    var data = {}
    var Form = this;

    //Gathering the Data
    //and removing undefined keys(buttons)
    $.each(this.elements, function(i, v){
            var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });

    //Form Validation goes here....

    //Save Form Data........
    $.ajax({
        cache: false,
        url : ?,
        type: "POST",
        dataType : "json",
        data : JSON.stringify(data),
        context : Form,
        success : function(callback){
            //Where $(this) => context == FORM
            console.log(JSON.parse(callback));
            $(this).html("Success!");
        },
        error : function(){
            $(this).html("Error!");
        }
    });
like image 154
Philip Avatar answered Jan 10 '23 23:01

Philip