Why indented dictionaries don't work in CoffeeScript? - coffeescript

I can't get my head around why this
$.ajax({ url: "http://ruzzle-map.herokuapp.com/bad",
data: { word: $(".words-list li > span.word").eq(current_word).text() },
dataType: 'jsonp',
jsonp: 'jsoncall' })
fails while this
$.ajax({ url: "http://ruzzle-map.herokuapp.com/bad", data: { word: $(".words-list li > span.word").eq(current_word).text() }, dataType: 'jsonp', jsonp: 'jsoncall' })
compiles well.

The compiler seems to be messing up with the indentation on the object literal, if you add a new line after the first opening brace it compiles:
$.ajax({
url: "http://ruzzle-map.herokuapp.com/bad",
data: { word: $(".words-list li > span.word").eq(current_word).text() },
dataType: 'jsonp',
jsonp: 'jsoncall'
})
Given that this is CoffeeScript, you can omit function call parentheses and trust indentation and newlines for the object literals instead of using braces and commas:
$.ajax
url: "http://ruzzle-map.herokuapp.com/bad"
data:
word: $(".words-list li > span.word").eq(current_word).text()
dataType: 'jsonp'
jsonp: 'jsoncall'

Related

Retrieving params with sinatra on form submit. Params is undefined

I am having trouble accessing params in Sinatra after submitting a form. This is my form:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
//grab the inputs from address_section
//data: $('.add_address_section .add_address_field').map(function() { return $(this).val() }),
data: [1,2,3],
dataType: "json",
success: function(data) {
debugger;
}
});
}
And this is my endpoint:
require 'sinatra'
require 'jobcoin_client'
get '/' do
erb :add_coins
end
post '/mix_addresses' do
puts params
end
I'm getting to the endpoint, but the params are blank. Shouldn't it be [1,2,3]? Instead, it's:
{"undefined"=>""}
Anyone see what I'm doing wrong?
Several issues here :)
Sinatra configuration
Main problem is coming from the fact that Sinatra doesn't deal with JSON payloads by default. If you want to send a JSON payload, then the easiest solution will be :
To add rack-contrib to your Gemfile,
Then, require it in your sinatra app: require rack/contrib
And load the middleware that deals with this issue: use Rack::PostBodyContentTypeParser
And you should be good to go!
Source: several SO post reference this issue, here, here or here for instance.
jQuery ajax call
Also, note that there might be some issues with your request :
You'll need to use a key: value format for your JSON payload: { values: [1,2,3] }
You'll need to stringify your JSON payload before sending it: data: JSON.stringify( ... )
You'll need to set the request content type to application/json (dataType is related to the data returned by the server, and doesn't say anything about your request format, see jQuery ajax documentation for more details).
Eventually, you should end up with something like this on the client side:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ values: [1,2,3] }),
success: function(data) {
debugger;
}
});
}

SyntaxError: missing ; before statement in kendoui

how come when i'm clicking on the update button popup kendo grid , this error ocurrs?
The error in Firefox browser is in this form : SyntaxError: missing ; before d.0=value
and in Chrome browser : Uncaught SyntaxError: Unexpected number
I've uploaded a video regarding this error for elaboration n stuff
Jsfiddle Code
Video
Code
transport: {
read: {
url: 'https://dl.dropboxusercontent.com/sh/u9oxg5f6uweqh40/CbR3pNVg04/documentj',
dataType: 'json',
type: 'get',
cache: false
},
update: function(e) { return true; }
}
save: function (e) {
var that = this;
$.ajax({
url: '/echo/json',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(e.model),
success: function (data) {
// Alertify.log.success(data);
console.log('ok dadasaved');
that.refresh();
},
error: function (data) {
// Alertify.log.error(data);
console.log('no datasaved');
that.cancelRow();
}
});
}
You should provide more code to detect what's wrong with your code, but read this may help you:
Such error occurs when the transport definitions are inconsistent. In other words, if you would like to use custom transport method, all transport types should be defined as functions.
Having a standard read transport and custom update is not supported. Please configure all transports as functions and let me know if the error still occurs.
I had the same error and for me the problem was that the dataType option was not set for all transport methods. I marked that line with a comment below:
var linksDataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: 'read-url',
type: "get"
},
destroy: {
dataType: "json", /* <============ THIS LINE WAS MISSING */
url: 'delete-url',
type: "delete"
},
update: {
dataType: "json",
url: 'update-url',
type: "post"
},
create: {
dataType: "json",
url: 'create-url',
type: "post",
complete: function () {
$("#searchResult").data("kendoGrid").dataSource.read();
}
},
/* ... */

Passing several variables to a method in a rest service with node JS

please I need to pass several variables to my rest service implemented with node JS, for now I have this:
Here I am passing just one variable, but I need more variables.
app.get('/announcement/:search', announce.findAllBysearch);
Method Implementation:
exports.findAllBysearch = function(req, res) {
var srch = req.params.search;//Here is receiving the variable
}
I am using it like this:
$.ajax({
type: "GET",
data: '{}',
cache:false,
url: "http://server:4000/announce/"+search,
dataType: "jsonp",
processdata: true,
success: function(data) {
}
});
I would like to do this:
$.ajax({
type: "GET",
data: '{}',
cache:false,
url: "http://server:4000/announce/"+search+'/'+page,
dataType: "jsonp",
processdata: true,
success: function(data) {
}
});
The docs show that you can use regular expressions or multiple variables. Possibly something like this where you would use req.params.search and req.params.page:
app.get('/announcement/:search/page/:page', announce.findAllBysearch);
or with a regex where you would use req.params[0] and req.params[1]:
app.get(/^\/announcement/(\w+)(?:\/page\/(\w+))$/, announce.findAllBysearch)

making jquery AJAX POST to resful API

I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.

how to read jquery.ajax() data in mvc 2 controller

I'm using mvc2 and jqueries to post the data from view to controller.
This is my view
$('#btnSaveAcademicInfo').click(function() {
var recordsToSave = [];
var curRecord = null;
$.each($("#academics tr"), function(i, v) {
curRecord = {};
curRecord.Institution = $(this).find('.tdName').text();
curRecord.PassoutYear = $(this).find('.tdPassOutYear').text();
curRecord.Percentage = $(this).find('.tdPercentage').text();
curRecord.Specialization = $(this).find('.tdspecialization').text();
recordsToSave.push(curRecord);
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function(result) { success(result); },
datatype: "json"
});
});
and my controller is
[HttpPost]
public ActionResult SaveAcademicInfo(List<AcademicModel> data)
{
//Here data is always null
return View("GetPersonalDataById");
}
Here im not getting the data to controller. But when i use, data: JSON.stringify(recordsToSave), I'm able to see the data in firebug.
How do i read the data in controller.
Please help.
JSON.stringify converts a javascript object into a JSON string. If you want to send JSON requests in ASP.NET MVC 2 you need a JSON value provider as this is not built-in. See this blog post for more details. In ASP.NET MVC 3 this works out of the box thanks to the built-in JsonValueProviderFactory.
Also if you want to send a JSON request you need to specify the content type as well:
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: JSON.stringify(recordsToSave),
contentType: 'application/json',
dataType: 'json', // <!-- notice the capital T
success: function(result) {
success(result);
},
});
and if you don't want to use JSON you will need to format the request in a way that the default model binder can understand. Try like this:
var recordsToSave = [];
$.each($('#academics tr'), function (index, value) {
recordsToSave.push({
'name': '[' + index + '].Institution',
'value': $(this).find('.tdName').text()
});
recordsToSave.push({
'name': '[' + index + '].PassoutYear',
'value': $(this).find('.tdPassOutYear').text()
});
recordsToSave.push({
'name': '[' + index + '].Percentage',
'value': $(this).find('.tdPercentage').text()
});
recordsToSave.push({
'name': '[' + index + '].Specialization',
'value': $(this).find('.tdspecialization').text()
});
});
$.ajax({
type: 'POST',
url: '/EmployeeMaster/SaveAcademicInfo',
data: recordsToSave,
success: function (result) {
success(result);
}
});