Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax post request string data instead of object

Similar to this question I need to send a string as data in a post request.

Unlike that one, I can't use an object because I have repeated items. As you can see in my sample data sn1, sn2 and sn3 are repeated several times on different datetimes.

Sample data:

&sn3=2013-2-4T12:43:52&sn3=2013-2-4T12:43:55&sn1=2013-2-4T12:43:59&sn1=2013-2-4T12:44:0&sn2=2013-2-4T12:44:0&sn3=2013-2-4T12:44:2&sn2=2013-2-4T12:44:3&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn2=2013-2-4T12:44:19&sn3=2013-2-4T12:44:21&sn2=2013-2-4T12:44:22&sn2=2013-2-4T12:46:39&sn3=2013-2-4T12:46:42&sn2=2013-2-4T12:46:44&sn2=2013-2-4T12:46:45&sn2=2013-2-4T12:46:46&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:49:44&sn2=2013-2-4T12:50:21&sn2=2013-2-4T12:52:21&sn2=2013-2-4T12:52:24&sn2=2013-2-4T12:57:35&sn3=2013-2-4T12:57:38&sn3=2013-2-4T12:57:39&sn2=2013-2-4T12:57:39&sn2=2013-2-4T12:57:40&sn3=2013-2-4T12:57:46&sn3=2013-2-4T13:21:30

I tried using the following

console.log(screens); //logs my sample data posted above.
        $.ajax({
            url : url,
            type: "POST",
            dataType : 'text',
            data : screens,
            success : function(data) {
                console.log("sucessfull sending:")
                console.log(data);
            },
            error : function() {
                console.log('failed');
            }

        });

But it always triggers failed.

Can I send it as a string? If not, how can I send multiple items with the same key?

like image 430
caiocpricci2 Avatar asked Dec 30 '25 10:12

caiocpricci2


2 Answers

    console.log(screens); //logs my sample data posted above.
    $.ajax({
        url : url,
        type: "POST",
        dataType : 'text',
        data : {screens:screens},
        success : function(data) {
            console.log("sucessfull sending:")
            console.log(data);
        },
        error : function() {
            console.log('failed');
        }

    });

See data : {screens:screens},, if you do something like that, on server you will be able to get it like: screensString = Request["screens"]. After that, screensString will contain a single string with all screens.

like image 142
Viktor S. Avatar answered Jan 02 '26 00:01

Viktor S.


When you don't specify contentType in the ajax options, your request will default to 'application/x-www-form-urlencoded; charset=UTF-8'. However, when your post data is just text, you should make the server aware of that fact by specifying a contentType 'text'. As opposed to the contentType, the dataType specifies the type of response data that you expect back from the server.

like image 25
marty Avatar answered Jan 01 '26 23:01

marty