How to get the Rendering Datasource after an AJAX postback - sitecore

I have the ajax code below:
$.ajax({
url: 'api/sitecore/SmartAds/GetSmartAddsItem',
type: "GET",
dataType: "json",
success: function (result) {
alert(result);
}
});
The problem is the Sitecore.Context.Item.ContextRendering is null in the ajax call.
Question: How do I get the rendering datasource during AJAX call?
I found the below code here, but I am having trouble getting it to work:
public class FormModelBinderProvider : Dictionary, IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
var binders = from binder in this
where binder.Key.IsAssignableFrom(modelType)
select binder.Value;
return binders.FirstOrDefault();
}
}
I am getting an error that says that Dictionary requires 2 type arguments.
Any help is appreciated.

The first issue with your code is that the AJAX request you are making is a 'GET' request rather than a post, so it won't be passing in the hidden field value for the datasource item. To clarify, the article covers situations where a form is posted back, not AJAX GET requests.

Related

Lucee ColdFusion.Ajax.submitForm

I'm converting a site from ColdFusion to Lucee (for the first time). In ColdFusion, after using the cfajaximport tag, I can run JS code similar to this:
ColdFusion.Ajax.submitForm('runMe', 'runCode.cfm', callback_testMe, errorHandler_testMe);
I seem to be unable to run this in Lucee. I'm looking for some kind of Lucee alternative, but can't seem to find anything.
Basically, I'm wanting to submit form data, run some server side stuff, then return the results without refreshing the page.
Any help would be greatly appreciated.
Lucee does not have CF UI tags, you're going to have to do this with jQuery AJAX or similar.
var formID = "runMe"; // formId Param
$("#"+formID).on("submit", function (e) {
e.preventDefault(); // Prevent page load
$.ajax({
type: "POST", // httpMethod Param
url: "runCode.cfm", // URL Param
data: $(this).serialize(),
success: function (data) {
console.log(data); // callbackhandler
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError); // errorHandler
}
});
})
This should do exactly the same thing and I even pointed out the similar params from ColdFusion.Ajax.submitForm

How to handle multiple actions in Django-Template

I have created a web app in which page which consist of choose file input and Now I need to preprocess the data with one button and that preprocessed data should be used for next button called forecast to show the result in that page.Is it possible with Django.
Does it compulsory to take any action in page with url changes in django?
The question is not completely clear, but from what I understand you can use Ajax. On first button click send an ajax request, process it in the view logic, send the appropriate data using maybe JsonResponse, and in the success block of your ajax request set the appropriate data for your forecast button using jquery. Something like -
$.ajax({
url: <url_of_data_processing_logic>,
type: 'post',
data: <required data>,
dataType: 'json',
success: function (data) {
$("#<forecast_button_Id>").html(data.forecast_html);
},
error: function (e) {
console.log(e);
}
});

Why does my Django request.method does not match POST

$.ajax({
type :'GET',
url : geturl(a),
// type: $(this).attr('method'),
dataType : 'json',
views.py:
if request.method=="POST":
if request.POST.get('monyrsubmit'):
monthform=MonthForm(request.POST)
if monthform.is_valid():
selected_month=monthform.cleaned_data["Month"]
selected_year=monthform.cleaned_data["Year"]
print selected_month
print selected_year
can i have both GET and POST requests in the type field of ajax. im using a form and only when the submit button is clicked im trying to display information based on the data submitted. if request.POST.get('monyrsubmit') does not work.
Help will be appreciated
It's very simple. You have to abstract the events.
function event_page_load() {
function ajax_request('GET')
}
function click_submit_button() {
function ajax_request('POST')
}
function ajax_request(type) {
$.ajax({
type : type,
......
......
})
}
You can also consider the follwoign general guidelines.
GET and POST should be used based on the type of the request to the server
- If you are reading the existing data(without modification) from the server, use GET
- if you are writing/modifying any data in the server, use POST
in jQuery, you can use these simple methods.
For GET requests
$.get(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
for POST requests
$.post(
url,
{param1: "value1", param2: "value2"},
function(responseText){
// todo ;
},
"html"
);
Make sure that you have disable the browser caching.
$.ajaxSetup ({
cache: false
});
In django side, you can use request.is_ajax() method to verify the ajax call and you can filter based on request.method property.
You can refer all the possible usages of AJAX with Djano at https://github.com/sivaa/django-jquery-ajax-exmaples

Ajax post for django form not working

For some reason I cannot get a successful post when trying to use ajax. The code I am trying is here:
http://jsfiddle.net/MRKNq/11/
$('#register_form').submit(function(e) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: $('#register_form').serialize(),
success: function(data) {
alert(data.text);
$('#result').text(data.text);
},
type: 'POST'
});
e.preventDefault();
});​
Any suggestions would be greatly appreciated.
You should look at the response that comes back in Firebug or some other tool. This likely has to do with CSRF.
Have a look at this: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
You can also exempt your view from CSRF protection by using this decorator: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt

Display JSON response text from ajax in jQuery Template

I need to pass the response from ajax call to a jquery template.The response json is not malformed.I have checked this by using alert statements in the ajax fn.When the response is passed to the template,it does not get recognized.For example,when I use ${field1} in template,nothing gets displayed in the browser.No error messages are displayed at the browser.Can someone help me fix this issue?
Json response from server:
{
"field1": 23432434,
"field2": "sometext",
}
Ajax fn:
function getinfo(uri)
{
jQuery.ajax({
url: 'http://{{request.META.SERVER_NAME}}'+uri,
success: function(info) {
return info;
},
async: false,
dataType: 'jsonp'
});
}
Template:
<script id="infoTemplate" type="text/x-jQuery-tmpl">
<div>${field1}</div>
</script>
Code to Bind JSON to template:
<script id="Template1" type="text/x-jQuery-tmpl">
{{tmpl(getinfo(uri)) "#infoTemplate"}}
</script>
Note: I can't use the following method to bind JSON with template.That's a long story.
function getinfo(uri)
{
$.getJSON('http://{{request.META.SERVER_NAME}}'+uri, function(data) {
$("#infoTemplate").tmpl(data).appendTo("#somedivid");
});
}
That's not how callbacks work. You're returning info to the callback function, and not to getinfo.
You either have to do something like you proposed after, or keep the result from the ajax call in a global var and call the tmpl function after while, to be sure that you have already got the answer from the ajax call. The first way is the way to go.