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

Delete a filename in Internet Explorer with the power of JavaScript and jQuery

In my attempts to clear the file input field in IE using $('#files').val('');, I found that it was not effective. $('#uploadimgdiv').html(''); var fil1 = document.getElementById("files"); $('#fil1').val(&a ...

Simple method for validating a text box field using jQuery without the need for a form

I am looking for a way to activate jquery unobtrusive validation without a form using the specified pattern: <script type="text/javascript"> $('.btnAddAsync').click(function (e) { e.preventDefault(); // Avoid href p ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...

Error: doc.data().updatedAt?.toMillis function is not defined in this context (NextJs)

I encountered an error message while trying to access Firestore documents using the useCollection hook. TypeError: doc.data(...)?.updatedAt?.toMillis is not a function Here is my implementation of the useCollection Hook: export const useCollection = (c, q ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

OroCrm is ensuring that Symfony2 profiler seamlessly updates the footer data without triggering a 404 error page within a popup

As a newcomer to OroCrm, I recently installed and configured it on my DEV environment using the app_dev.php entry point. After setting up OroCrm, I immediately noticed the Symfony2 profiler bar appearing at the bottom of the interface. While this was a he ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> loop cont ...

There was a rendering error: "Type Error: Unable to access the 'PAY_TYPE' property of null"

I am attempting to retrieve the PAY_TYPE value from the callback_details object by using JSON.parse() function to convert a string into an object. However, I keep encountering an error related to the question's title. Here is my code snippet: <td ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

Tips for displaying my libraries' function arguments while hovering in VSCode

As the creator of a JavaScript library, I am intrigued by how some libraries display function parameters and definitions when hovering over them in VSCode. Despite my efforts to add jsdoc style comments around the class definitions, I have not been able to ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

Removing values in javascript for checkboxes that are not selected

Here is the JavaScript Code : var clinicalStat; var id; var val; var clinicalVals; $(":checkbox").click(function() { //alert(" you checked"); if ($(this).is(':checked')) { var checked1 = $(this).val(); //Inital value of check ...

What is the best way to reset the scroll position of a div when you stop hovering over a link?

Can anyone help me figure out how to reset the scroll wheel when hovering over dropdown menu items? I've tried multiple solutions found online, but none seem to be working for me. If you have any ideas on how to accomplish this, please let me know! f ...

Launching a pre-built React application

I'm facing an issue while attempting to run a pre-existing React App on my Mac locally. I have all the source files and node.js installed on my machine. Upon running npm install, I encountered a massive list of deprecations and npm ERRors that surpas ...

Tips for hovering over a link with Webdriver

Currently, for my project, I am utilizing Selenium Webdriver. Successfully automating the functionality to mouse over an image has been achieved. However, there seems to be an issue when attempting to trigger a mouse-over event on a hyperlink using the sam ...

Delete an <li> element upon clicking a span tag

I've been attempting to fadeOut some <li> elements, however I haven't had any success. Here's my code below: <li class="lclass" id="1"> First Li <span class="removeit" id="1" style="color:#C00;">Remove</span> ...