Frets
Frets

Reputation: 151

Passing client-side JSON to back-end using ajax

I'm trying to connect the behavior of 2-3 APIs based on JSON responses from one or another API. I'm using ASP.NET MVC and vanilla JS.

The goal is to use a places API (Algolia) so a user can choose a place from an autocomplete input box and after choosing pass the name variable from the JSON to the next API which is a weather API (DarkSky).

The Algolia API is completely JS based and running on the client-side using the following html elements and scripts provided by Algolia:

<input type="search" id="address-input" placeholder="Search for a place.." />
<script>
    var placesAutocomplete = places({
        appId: "my-app-id",
        apiKey: "my-api-key",
        container: document.querySelector('#address-input')
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

After selecting a place the API returns the following JSON structure:

{ 
"query": "new york", 
"suggestion": { 
"name": "New York", 
"country": "United States of America", 
...},
...
}

I want to use the name attribute i.e. "New York" and pass it to my back-end API client so I can use it for the GET request towards the DarkSky API.

I made a AJAX script for posting that value back to my MVC Controller but after a lot of trial and error I still don't know how to setup the Controller action to receive the data and and make it available to the rest of the back-end.

Here is the ajax script:

<script>
placesAutocomplete.on('change', function resultSelected(e) {
        var place = e.suggestion.name || '';
        $.ajax({
            type: 'POST',
            url: 'Ajax', //name of the action in the Home controller
            data: { place }
        })
    });
</script>

Could you please guide me how my action should look like and is my ajax script ok.

Thank you!

Upvotes: 0

Views: 118

Answers (2)

Hasta Tamang
Hasta Tamang

Reputation: 2263

Your Controller Action should look something like below:

public class PlaceController : Controller
{
    [HttpPost]
    public JsonResult Search(string place)
    {
       // process
       return Json(place, JsonRequestBehavior.AllowGet);
    }
}

Your AJAX request

    var place = "New York";
    $.ajax({
        type: 'POST',
        url: "/Place/Search", or // @Url.Action("Search", "Place")
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { place : place },
        success: function(data){

        }
    });

Upvotes: 1

akg179
akg179

Reputation: 1559

the url parameter in the ajax call should be of the format baseUrl+"controllerName/actionName" where 'baseUrl' is the definitive part of the URL which tells you the domain name. For example - 'http://localhost:23456/api'

Something like this:

url: baseUrl + "home/actionName" //here 'home' is the controller name as mentioned in the question

Upvotes: 0

Related Questions