1

I am used to sending AJAX requests with jQuery. I now find myself with the task of having to send them using 'vanilla' JS. Using my limited knowledge, I managed to get everything working except for passing the data along with the request. The two variables that are supposed to be being passed along are always filled in as NULL in my database. Every example I have been able to find on here shows the jQuery way, which I have no problem doing.

Can anyone tell me what I am doing wrong? I assume it has something to do with the format of the data, but cannot for the live of me figure it out.

Here is the code for the request. The request object is built in the createXMLHttp() function.

var xmlHttp = createXMLHttp();
var data = {Referrer: document.referrer, Path: window.location.pathname};
xmlHttp.open('post', '/PagePilotSiteHits.php', true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(data);
1
  • You need to pass the data as querystring Commented Jan 26, 2015 at 21:14

1 Answer 1

1
 var data = {Referrer: document.referrer, Path: window.location.pathname};

 function buildQueryString(data)
 {
     var dataKeys = Object.keys(data);
     var queryString = "";
     for (var i = 0; i < dataKeys.length; ++i)
     {
         queryString += "&" + dataKeys[i] + "=" + encodeURICompenent(data[dataKeys[i]]); 
     }
     return queryString.substr(1);
 }

 xmlHttp.send(buildQueryString(data));

This should do it. The data needs to be passed as a querystring. This functions will create a querystring from the data object you've provided and encodes the uri components as mentioned by @AlexV and @Quentin.

Sign up to request clarification or add additional context in comments.

3 Comments

And don't forget tu escape the data with encodeURIComponent() !
xmlHttp.send( encodeURIComponent(data) ); will break the data. You need to run encodeURIComponent on each component of the data, not the whole thing.
@Quentin. True, to fast here :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.