Trying to load in a form from a third party service
They want us to load the script for their service then another script to populate the form with html/data
//load the marketo script if it doesn't exist already
const loadMarketoScript = (callback) => {
const existingScript = document.getElementById('mktoForms');
if (!existingScript) {
const script = document.createElement('script');
s.id = "mktoForms";
s.type = "text/javascript";
s.async = true;
s.src = "//app-ab11.marketo.com/js/forms2/js/forms2.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
script.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};
export default loadMarketoScript;
//page calling the function to load the script
const [loaded, setLoaded] = useState(false);
useEffect(() => {
loadMarketoScript(() => {
setLoaded(true);
});
});
useEffect(() => {
MktoForms2.loadForm("//748-KKO-677.mktoweb.com", "748-KKO-677", 1169);
}, [loaded]);
However MktoForms2 shows as undefined. Unsure what to do here.
2
Answers
It seems like the issue is that the script for MktoForms2 is not loaded properly. Here’s what you can do to fix it:
Double-check if the script URL for MktoForms2 is correct. Make sure that it is the correct URL and that it is accessible.
2 Make sure that the script is loaded before trying to use the MktoForms2 object. You can do this by either adding the defer attribute to the script tag or by waiting for the load event to fire before using the object.
If the above steps do not work, try using a different method to load the script, such as using the fetch API or a library like jQuery.
Here’s an updated version of the code that implements these changes:
Note that in this updated code, we are using getForm instead of loadForm to retrieve the form object. We are also adding onSuccess and onSubmit event handlers to the form object. You can modify these event handlers to suit your needs.
It seems the second
useEffect
hook doesn’t wait for anything to actually be loaded prior to callingMktoForms2.loadForm(....);
. TheuseEffect
hook is guaranteed to be called on the initial render, and then again anytime a dependency updated.The first
useEffect
hook is also missing its dependency array, so anytime the component renders the callback will be called andloadMarketoScript
will be called. An empty dependency array should be added if you only want to attempt to load the market script when the component mounts.Alternatively you could call
MktoForms2.loadForm(....);
in theloadMarketoScript
callback that is only ever called after the script is loaded.