2

I'm trying to post an array through ajax to php file on form submit.

<form action="echo.php" method="post">
<input name="qwerty[]" type="text">
<input name="qwerty[]" type="text">
<input type="submit"/>
</form>

Basically, I use this to post to php file:

function getlist(alt) {
    $.ajax({
    type:'POST',
    url: 'markattlist.php',
    data:{today:alt},
    success: function(data){
    $('#helloflist').html(data);
    },
    error:function (){}
    });
}

Above is an example of what I'm trying to do. I've searched, but unable to find the solution to that. How can I post an array through ajax.

2
  • And what is your question? Commented Aug 6, 2016 at 14:01
  • How can I post an array through ajax in the same way? Commented Aug 6, 2016 at 14:03

3 Answers 3

2

You can serialize the form data using data:$('#form').serialize() function and can send it using ajax or you can use JSON data type to send an array.

var Data = $('#yorFormName').serializeArray();
var JSONData = JSON.stringify(convertToJSON(Data));

 $.ajax({
        url: your_url,
        type: "POST",
        dataType: "json",
        data: JSONData,
        contentType: "application/json; charset=utf-8",
        success: function (response) {

            if (response.status == 'success') {
            // success logic
           } 
        },
        error: function () {
            var errMsg = "Unexpected Server Error! Please Try again later";


        }

    });

Hope this will help you.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of bothering how to send what you need, I advise you to use jquery serialize() method:

function getlist(alt) {
    $.ajax({
    type:'POST',
    url: 'markattlist.php',
    data: $("form").serialize(),
    success: function(data){
        $('#helloflist').html(data);
    },
    error:function (){}
    });
}

And check on server-side with

print_r($_POST);

7 Comments

This looks good, but i've to insert it into mysql. How can I then distinguish posted data on server ?
distinguish from what?
I'm posting multiple <input name="qwerty[]" type="text"> and multiple <input name="hello[]" type="text">
How will I know which one is qwerty[] and hello[] ?
I got what I needed.
|
0
data: JSON.stringify({d:c}),

Encode it as json and decode it on the server:

$data=json_decode($_POST["data"]);

4 Comments

I don't understand. What is d:c ?
{} is just an object. You could also put [] an array inside the stringify function
See afshans answer for a better example with jquery and ajax
u_mulder had a better approach.

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.