1

I'm trying to make an Ajax query with an array in the parameters. Here's an example :

var info = [ter,ter,ter];

$('body').on('click','#upload', function(){
    $.ajax({
        url:'/app_dev.php/uploader_photos',
        data:{
            links : info,
        },
        dataType : 'json',
        beforeSend : function(){
            $('#upload_photo').empty();
            $('#upload_photo').append('<i class="fa fa-refresh fa-spin"></i> Loading');
        },
        success : function(data){
            $('#upload_photo').empty();
            $('#upload_photo').append('<i class="fa fa-thumbs-o-up"></i> OK');
        }
    });
});

The issue is my url is encoded this way :

/upload?links%5B%5D=ter&lioks%5B%5D=ter&lioks%5B%5D=ter

What i need to know how to encode it this way :

/upload?links=[ter,ter,ter]

Thanks for the help !

1
  • be sure to accept one of the answers as well as optionally voting. thank you. Commented Dec 29, 2015 at 8:56

3 Answers 3

2

Stringify your array to json:

info = JSON.stringify(info);

in your php:

$info = json_decode($_POST['links']);

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

Comments

2

That shouldn't be a problem actually. As you have not set the Content-Type so by default jQuery uses formurlencoded query string so it encodes the values that way and it sends it as a form data instead of Request Payload.

You can get it like:

if(isset($_GET['links'])){
  echo $_GET['links'];
}

From the docs:

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: Boolean or String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

Comments

1

This will convert a native JavaScript object to a JSON string:

JSON.stringify(yourString);

so, in your code:

links : JSON.stringify(info),

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.