The data variable returns nothing when it should return "OK" or "EXISTS".
I have a template with an overlay effect. The income.html template has a form and a button "Add a new category", when you click on it a new window is displayed(overlay effect) with a tiny form.
income.html:
(document).ready(function(){
$("#new_cat").live("click", ( function() {
var cat_name = $("#nc").val();
if (cat_name) {
$.get("/cashflow/new_cat/0/", { name: cat_name, account: {{ account }} },
function(data){
if (data == "OK") {
$("#id_category").val(cat_name);
}
if (data == "EXISTS") {
var error = "The category already exists";
alert(error);
}
});
}
else {
var error = "Please enter a name";
alert(error);
}
}))
});
</script>
...
<form>{% csrf_token %}
<label for="name">Name:</label><input type="text" id="nc" />
<input type="submit" value="Submit" id="new_cat" />
</form>
views.py:
#login_required
def income(request, account_name):
account = account_name
if request.method == 'POST':
form = TransForm(user=request.user, data=request.POST)
if form.is_valid():
income = form.save(commit=False)
income.type = 0
income.account = Account.objects.get(
name = account_name,
user = request.user)
income.name = form.cleaned_data['name']
income.category = form.cleaned_data['category']
income.save()
uri = ("/cashflow/account/%s") % str(account_name)
return HttpResponseRedirect(uri)
else:
form = TransForm(user=request.user)
context = {
'TransForm': form,
'type': '0',
'account': account,
}
return render_to_response(
'cashflow/income.html',
context,
context_instance = RequestContext(request),
)
def new_cat(request, type):
if request.method == u'GET':
GET = request.GET
if GET.has_key(u'name'):
name = request.GET[u'name']
account = request.GET[u'account']
c = Category.objects.filter(name=name, account=account)
if c:
s = "EXISTS"
else:
c = Category(name = name, user = request.user,
type = type, account = account)
c.save()
s = "OK"
return HttpResponse(s)
Are you crossing domains? You cannot do cross-domain ajax requests. That includes subdomains.
Related
I'm trying to build a 'like' button with ajax and flask,but when I try to get the string for the button to decide which button was clicked,my alert always return 'None'.
flask relevant part:
#bp.route('/<int:id>/post', methods=('GET', 'POST'))
#login_required
def show_post(id):
my_opinion=request.form.get("opinion")
my_post=get_post(id,False)
if request.method == 'POST':
opi = request.form.get("opinion")
if opi == 'Like':
update_like(id,my_post,g.user['id'])
my_opinion='like'
elif opi == 'Dislike':
update_dislike(id,my_post,g.user['id'])
my_opinion='dislike'
user_info=g.user['id']
user_new = get_db().execute(
'SELECT liked_posts,disliked_posts'
' FROM user u'
' WHERE id = ?',
(user_info,)
).fetchone()
return render_template('blog/show.html',post=my_post,user=user_new,my=my_opinion)
ajax part:
<script src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).on('submit','.opin',function(e)
{
e.preventDefault();
$.ajax({
type:'POST',
url:'/1/post?author=josh',
data:{
opinion:"check"
},
success:function()
{
const new_opinion = document.getElementsByClassName("opinion");
let special = "{{my}}";
alert(special);
const cssObj = window.getComputedStyle(new_opinion[0], null);
let bgColor = cssObj.getPropertyValue("background-color");
if (bgColor=='rgb(128, 128, 128)'){
bgColor="linear-gradient(144deg,#AF40FF, #5B42F3 50%,#00DDEB)";
}
else{
bgColor="gray"
}
new_opinion[0].style.background=bgColor;
}
})
});
</script>
This part alert 'None':
let special = "{{my}}";
alert(special);
I'm trying to get 'check' string into 'my' template parameter.
I write code that will be deleted from the product database. For this I need to perform in ajax that if the operation was performed then it will also delete the row in the table on the page.
the code behind -
public IActionResult OnPost (int id)
{
try
{
Order order = Order.Where (a => a.Id == id) .FirstOrDefault ();
_context.Order.Remove (order);
_context.SaveChanges ();
JsonType returnJson = new JsonType {Status = 0, Massage = "success"};
return new JsonResult (returnJson);
}
catch
{
JsonType returnJson = new JsonType {Status = 1, Massage = "canceled"};
return new JsonResult (returnJson);
}
}
The code on the page-
<form method = "post" asp-route-id = "# item.Id" data-ajax = "true" data-ajax-confirm = "Are you sure?" data-ajax-success = "deleteItem (this)">
<input type = "submit" value = "delete" asp-route-id = "# item.Id" class = "dropdown-item" />
</form>
And the javascript code
function deleteItem (form) {
$ (form) .parent (). parent (). css ({
"display": "none"
});
}
The problem when the file fails, it also deletes the row in the table.
So I thought of getting the response.
function deleteItem (response) {
// if response ...
}
But then I write the code on the page like this -
<form .... data-ajax-success = "deleteItem">
....
</form>
And I can not get both data at the same time,
How can this be done?
Try this
<form method = "post" asp-route-id = "#
item.Id" data-ajax = "true"
data-ajax-confirm = "Are you sure?"
data-ajax-success = "deleteItem">
<input type = "submit" value = "delete" asp-route-id = "# item.Id" class = "dropdown-item" />
</form>
var deleteItem= function(context){
console.log(context);
};
I have some contact form and JS/Angular code sending it to view for some validation and mailing.
contact_form.js
(function() {
var app = angular.module('contactForm', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});
app.controller('contactFormController', ['$http', '$scope', function($http, $scope){
$scope.contact_form = {};
this.send = function(form){
if (form.$valid){
$http.post('/contact_form_submit/', {'form': $scope.contact_form}).
success(function(data, status, headers, config) {
if (data.status == 1) {
$scope.msg = 'Twoja wiadomość została wysłana.';
$scope.contact_form = {};
$scope.contactForm.$setPristine();
}
else if (data.status == 'delay')
$scope.msg = 'Odczekaj.';
}).
error(function(data, status, headers, config) {
$scope.msg = 'Wystąpił błąd.';
if (status == '403')
$scope.msg += ' Włącz cookie!';
});
}
else
this.msg = 'invalid!';
};
}]);
})();
view.py
def contact_form_submit(request):
return return_json(request)
if not request.is_ajax() or (request.method != 'POST'):
raise SuspiciousOperation
response_data = {}
# dealing with existing (or not) delay entry
try:
if request.session['mailer_delay'] > str(timezone.now()):
response_data['status'] = 'delay'
return return_json(response_data)
except KeyError:
pass
# validation
form_data = {}
for field in ['name', 'email', 'phone', 'subject', 'text']:
form_data[field] = request.POST.items()
# mailing
mailer = send_mail('Subject here', 'Here is the message.', 'from#example.com',
['to#example.com'], fail_silently=False)
request.session['mailer_delay'] = str(timezone.now()+timedelta(seconds=60))
response_data['status'] = mailer
return return_json(response_data)
and the return_json()
def return_json(data):
from django.http import HttpResponse
import json
return HttpResponse(json.dumps(data), content_type="application/json")
The problem is i get no items at all in request.POST in view. Firebugs tells me that data was sent correctly, but there's no in view.
Someone knows the answer what's wrong?
Ok, i got it. All data was in request.body, not request.POST.
Could anyone explain why? I've read the docs, but still it's not clear for me.
I am working on Grails framework. I have 2 domain classes Country and City with one-to-many relationship. My idea is when the page is loaded the gsp will have two select boxes, one populating the countries and when any country selected the cities of that country are populated in second select box. here i am using grails ajax (jquery).
import grails.converters.JSON
class CountryController {
def index() { redirect action: 'getCountries' }
def getCountries() {
def countries = Country.list()
render view:'list', model:[countries:countries]
}
def getCities() {
def country = Country.get(params.id)
render country?.city as JSON
}
}
When getCities action is fired i am getting the JSON as below:
[
{
"class":"com.samples.City",
"id":3,
"country":{
"class":"Country",
"id":2
},
"description":"California",
"name":"California"
},
{
"class":"com.samples.City",
"id":4,
"country":{
"class":"Country",
"id":2
},
"description":"Dalls",
"name":"Dalls"
}
]
But from my gsp page when evaluating JSON with eval function, its returning "undefined".
<g:select name="countrySelect" from="${countries}"
optionKey="id" optionValue="name"
noSelection="[null:'Select Country']"
onchange="${
remoteFunction(action: 'getCities',
update: message,
params: '\'id=\' + this.value',
onSuccess:'updateCity(data)')
}"/>
<br/>
City :: <g:select name="city" id="city" from=""></g:select>
Following code in tag
<head>
<g:javascript library="jquery"></g:javascript>
<g:javascript>
function updateCity(data) {
alert('done');
var cities = eval("(" + data.responseText + ")") // evaluate JSON
alert(cities)
var rselect = document.getElementById('city')
// Clear all previous options
var l = rselect.length
while (l > 0) {
l--
rselect.remove(l)
}
//build cities
for(var i=0; i < cities.length; i++) {
var opt = document.createElement('option');
opt.text = cities[i].name
opt.value = cities[i].id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
}
</g:javascript>
<r:layoutResources />
</head>
Can anyone help me finding out where is the problem?
I got it solved by using JQuery each method on JSON data.
<g:javascript>
function updateCity(data) {
var rselect = document.getElementById('city')
$.each(data, function(index, element) {
//alert(element.name);
var opt = document.createElement('option');
if(element.name !== undefined){
opt.text = element.name
opt.value = element.id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
});
}
</g:javascript>
i have a kendodropdown list with the workername and details... how can i fetch the ID of the selected worker so i can able to save... everytime i save it returns a null value in ID.. thanks for those who can help
Heres my code:
<input id="titles" class:"validate[required] inputLong" style="width: 400px;" />
$(document).ready(function () {
var clientCusPosId = $("#clientCusPosId").val();
$("#titles").kendoDropDownList({
dataTextField: "workerName",
dataValueField: "workerID",
autoBind: false,
// define custom template
template:
'<h5>${ data.workerName }</h5>' +
'<p>${ data.workerID }</p>' +
'<p>${ data.AvailableDay_LookID }</p>' +
'<p>${ data.StartTime } - ${ data.EndTime }</p>',
optionLabel: "Assign worker",
dataSource: {
transport: {
read: {
url: '/Client/LoadWorkerDropdownList?clientCusPosId=' + clientCusPosId,
dataType: "json",
type: "POST"
}
}
}
});
var dropdownlist = $("#titles").data("kendoDropDownList");
dropdownlist.list.width(250);
});
My Controller:
[Authorize]
[HttpPost]
public ActionResult ClientWorkerPositionSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientWorkerPosId = formCollection["clientWorkerPosId"];
String clientID = formCollection["clientId"];
String clientCusId = formCollection["clientCusPosId"];
String workerID = formCollection["titles"];
Client_Worker_Position clientCusPos = new Client_Worker_Position();
try
{
if (String.IsNullOrWhiteSpace(clientWorkerPosId) || clientWorkerPosId == "0")
{
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateCreated = DateTime.UtcNow;
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.CreatedBy = User.Identity.Name;
clientCusPos.ModifiedBy = User.Identity.Name;
db.Client_Worker_Position.Add(clientCusPos);
}
else
{
int id = Convert.ToInt32(clientWorkerPosId);
clientCusPos = (from a in db.Client_Worker_Position
where a.ID == id
select a).SingleOrDefault();
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
return RedirectToAction("ClientCustomerDetails", new { });
}
It could be as simple as using $("#titles).val() to get your WorkerID since it has already been configured.
Create a hidden input field hidden id="workerID" then before your post or in a drop down change event set it to $("#workerID").val($("#titles).val()). This should come across in your controller collections.