OH THE JOYS OF AJAX (AJAX Examples)

<script type="text/javascript">
$.ajax({
    type: 'PUT',
    url: "http://localhost:3001/week/2017/2/celebrate/1",
    data: {
        "celebration[text]": "something very brilliant"
    },
    success: function(data) {
        console.log("Success!!")
    },
    error: function(data) {
        console.log("Error!!");
    }
})
</script>

OH THE JOYS OF AJAX. Ajax is great because it allows you get away from HTML form elements. You can save your form answers to a javascript variable. AJAX sucks because CORS. AJAX sucks because it seems like a guessing game to get it to work. You’ll read online 5 people got it to work by adding this line, 4 others with a different line and you try both and it doesn’t work. THEN YOU JUST GO APE SHIT ON YOUR CODE AND DELETE A BUNCH OF LINES AND ALL OF A SUDDEN IT WORKS.

FUCK. THEN PEOPLE BE LIKE YO DAWG YOU AINT GONNA INCLUDE JQUERY JUST TO DO AJAX R U? AND I SAY FUCK YES I AM BECUZ IT MAKES IT WAY FUCKING EASIER AND YOU ALREADY MAKE IT DIFFICULT AS FUCK, so fuck YES I’m including jquery JUST TO HAVE .ajax.

Let’s say you have a string that you want to be apart of a URL. I’ve found this works pretty damn well to turn a " " into a "+"

let encodedAddress = encodeURIComponent(this.state.address).replace(/%20/g,'+');

"123 Main Street" => "123+Main+Street"


$.ajax({
  url: "https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddress + "&key= googlegeocodeapikey",
  success: function(data) {
    console.log("Success!!")
    data.results[0].geometry.location.lat
    data.results[0].geometry.location.lng
  },
  error: function(data) {
    console.log("Error!!");
  }
})

Here is an ajax request that works with Phoenix and Elixir

$.post({
  url: "http://localhost:4000/api/searches",
  dataType: 'json',
  data: {
    search: {
      mood: mood,
      radius: this.state.selectedDistance,
      budget: this.state.selectedBudget,
      address: this.state.address
    }
  },
  success: function(data) {
    console.log("Your request succeeded!");
    console.log(data);
  },
  error: function(data) {
    console.log("Your Request ended in an error");
    console.log(data);
  }
})

OH AND JUST BECAUSE YOUR AJAX REQUEST WORKS TO YOUR LOCAL DEV DOES NOT MEAN IT WILL WORK ON PRODUCTION, FYI. URLS NEED TO BE UPDATED (although it is possible to do that automatically).

Post Content