0

From within a javascript file in my rails application: I want to send a JSON request to my application, which returns an array of strings, and capture that return value within a variable.

From the root of the application: the path to the request is: '/employers/get_unique_employer_names.json'

So If I'm in development mode: the full url would be:

http://localhost:3000/employers/get_unique_employer_names.json

Something like this but it doesn't work:

// app/assets/javascripts/application.js 
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).ready(function(){
  var array_of_names = get: '/employers/get_unique_employer_names.json'
});

2 Answers 2

2

I suppose you have injected jquery

$.ajax({
  url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
    console.log("here is you data", data);  
});

and same without jquery

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
       if(xmlhttp.status == 200){               
           console.log("Here is your data", xmlhttp.responseText);
       }           
       else {
           console.log('something else other than 200 was returned');
       }
    }
}

xmlhttp.open("GET", "/employers/get_unique_employer_names.json", true);
xmlhttp.send();

Open console and check for your data

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. I think I'm almost there. Please see my updated question. For some reason it is coming up undefined.
It is correct, but you have to put debugger right after array_employer_names = data; If you put outside done callback then debugger will be called before result of request returned. Ajax requests are asynchronous that is the reason of using done method. You can read about sync/async requests here developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
Also check network tab in inspector to debug whether your request sent without errors
0

array_employer_names is undefined because it is defined in your js file, which make it unvisible from console. it's a scope thing.

you'll able the view it in your console if you change it to

$.ajax({
  url: "/employers/get_unique_employer_names.json"
})
.done(function( data ) {
    window.array_employer_names = data
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.