0

I have a form input generated with PHP like given below:

<input type="text" name="category[type]">
<input type="text" name="category[name]">

In PHP, it's ok. But I need to send it with javascript by Ajax. I use jQuery and tried with function $.serializeArray() in data.

'form': $(this).closest('form').serializeArray(),

But the result what I got is:

array (7)
  0 => array (2)
    name => "category[type]" (11)
    value => "my_type"

JSFIDDLE

Best result what I need is:

array
  category => array
    type => my_type

or anything similar what I can work with.

Any idea?

Thank in advance for your help

3
  • Post your JavaScript. I have a feeling that you are placing serializeArray() line in the wrong place. It should look more like 'data': $(this).closest('form').serializeArray() Commented Jun 7, 2016 at 3:02
  • If you structure your inputs into a <form>, you could also just use $("form").submit() and it will handle all the data passing for you. Commented Jun 7, 2016 at 3:03
  • @cyberbit I added jsfiddle demo Commented Jun 7, 2016 at 3:10

2 Answers 2

2

Use .on method to attach the submit event handler to your form. This will trigger when you click on a submit button within your form.

You want to pass $(this).serializeArray() directly into data setting.

$('form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'script.php'
        data: $(this).serializeArray(), 
        success: function (res) {
            // handle the response you get back from the PHP
        }
    })
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I found out where is a problem. Your solution work correctly but i need to add custom variables which are not part of form.
0

It seems to be better approach get data with serializeArrayand modify them before sending.

Custom data must represent the same object as form object which is returned serializeArray.

.

var formData = $(this).closest('form').serializeArray();
    formData.push({ name: 'customParam', value: 'my_val'});

JSFIDDLE

Notice: If you put serializeArray directly to the ajax data. It will work correctly.

It might help someone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.