daveomcd
daveomcd

Reputation: 6565

How can I perform a jQuery post with a string of data?

So I'm wanting to create a "POST" to another page. I want to do it like the following...

$.ajax({

    type: "POST",
    url: "maintain.aspx",
    data: { key1:value1, key2:value2, key3:value3 },
    success: function(msg){
        alert("Done!");
    }

});

The problem is I don't have data in the form of variables. Instead I'm supplied with the data in a string formatted like so...

&myvar=1&thisguy=dave&thatguy=martin

How can I get the key/value information from that string into the data: {} section of the ajax call? Thanks!

Upvotes: 0

Views: 104

Answers (3)

toto
toto

Reputation: 1188

Sorry for the confusion. Here's an example:

var url = "?param1=123&param2=222&param3=aaaa";
var json = {param1: " + getQueryString(url, param1)  + ", param2: " + getQueryString(url, param2)  + "}

function getQueryString(url, param){
        var currentURL ="";
        currentURL = url;
        var separar = currentURL.split("&");
        var value = "";
        for (i = 0; i < separar.length; i++) {
            var separarValue = separar[i].split("=");
            if (separarValue[0] == a) {

                value = separarValue[1];
                break;
            }
        }
        return value;
    }

Upvotes: -1

Sushanth --
Sushanth --

Reputation: 55750

Try this

var str = "&myvar=1&thisguy=dave&thatguy=martin";

var params = str.split('&');

var objData = {};
for (var i = 0; i < params.length; i++) {
  if (params[i] !== '') {
    var attrs = params[i].split('=');
    if (attrs.length) {
      objData[attrs[0]] = attrs[1];
    }
  }
}

$.ajax({
  type: "POST",
  url: "maintain.aspx",
  data: objData,
  success: function (msg) {
    alert("Done!");
  }

});
console.log(objData)

Check Fiddle

Upvotes: 0

James Montagne
James Montagne

Reputation: 78690

The data property can be either an object as you have it, or a query string. So you can simply use it as-is. (though you may need to strip the leading &).

$.ajax({
    type: "POST",
    url: "maintain.aspx",
    data: "myvar=1&thisguy=dave&thatguy=martin",
    success: function(msg){
        alert("Done!");
    }
});

Upvotes: 4

Related Questions