Home > Net >  problems with parsing arguments jquery: $getJSON --> php:$_GET
problems with parsing arguments jquery: $getJSON --> php:$_GET

Time:01-13

I want to invoke a php program from javascript and send relevant info by $.getJSON from the js side to be processed to the php module through $_GET.

Thankful for any helpful suggestions

Cheers, Nisse

I start out with functioning legacy code looking like:

onestr='?q=valuezero';
$.getJSON(onestr ,function() {
    console.log("Be here now:");
}
)

On the server side, I get _GET:

{"view":"app","q":"valuezero"} 

which is what I want.

I then want to augment onestr with the content of two objects:

clientside (js):

my_obj1={property1:"value1",property2:"value2",propery3:"value3"};
my_obj2={property4: "value4", property5: "value5", propery6: "value6"};
scr_str1=JSON.stringify(my_obj1).substr(1).slice(0,-1);
scr_str2=JSON.stringify(my_obj2).substr(1).slice(0,-1);
//the substr and slice breaks everything down to one level
//
onestr='?q=valuezero' '&' scr_str1 '&' scr_str2;
$.getJSON(onestr ,function() {
    console.log("Be here now");
}
)

On the server side, I now get :

 _GET:  {"view":"app","q":"valuezero","\"property1\":\"value1\",\"property2\":\"value2\",\"propery3\":\"value3\"":"","\"property4\":\"value4\",\"property5\":\"value5\",\"propery6\":\"value6\"":""}

whereas the desired result would have been:

{"view":"app","q":"valuezero","property1":"value1","property2":"value2","propery3":"value3","property4":"value4","property5":"value5","propery6":"value6"}

It initially looked trivial to append something like .replace(/\\/g,'').replace(/'""'/g,'"'); to the def of scr_str1 and scr_str2 but then I realized that the backstrokes appear on the server side; also tried replacer function in stringify and other stuff but I just cant transfer _GET to an associative array of the desired structure.

CodePudding user response:

If you need to compose an url having as GET parameters the property values coming from an object, this could be the strategy to get there:

Warning! I'm not escaping the property names/values that may need to pass through encodeURIComponent

my_obj1 = {property1:"value1",property2:"value2",propery3:"value3"};
my_obj2 = {property4: "value4", property5: "value5", propery6: "value6"};

const params = {...my_obj1, ...my_obj2};
let url = buildUrl("https://host.com/path/to/action", params);
console.log(url);

function buildUrl(baseurl, params){
  const queryParams = Object.entries(params)
    .map(([key, value]) => `${key}=${value}`)
    .join('&');
  return `${baseurl}?${queryParams}`;
}

  • Related