Pages - Menu

Demandware - Ajax Fetch Form Post in React

Scope

Previously, we did a mini project for Demandware - Converting Multi-steps Checkout to One Page Checkout

Ajax post was done by using jQuery as that is the standard javascript framework in Demandware. As we are migrating from jQuery to React, we no longer have the luxury to use $.ajax().


Technical

In our ES6/Javascript, we will use fetch to perform our form post. In React/Redux, we will do this in our action.

By not using jQuery framework, we also no longer be able to use the .serialize() to serialize the Form object. This will need to be done by Vanilla JS and I have found a library just do exactly that. :)

Code


import serialize from 'form-serialize'

export const postFormAjax = (actionUrl) => {
 
 var myForm = document.getElementById('my-form')
 var data = serialize(myForm)
 
 return dispatch => {
 
  var init = {
   credentials: 'same-origin',
   method: 'POST',
   headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
   body: data
  }

  return fetch(actionUrl, init)
   .then(response => console.log(response))
 }
}

Note

  • In the above code, I passed in the actionUrl to my javascript from my Demandware isml by URLUtils.continueURL().toString().
  • We need to manually set the content-type header, otherwise pdict.CurrentHttpParameterMap will be empty.
  • I was trying to use FormData, but I couldn't get it to work with latest Chrome and Demandware. I ended up with bunch of WebKitFormBoundary string that was not usable.



Result

I implemented the above in React and I am able to parse form data correctly in Demandware.



In our checkout page, I can dispatch actions to disable/enable the correct panels while performing ajax post back in the background.


No comments:

Post a comment