I have a form that will send the completed data through PHP, but, before being sent, I want the value of a hidden input to be changed through JavaScript when the user clicks the submit button. As if you were using asynchrony between javascript and php.
This is the javascript:
const getCoords = (dir) =>{
const direccion = dir.replace(/ /g,"+"),
$mapa = document.querySelector(".mapa");
fetch('https://maps.googleapis.com/maps/api/geocode/json?address='+direccion+'&key=AIzaSyCz8IS8ryD6Z5kn8Rvq6DwObryxnZcBDpo')
.then(response => response.json())
.then(data =>{
let latitud = data.results[0].geometry.location.lat,
longitud = data.results[0].geometry.location.lng
document.getElementById("coords").value = "{latitud}, {longitud}" //aqui cambio el value del input hidden
})
}
document.getElementById("submit").addEventListener("click", ()=>{
getCoords(document.getElementById("ubication")) //ejecuto la funcion en base a lo que se ha rellenado en otro de los input
})
The hidden input is filled based on the value that another input has. With the code as it is, it tells me that my field that is filled by the hidden is null because the javascript code is not executed.
How can I make the form "wait" for javascript before being submitted?
You need to cancel the event to apply the modifications you want and then continue with its execution. To do this you must link the event to a listener and then in the callback apply the function
.preventDefault()
to the event that arrives as the callback argument, this will allow you to stop the action and have full control.Fear not, you can then resume the call to make the process invisible to the user without needing to click the send button twice.
I leave you a referential example of what you want to do.