Updating a Rails Model From JS Event - javascript

I have been looking around and cannot seem to find out if it is common practice to update a Rails model attribute from a JS callback.
In one of my views I have a datepicker that sends a callback once the value has been changed. I would like to save this date to the current model "date" attribute.
$('#datetimepicker4').on('dp.change', function (e) {
// SAVE THIS VALUE TO SPECIFIED MODEL ATTRIBUTE HERE
});
Any suggestions would be very much appreciated. Thanks!
Edit: This is common practice, Ended up getting it working with the following ajax put request.
$.ajax({
type: "PUT",
dataType: "script",
url: '/thread/27',
contentType: 'application/json',
data: JSON.stringify({ thread:{id:27, title:"blaaahhh title"}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
});

I'm not sure if you've done much research beforehand, because this is a very common thing to do.
Your terminology is also wrong. You're not changing anything in the model. You're simply POSTing a value to your database. Do some research on AJAX and then ask a more detailed, but concise question.
There's nothing wrong with being a beginner, but please do research beforehand, and then create a Stack Overflow question only if that research has led to dead ends. Then create a question featuring what you already know and where you're stuck.

Related

Find definition of the 'action' inside 'data' object in jquery

I'm a back-end dev that inherited code that looks like this
xhr = jQuery.ajax({
type: 'POST',
url: ajax_url, // ERROR!!
dataType: "json",
data: {
action: 'properties', <---------------------------------
data: url_vars,
url: document.URL
},
I know that the action called properties has to be defined somewhere, but I'm not sure how to find it.
I read multiple threads on SO, but this is not a form action, so I'm not sure how one would go about finding it. If an experienced front-end dev saw this name, what would they look for specifically inside the code?
Apologies for the newbie question, but this is a bit confusing.
Closest answer I found is the data.action is an attribute action of the object data is a value that you known cos we haven't any reference, unfortunately I'm not even sure where to look for any reference apart from analyzing 1000+ times the word 'properties' is mentioned in the framework's code.
Any help is greatly appreciated.

Post a variable to json format in Ember.js

I apologize if this question seems basic as I am new to both stackoverflow and javascript in general.
My goal here is to store the user's dropdown menu selection as well as some other user inputs into variables, then I want to post the json file that contains the variables into a specific route where my serve-side javascript can read from. I have the variable part and user selection part covered, however, I am having trouble posting the variables to the specified route.
So in my app.js file in my ember framework, I tried the below code to test out if I can post {12345} to address:port/api/iwantmyjsonhere/ but when I run it and go to that specific page (address:port/api/iwantmyjsonhere/), it says cannot GET.
$(document).ready(function() {
$.ajax({ url : "/api/iwantmyjsonhere/",
type: 'POST',
dataType : "json",
data: "12345"
});
});
I understand that this question is lower level, so if you guys are too busy to answer, point me to any resources that might help me would be greatly appreciated too! Thanks in advance!
I guess this is not related to ember anywhere.
You are just using jQuery for ajax call and as per jQuery standards "Data" Object must be Key/Value pairs.
Means you should do something like -
$(document).ready(function() {
$.ajax({ url : "/api/iwantmyjsonhere/",
type: 'POST',
dataType : "json",
data: {id:"12345"}
});
});
You can read more on this one at -
http://api.jquery.com/jquery.ajax/
And if you want to implement it in ember way the you can use something like -
return Ember.$.ajax({
url: '/api',
method: 'POST',
dataType: 'json',
data: {//key value pairs}
}).then(function(result){
//After ajax is successful.
}

Ajax Error: SyntaxError: Unexpected token < error

So I have searched the forum for similar questions unfortunately I have been unlucky to find an answer that suits my problem.
I am trying to make an ajax call in my jquery using the following code;
function submitForm(formData)
{
$.ajax({
type: 'POST',
url: 'addEvents.php',
data: formData,
dataType:'json',
cache:false,
timeout:7000,
success: function(data){
$('#addEventsForm #response').removeClass().addClass((data.error === true) ? 'error' : 'success').html(data.msg).fadeIn('fast');
if($('#addEventsForm #response').hasClass('success')){
setTimeout("$('#addEventsForm')",5000);
}
},
error:function(XHR,textStatus,errorThrown)
{
$('#addEventsForm #response').removeClass().addClass('error').html('<p> There was an <strong>' + errorThrown +
'</strong> error due to <strong>'+ textStatus +'</strong> condition.</p>').fadeIn('fast');
console.log(arguments);
//alert(XMLHttpRequest.responseText);
},
complete:function(XHR,status)
{
$('#addEventsForm')[0].reset();
}
});
}
But I am getting a sysntax error. I have tried doing this to see what errors I get in chrome
console.log(arguments);
but the responseText in the [Object, "parsererror" , SyntaxError] node seems to display the entire html of the page that contains the form where I am inserting the record.
I am still getting my feet wet in ajax so I am not yet a pro in absolutely understanding the error messages and what they mean.
Is the above js/jQuery code located on the addEvents.php page -- that is, on same page that you are posting the AJAX to? (In other words, are both the form/ajax and the AJAX destination on the same physical PHP page?)
If so, you will get exactly what you describe: the entire HTML of the page spat back at you.
AJAX, by design, must post to a different physical page on the server. That's just how it works.
Also, FWIW, note that dataType: 'json', refers to the data being returned, not the data being sent. Perhaps you already know this, but it is a common misunderstanding so is worth mentioning.
Edit:
As Felix points out, this answer is not technically perfect. It is possible to post AJAX code to the same page, but you must specifically allow for that. Perhaps FK or another could edit this post to add an example of what that additional code would look like?

How can I add an event to a Google calendar using v3 API and JQuery?

I am attempting to teach myself some JQuery/REST/Google API by putting together a simple page that does the following:
Authenticates with Google
Validates a token
Gets a list of Google Calendars for the user
List events for a selected calendar
Add an event for a selected calendar
I have #1 through #4 working (although no doubt in an ugly manner), and am getting tripped up on #5. Here's the JQuery ajax call:
var url = 'https://www.googleapis.com/calendar/v3/calendars/[MY_CALENDAR_ID]/events?sendNotifications=false&access_token=[GOOGLE_API_TOKEN]';
var data = { end: { dateTime: "2012-07-22T11:30:00-07:00" }
, start: { dateTime: "2012-07-22T11:00:00-07:00" }
, summary: "New Calendar Event from API"
};
var ajax = $.ajax({ url: url
, data: data
, type: 'POST'
}).done(addEventDone)
.fail(function (jqHXR, textStatus) {
console.log("addEvent(): ajax failed = " + jqHXR.responseText);
console.log(jqHXR);
});
The results are a global parseError: "This API does not support parsing form-encoded input.". The first four steps are all using GET ajax calls, so I'm not sure if that is what is tripping me up.
Here's the API in question: https://developers.google.com/google-apps/calendar/v3/reference/events/insert
I think I may be doing things the long and hard way, and my new approach is to tackle this using the javascript API instead of going straight at it with manual JQuery and REST. This is the approach I am attempting going forward http://code.google.com/p/google-api-javascript-client/wiki/Samples#Calendar_API, although I would still love to use this as a learning opportunity if there is something simple I am screwing up in the code above.
Thanks for any help, insights, pointers, etc. I will post updates if I make any progress using the javascript API.
Interestingly, I just answered a similar question here. Your intuition to use Google's JS client library is a good one. It's going to handle OAuth 2 for you, which is a requirement if you're going to do any manipulation of the Calendar data.
My other answer has both a link to a blog post that I authored (which demonstrates configuration of the client and user authorization), as well as an example of inserting a Calendar event.
you need to set contentType: "application/json", to do JSON.stringify for your data and method : 'POST'
var ajax = $.ajax({
url: url,
contentType: "application/json",
data: JSON.stringify(data),
method : 'POST',
});

Django ajax view csrf fails with 500 error

I have a Django view, named vote. It is protected by a #login_required decorator, and in normal use works completely fine.
I decided it would be a worthwhile idea to start looking into ajax and javascript to make the system more dynamic, and so I implemented something like the below for my first try:
$(function() {
$(".vote").click(vote);
});
var vote = function() {
pk = $(this).attr('pk');
$.ajax({
type: "POST",
data: "pk=" + $(this).attr("pk"),
url: "/link/" + $(this).attr("pk") + "/vote/",
});
};
Which successfully POSTS to the correct URL. When I look at the output with firebug, I find I'm getting 500 errors. I've included the snipped from https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax into my pages, which I had thought would solve the CSRF issue, however it appears not to have done so.
Wondering whether I'm missing something obvious!
Thanks!
Turns out the way that I solved this was to tidy up the above:
var vote = function() {
pk = $(this).attr('pk');
data = {
'pk': pk
};
$.ajax({
type: "POST",
data: data,
url: "/link/" + pk + "/vote/",
});
};
Thus tidied, I then checked out the view, and discovered that it was not pulling the correct value out of the DataDict passed to it by ajax, which was where the 500 error was coming from.
I had previously encountered a 403 due to the CSRF issue, for those wondering how to solve that, I simply used the script mentioned in the question above, saved in a 'csrf.js' file in the /static/js/ directory of my app, and then included that as one of the scripts, which then solved that issue.

Categories