devonian666's avatar

jQuery Pass Data Parameter to Function

Hi all,

I'm trying to pass the 'data' parameter of my AJAX call which is within a function and it's not working. My Javascript/jQuery is below:

$(document).ready(function(){

   function geocode(location){
      $.ajax({
         type: 'post',
         url: '/test',
         data: location,
         dataType: 'json',
         success: function(data){
            //alert(data);
            $('#exampleModal .modal-body').html(data);
            $('#exampleModal').modal('toggle');
         }
      });
   }

   // BOF Current location...
   $('.current-location').click(function(){
      if ("geolocation" in navigator){ //check geolocation available
         //try to get user current location using getCurrentPosition() method
         navigator.geolocation.getCurrentPosition(function(position){
            //Run AJAX...
            location = { lat: position.coords.latitude, lng: position.coords.longitude };
            geocode(location);
         });
      }else{
         alert('Your browser does not support geolocation!');
      }
   });
   // EOF Current location...

});

Upon submit, I'm just redirected to the following: http://localhost:8888/[object%20Object]

To be clear, I'm trying to pass JSON to the function as a parameter but it's not having it. Any help would be hugely appreciated. You will save my bacon!

0 likes
9 replies
jlrdw's avatar
data : JSON.stringify(location),
jlrdw's avatar

Have you tried something like:

data: {
            lat: $('#latitude').val(),
            long: $('#longitude').val()
        },

// whatever your fields are called.

I'm just trying to help you pass some data, I am no expert on geo locations.

Try to set up a simple jquery routine, and get it where you can pass a simple parameter first, then try the geo data.

Try changing

function geocode(location){

To a click event, perhaps a button.

devonian666's avatar

This is my full code before attempting this, I'm calling exactly the same function with with different data. The code below works, but it's code replication so would rather abstract it into a function. Any suggestions on a potential way forwards?

$(document).ready(function(){

   //Setup AJAX...
   $.ajaxSetup({
      headers: {
         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
   });

   function geocode(location){
      $.ajax({
         type: 'post',
         url: '/test',
         data: JSON.stringify(location),
         dataType: 'json',
         success: function(data){
            //alert(data);
            $('#exampleModal .modal-body').html(data);
            $('#exampleModal').modal('toggle');
         }
      });
   }

   // BOF Current location...
   $('.current-location').click(function(){
      //alert('Boo');
      if ("geolocation" in navigator){ //check geolocation available
         //try to get user current location using getCurrentPosition() method
         navigator.geolocation.getCurrentPosition(function(position){
            //Run AJAX...
            $.ajax({
               type: 'post',
               url: '/test',
               data: { lat: position.coords.latitude, lng: position.coords.longitude },
               success: function(data){
                  //alert(data);
                  $('#exampleModal .modal-body').html(data);
                  $('#exampleModal').modal('toggle');
               }
            });
         });
      }else{
         alert('Your browser does not support geolocation!');
      }
   });
   // EOF Current location...

   // BOF Postcode Finder...
   $('.postcode input[type=submit]').click(function(e){
      //Get postcode...
      postcode = $('.postcode input[name=postcode]').val().toUpperCase();

      //Run AJAX...
      $.ajax({
         type: 'post',
         url: '/test',
         data: { postCode: postcode },
         success: function(data){
            //alert(data);
            $('#exampleModal .modal-body').html(data);
            $('#exampleModal').modal('toggle');
         }
      });

      e.preventDefault();
   });
   // EOF Postcode Finder..
});
jlrdw's avatar

but it's code replication so would rather abstract it into a function.

Sorry I don't understand.

The code below works

It's in a jquery function already. Where would you want it put.

devonian666's avatar

Sorry, ignore the geocode function, I didn't mean to include that. Based upon my above code (without the geocode function), I'm using exactly the same AJAX call twice, apart from a different 'data' object within the AJAX call. That is code replication.

So instead of writing the same code twice, what would be a better way of writing this so to combine the AJAX call into one function and fed different 'data' parameters.

Sorry, I appreciate this is a bit of a mind fuck, but hope I've explained clearly. Thank you so much for bearing with me and understand my problem, your very kind.

jlrdw's avatar
jlrdw
Best Answer
Level 75

This example is not your code:

<script>

$(function () {
    function makeAJAXRequest (text) {
        $.ajax({
            url: 'owner/getowner',
            type: 'GET',
            dataType: 'json',
            data: { id: text },
            success: processSuccess
        });
    }

    function processSuccess (data) {
        $.each(data, function (key, value) {
            var id = '#' + key,
                elem = window.opener.$(id);
           if (key === 'ocheck') {
                elem.attr('checked', value === '1');
            }
            else {
                elem.val(value);
            }
        });

        self.close();
    }

    $("#myTable td:nth-child(1)").click(function (event) {
        event.preventDefault();

        var $td = $(this).closest('tr').children('td');
        var currentCellText = $td.eq(0).text();
        var CellText = $td.eq(1).text();

        makeAJAXRequest(currentCellText);
    });
});



</script>

Take note of

 makeAJAXRequest(currentCellText);

So basically, play around with having some functions you can re-use, such as makeAJAXRequest.

Backup all first and just see what you come up with.

Your

$.ajax({
               type: 'post',
               url: '/test',
               data: { lat: position.coords.latitude, lng: position.coords.longitude },
               success: function(data){

is completely re-usable by sending it variables instead of hard coded data, i.e., /test could be sent as a variable for use.

I hope you get the general idea.

devonian666's avatar

Hi there, many thanks for your detailed reply, much appreciated. I've had a bit of a tinker and got things working as I wanted. Many thanks again for your reply and sharing your knowledge.

jlrdw's avatar

@DEVONIAN666 - Glad you got it, I may share this post in future with others who may need similar advice, all the best.

Please or to participate in this conversation.