2

this does work fine as long the homepage var has no // in it

$.getJSON(url + "/addPerson/'" + name + "'/'" + homepage +"'", function(data){console.log(data);} );

how would I correctly prepare an url var to pass it as JSON call ?

user3732793
  • 1,699
  • 4
  • 24
  • 53

2 Answers2

2

If homepage is an URL with http:// in it you need encode it.

You should write :

$.getJSON(url + "/addPerson/" + name + "/" + encodeURIComponent(homepage), function(data){console.log(data);} );

If that is the case, you should not pass urls in urls. Use the POST payload or multiform data.

Also, if the aim of the request is to add a record in your database, use POST instead of GET.

$.post(url+'/addPerson', {name: name, homepage: homepage}, function(data){console.log(data);});
Charleshaa
  • 2,218
  • 2
  • 21
  • 25
  • 1
    You need to use `encodeURIComponent`, encodeURI don't encode slashes `encodeURI('http://example.com')` return `http://example.com` – jcubic May 24 '16 at 12:46
  • excellent thanks. that did work. thanks to you all ! – user3732793 May 24 '16 at 12:50
  • actually only getJSON did work for me – user3732793 May 24 '16 at 12:53
  • @user3732793 well you need to make the appropriate changes to your API for the POST request to work properly which I strongly recommend. GET requests are for GETTING data. POST requests are for POSTING data. – Charleshaa May 24 '16 at 12:57
  • yeah makes sense, I have changed tha api to accept post requests. However your second code example didn't work with it so used the uri compose from the getJSON example... – user3732793 May 24 '16 at 13:12
0

Use encodeURI to encode the uri and get the correct value to the api, when trying to access a api over http

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
  • can you kindly post an example ? – user3732793 May 24 '16 at 12:38
  • 1
    `$.getJSON(encodeURI(url + "/addPerson/'" + name + "'/'" + homepage +"'"), function(data){console.log(data);} ); ` – wilovent May 24 '16 at 12:39
  • @user3732793 Only name and homepage should be encoded use `$.getJSON(url + "/addPerson/" + encodeURIComponent(name) + "/" + encodeURIComponent(homepage)), ...` – jcubic May 24 '16 at 12:44
  • thanks but that does not reach the api behind Person anymore. Which is currently reduced to "../addPersonen/{param1}/{param2}" as url – user3732793 May 24 '16 at 12:47