Guidance on sending Ajax response to JavaScript function in OctoberCMS

In the HTML file of my component, I have created a form. When I submit the form, it triggers an AJAX call to an action defined in the component. Currently, my code is functioning properly and I am receiving a response. However, I now need this response to be passed to a JavaScript function that I have created within the component's HTML 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. It appears to be utilizing the OctoberCMS Ajax framework.

Answer №1

Utilize the data-attributes-api for your project.

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

Ensure that markAddresses is a global function that can be accessed globally, and data represents the return value from the handler.

If your handler function is as follows:

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

It will provide an object like the following to the markAddresses function as the variable data:

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

If you have any questions, feel free to leave a comment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML content does not reload when using AJAX

I have been experimenting with this code to show text and then fade it out: $('#submit_new_player_order').click(function(e){ //some data to define data_to_send $.post(ajaxurl, data_to_send, function() { alert('it is in here') ...

Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users, Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no ...

Can I determine if onSnapshot() has detected any updates prior to fetching the data?

While navigating to a page, I pass parameters like "Discounts" and display that number in the render(). However, I call onSnapshot() right at the beginning of navigating to that class. My goal is to initially display only the value of the parameter and the ...

Using DataTable with backend processing

Has anyone successfully implemented pagination in DataTable to dynamically generate the lengthMenu (Showing 1 to 10 of 57 entries) and only load data when the next page is clicked? I'm currently facing this challenge and would appreciate some guidance ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

Modify the size of images while shuffling using Javascript

Hey there! I've got some bootstrap thumbnails set up and I'm using a script to shuffle the images inside the thumbnails or a element within the li. It's working fine, but some of the images are coming out larger or smaller than others. I&apo ...

Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears: <template ...

Using JavaScript to open a new window and display CSS while it loads

I am looking to utilize a new window for printing a portion of HTML content. var cssLink = document.getElementByTagName('link')[2]; var prtContent = document.getElementById('print_body'); var WinPrint = window.open(' ...

Is there a way to use JavaScript to rearrange the order of my div elements?

If I have 4 divs with id="div1", "div2", and so on, is there a way to rearrange them to display as 2, 3, 1, 4 using Javascript? I am specifically looking for a solution using Javascript only, as I am a beginner and trying to learn more about it. Please p ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

Mastering the art of bi-directional data binding with nested arrays in Angular

Imagine you have a to-do list with various tasks, each containing multiple subtasks. You want the ability to change the subtask data, but why is Angular not properly two-way binding the data for the subtasks? HTML <div *ngFor="let task of tasks"> ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

URL not receiving AJAX request

I encountered an issue while attempting to send an ajax request to a specific URL in order to receive a JSON response. However, the request does not appear to be going to /login as expected. Instead, it remains on the current URL and appends the formData p ...

I've tried multiple stack overflow solutions, but none of them seem to be effective for my issue. What am I missing

Having encountered this common question multiple times, I stumbled upon an article discussing how to allow users to refresh their browser without facing the dreaded "Confirm Form Resubmission" pop-up. The article can be found here. Following the recommend ...

What are the differences between displaying JSON data on a Flask interface compared to a Django interface

Currently, I am looking for the simplest method to display data on a web interface using either Flask or Django (whichever is easier). I already have some sample JSON objects available. Could anyone provide recommendations on how to achieve this and whic ...

Learn how to verify changing form inputs with Vue watchers. The challenge of numbers

Currently, I am working on a sum application and encountering some challenges with input validations. I have implemented Watcher to handle the validations, and I am exploring the possibility of adding sound and color feedback for accurate validation. Repo ...

Tips for enabling multiple v-list-group components to remain open simultaneously (bypassing the default Vue behavior)

Currently, I am facing an issue with Vue's default behavior where only one v-list-group can be open at a time. I am using Vuetify 2.6 and have attempted to use the multiple prop without success. Additionally, individually assigning the :value prop to ...

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...