简体   繁体   中英

AJAX Send POST Variables to PHP

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);
 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM