4

I want to submit a POST request while passing a url among other parameters. I have the following script but it is not working.

var params = "param1="+param1_value+"&url="+url_value;

var xhr = new XMLHttpRequest();
xhr.open("POST", action_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
  if(xhr.readyState == 4 && xhr.status == 200){
    console.log("Done");
  }
}
xhr.send(params);

Assuming that the url_value is something like this:

https://www.domain.com/blah?param=&email=domain%40email%2Ecom&blah=1234

what would be wrong with this script?

3 Answers3

2

Take a look at this question/answer - Should I URL-encode POST data?

Your sample value for url_value is using the HTML Entity Code. Because of the & symbol in the value, it is being sent as multiple values. You probably need to URL encode it so it looks like this

https%3A%2F%2Fwww.domain.com%2Fblah%3Fparam%3D%26email%3Ddomain%40email.com%26blah%3D1234

Community
  • 1
  • 1
Daniel Ma
  • 646
  • 5
  • 10
  • I think the problem is something about the encoding as well, however I just encoded the url like what you suggested but nothing yet.. – Giannis Tzagarakis Aug 18 '15 at 08:01
  • When you say "nothing yet" what does that mean? Is the request not going through? is your server not receiving the expected data? – Daniel Ma Aug 18 '15 at 08:18
  • I copied your code directly into my console, and as long as the `param1_value`, `url_value`, and `action_url` variables are set, it works fine for me. Can you share any errors or more information about what's wrong? – Daniel Ma Aug 18 '15 at 08:51
  • this code runs inside a google chrome extension. if the submit is successful, a cookie will be created. So, what I am looking for, is a cookie. I can not see any errors.. – Giannis Tzagarakis Aug 18 '15 at 09:57
0

You may have a problem when trying to access another domain/website. The receiving side must have the Access-Control-Allow-Origin header in its return message.

You can probably find your solution in this answer.

Community
  • 1
  • 1
LaVomit
  • 492
  • 5
  • 15
  • Assuming that the `Access-Control_Allow_Origin` does not exist, would I be able to send an html form with the same parameters to the same domain/website? Cause if I create this html form, the request is successful. The problem is on this XMLHttpRequest. – Giannis Tzagarakis Aug 18 '15 at 07:35
  • Yes you can. Though I would recommend you to use jQuery, because then you can use `$('form').serialize()` to pass through `xhr.send()`. Though I think it would be better to use jQuery's `$.ajax()` function like described [here](http://api.jquery.com/jquery.ajax/) – LaVomit Aug 18 '15 at 07:45
0

You are missing quotation to the url string value,alert the parameter string as below

var params = "param1='"+param1_value+"'&url='"+url_value+"'";

Sumit Jambhale
  • 565
  • 8
  • 13