OctoberCms How to pass ajax response to javascript function

874 Views Asked by At

I created a form in my component html file, When i submit a form an ajax call triggers to my action defined in component. So far my code is working fine i'm getting response. But now i want the response to be passed to the javscript function that i created inside component htm file.

function markAddresses(addresses) {
geocoder = new google.maps.Geocoder();
addresses.forEach(address => {
  geocoder.geocode({'address': address}, function(results, status) {
   if (status === 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({map: map,position: results[0].geometry.location});
       } else {
      alert('Geocode was not successful for the following reason: ' + status);
   }
  });
  })

}

I want to pass my response like markAddresses(response)

<form method="post" data-request="onSend">
<div class="col-md-5">
    <input type="text" name="location" class="form-control">
</div>
<div class="col-md-2">

    <select name="service[]" id="services" class="form-control">&nbsp;
        {% for client in records %}
            <option value="{{ client.service }}">{{ client.service }}</option>
        {% endfor %}
    </select>
</div>
<div class="col-md-2">
    <select name="area[]" id="search" class="form-control" >&nbsp;
        {% for client in records %}
            <option value="{{ client.area }}">{{ client.area }} Miles</option>
        {% endfor %}
    </select>
</div>
<div class="col-md-3">
    <input type="submit" value="Looks for Shops" class="red-btn btn btn-default">
    <a class="location-view" href="#">View all Shops</a>
</div>

This is how my Ajax is working. I think it is using octobercms Ajax framework

1

There are 1 best solutions below

0
On

You can use data-attributes-api

<form method="post" 
      data-request="onSend" 
      data-request-success="markAddresses(data)"
      <!--    ^-- this one -->
>
....
</form>

make sure markAddresses is global function you can access it globally. and data is return value from the handler.

If your handler looks like this

function onSend() {
    return ['test' => 'data'];
}

It will pass object like below in markAddresses as variable data

console.log(data); // output : { "test": "data" }

If any doubt please comment.