Uncaught SyntaxError: Unexpected token u - javascript

I am trying to get a JSON response from a get request. However, I am getting the following error: Uncaught SyntaxError: Unexpected token u. I know the rails route works because I do get the response loaded successfully in the Console.
The Ajax Response is supposed to start when the checkbox changes and is checked.
Why am I getting this error from the $.parseJSON?
Rails Controller
def providers
#providers = User.order("last_name ASC, first_name ASC, middle_name ASC").where("provider_flag = ? and inactive_flag = ? and del_flag = ?", true, false, false).select("id, CONCAT(IFNULL(last_name,''), ', ', IFNULL(first_name,''), IFNULL(middle_name,'')) AS full_name");
respond_to do |format|
format.json { render :json => { :providers => #providers.to_json}, :status => :ok }
# format.json { render :json => #providers.to_json }
end
end
Javascript
$('#provider_chk').change(function() {
if($(this).is(":checked")) {
$.ajax({
url: '<%= providers_schedule_index_path %>',
type: 'GET',
dataType: 'json',
data: {
authenticity_token: $('meta[name=csrf-token]').attr('content')
},
success: function(data) {
console.log('loaded successfully.');
var providers = $.parseJSON(data.responseText)['providers'];
providers_count = $(providers).size();
console.log(providers);
console.log(providers_count);
},
error: function(data) {
console.log("An error has occurred!")
}
});
} else {
$('#providers_results').empty();
}
});
JSON Response
providers: "[{"id":2,"full_name":"Test, User"}]"

Your JSON response should look more like this:
providers: [{"id":2,"full_name":"Test, User"}]
The outermost quotations marks aren't needed.
If you really need the outer quote marks, you need to escape the inner ones.

In $.ajax({}), add the property "async:false". parseJSON hasn't gotten that JSON yet - it's immediately trying to operate on undefined ("u") and throwing the error.

Remove to_json since you are already telling rails to return json
format.json { render :json => { :providers => #providers }, :status => :ok }

Related

Rejected Promise but response.ok is true. JavaScript Rails fetch request "Failed to execute 'json' on 'Response': body stream already read"

I am trying to pass a member's information from my Rails backend to my vanilla JS frontend after a member logs in. This way I will be able to store the member's id to later persist data to the backend for the member's profile (e.g. if the member added a new book to their wishlist).
I am able to authenticate the member and confirm their credentials in the backend, but when I try to send the logged in member info from rails to the JS frontend, I get the following error when I run resp.json() in console.
Failed to execute 'json' on 'Response': body stream already read. Interestingly, I am getting a 'true' response.ok, and status: 201, but am not able to access the member's data.
[[PromiseResult]]: TypeError: Response {type: "cors", url: "http://localhost:3000/login", redirected: false, status: 201, ok: true, …}
[[PromiseState]]: "rejected"
Here's my sessions controller: The create action is the struggle.
class SessionsController < ApplicationController
def create
#member = Member
.find_by(email: session_params[:email])
.try(:authenticate, session_params[:password])
binding.pry
if #member
login!
render json: {
logged_in: true,
member: #member
},
status: :created
else
render json: {
status: 401,
errors: ['No such member', 'Verify credentials and try again or sign up']
}
end
end
def is_logged_in?
if logged_in? && current_member
render json: {
logged_in: true,
member: current_member
}
else
render json: {
logged_in: false,
message: 'no such member'
}
end
end
def destroy
logout!
render json: {
status: 200,
logged_out: true
}
end
def session_params
params.require(:member).permit(:email, :password)
end
end
My application controller:
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
helper_method :login!, :logged_in?, :authorized_member?, :logout!, #current_member (current_member is currently in controller/concerns)
def login!
session[:member_id] = #member.id
end
def logged_in?
if #current_member
render json: {
logged_in: true,
member: #current_member
}
else
render json: {
logged_in: false
}
end
end
def authorized_member?
#member == current_member
end
end
and my JavaScript fetch request Side bar: I do not believe I need the commented out lines:
async function submitLogin() {
let email = document.getElementById("login-email").value;
let password = document.getElementById("login-password").value;
const memberLogin = { member: { email, password } };
let options = {
method: "POST",
credential: "same-origin",
headers: {
"Content-Type": "application/json",
// "Access-Control-Allow-Origin":
// "file:///Users/awb/Coding/Flatiron/Projects/bookclub-javascript-rails-api/bookclub-frontend-javascript/index.html",
// "Access-Control-Allow-Methods": "POST",
// "Access-Control-Allow-Headers": "Content-Type, Authorization",
Accept: "application/json",
},
body: JSON.stringify(memberLogin),
};
fetch("http://localhost:3000/login", options)
.then((resp) => {
resp.json();
debugger;
})
}
It's probably javascript fetch - Failed to execute 'json' on 'Response': body stream is locked. Promises can be resolved only once.
Since your function is async, try:
let response = await fetch("localhost:3000/login", options);
let data = await response.json();

Not able to pass parameters through url in Ajax request using Rails

I'm trying to pass a parameter through a url in an Ajax request that's triggered by a confirmation dialogue. I'd like to fetch the value of that parameter in my Rails controller given a successful request but I haven't been able to do it.
I've tried so far the following code:
Here my Ajax request where I've been adding the param in the URL plus other params in data
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "POST",
url: "/leaderboards/1/?test=1",
data: { leader: { name: name, time: time } },
success: success
});
}
Here the dialogue-related JS
function nameAlert() {
return confirm("Name already exists. Would you like to continue?");
};
(function() {
if (nameAlert()) {
continueSave();
}
else {
//something else here
}
})();
Although the request successfully reaches the controller there's params[:test] is nil in the controller.
I've also tried to pass the test param in data, but it is not working either.
Would appreciate some help.
The relevant controller action (leaders_controller.rb)
def create
#leader = Leader.new(leader_params)
#leader.leaderboard_id = #leaderboard.id
#name_repeated = !#leaderboard.leaders.find_by(name: #leader.name).nil?
#check = params[:test]
if params[:test].nil? && #name_repeated == true
render :template => 'leaders/repeated_name.js.erb'
else
#leader.save
#rank = #leader.rank_in(#leaderboard)
respond_to do |format|
if #leader.save
format.html { redirect_to root_path }
format.js { }
else
end
end
end
end
Note:
1.- 'leaders/repeated_name.js.erb' contains the code for the Ajax request
2.- In routes Leader resource is nested within Leaderboard resource
Sorry guys I found the mistake. It was a dumb one.
I have shallow nested routes so that leaders is nested in leaderboards, therefore I was using the incorrect path for the request. It should be:
$.ajax({
type: "POST",
url: "/leaderboards/1/leaders?test=1",
data: { leader: { name: name, time: time } },
success: success
});
I should have caught that before sorry for wasting your time.
I'll post here - my comments are getting too long.
Try adding { type: 1} to your data and changing type to GET. Rails params contain both GET and POST data - you don't even have to change your controller.
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "GET",
url: "/leaderboards/1/",
data: { leader: { name: name, time: time }, test: 1 },
success: success
});
}

Routing error in ajax on ruby on rails

I have this in my .html.erb code:
$.ajax({
url: "/timeMachineEdit",
data: {editTimeMachine: newArray},
type: 'POST',
success: function (res) {
if (res.result === 'ok') {
alert('Data saved');
} else {
alert('Save error');
}
},
error: function () {
alert('Save error.');
}
});
This in my datasets_controller.rb
def timeMachineEdit
#dataset = current_user.dataset
#dataset.machine_time = params[:editTimeMachine]
end
And in my routes.rb:
match "/timeMachineEdit", to: "datasets#timeMachineEdit"
But when is submited shows:
POST http://localhost:3000/timeMachineEdit 500 (Internal Server Error)
Where is the problem here?
is the routes in the ajax url or something else?
The problem is in your route definition....
try match "/timeMachineEdit", to: "datasets#timeMachineEdit"
I think, it will still not work because of the nature of format..In the datasets_controller try the following code...
def timeMachineEdit
#dataset = current_user.dataset
#dataset.machine_time = params[:editTimeMachine]
respond_to do |format|
format.js
end
end
Also change the dataType of your AJAX request to "script" in order to correctly match it with format.js else the format will be / which will select the first format that you will specify in the respond_to block..

Cannot receive Rails response with Ajax

When I post from phonegap (with ajax, in javascript) something to my rails server, the post succeeds, but I have no response from my server, so finally it fails. I don't understand why I cannot get the response ..
For example, here is my sign up script (javascript with ajax):
$('#sign-up-button').click(function(e) {
var str = $("#signUpForm").serialize();
$(".error").remove();
e.preventDefault();
$.ajax({url: "http://localhost:3000/api/users.json",
type: "POST",
data: str,
success: function(result, status) {
alert('success');
$.mobile.changePage( "welcome.html", { transition: "slide"} );
},
error: function(result) {
alert('error');
}
});
});
and my code on Ruby on rails side:
# POST /users
# POST /users.json
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render json: #user, status: :created }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
In firebug, I have : the message 201 Created, the user is created (I can check it), but I have no response, so the message alert('error') appears ...
Thanks a lot for your advices!
If you are expecting an empty response such as a 201, you need to specify dataType: 'text' in your $.ajax options. What's happening right now is that jQuery is attempting to parse the response as JSON, and failing as there is no response to parse.
I've just stopped to try making it working with Firefox, and launched it in X-code.
It worked.
I was wondering if I needed to work on a server to obtain a response from a post, somebody knows if X code creates a server?

How to access json in javascript after rendering it in rails

If I render json in Ruby, how do I access the values in javascript?
In ruby, if I write:
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
How would I access "val" in javascript?
If I do alert(response) in javascript, I see a tag surrounding the json, does this make a difference or is this expected?
I tried jQuery.parseJSON(response) but I got a syntax error. If I try to access response directly, I don't get the correct value- should
response.key === "val"
evaluate to true?
Am I setting it up incorrectly in Ruby or accessing it incorrectly in javascript, or both?
It would really help if you could show your javascript code.
Anyway, one way you can do it is to use jQuery's ajax function and set the dataType to json.
$.ajax({
type: "GET",
url: "<your link>",
dataType: "json",
success: function(response) {
if (response.key)
alert(response.key);
});
});
Hope this helps.
Here's a quick example.
In ./config/routes.rb
match '/index' => 'application#index'
match '/json' => 'application#json'
The controller, ./app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def index
# server side code required by index
end
def json
response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200
end
end
The erb page an ajax request is made from, in this case ./app/views/application/index.html.erb:
<script type="text/javascript" charset="utf-8">
$(document).ready(
function(){
$("a#my_ajax").bind("ajax:success",
function(evt, data, status, xhr){
console.log(data.key);
console.log(data.key === "val");
}).bind("ajax:error", function(evt, data, status, xhr){
console.log("doh!")
});
});
</script>
<%= link_to "test", {:controller=>"application", :action => 'json'}, :remote=> true, :id => "my_ajax" %>

Categories

Resources