AJAX POST request error - `Uncaught TypeError: Illegal invocation` - django

If I try to do this, I get this error:
Uncaught TypeError: Illegal invocation
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
And if I try to do this, I get this error:
403: Forbidden
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
processData: false,
contentType: false,
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
# This is my views.py
def search(request):
return JsonResponse(data={
'test': 'test'
})
What could be the problem?
Your help is greatly appreciated. Thank you

I am so sorry that I bothered everyone.
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
I had done this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]')
But should do this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

Related

Update empty field to contain value - rest API

So I have a snippet of code that will update a field value if the field has content, although if the field that I'm trying to update is null than the value won't update. Am I doing something wrong?
siteURL = _spPageContextInfo.webAbsoluteUrl;
var apiPath = _spPageContextInfo.webAbsoluteUrl +"/_api/lists/getbytitle('Training%20Copy')/items/getbyid(9)";
$.ajax({
url: apiPath,
type: "POST",
headers: {
Accept: "application/json;odata=verbose"
},
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.Training_x0020_CopyItem"
},
Admin_x0020_Function: "Have content"
}),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
async: false, success: function(data) {
console.log("Item updated successfully");
}, eror: function(data) {
console.log("An error occurred. Please try again.");
}
})
There are two headers parameters in your ajax request, it is not clear whether it will affect.
My test code for your reference:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
Update()
function Update(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(9)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: JSON.stringify({__metadata:{'type':'SP.Data.DocItem'},test:'test'}),
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>

TypeAhead: error message instead of suggestions data

I am using typeahead library, it's fetching the data successfully. But not loading the data into the suggestions list, instead its showing the unable to find any company that match current query every time.
Here is my code:
$('#js-typeahead').typeahead({
highlight: true,
minLength: 1
}, {
displayKey: ['title'],
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: function(data) {
return '' + data.title + '';
}
}
});
Here is the fetched data
Please tell me what am I doing wrong here.
[SOLVED]: Here is my final code...
$('.js-typeahead').typeahead({
hint: false,
highlight: true,
minLength: 1
}, {
displayKey: 'title',
source: (new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '{{ route("admin.{$parent['route']}.auto-complete") }}',
prepare: function (keywords, settings) {
return $.extend({}, settings, {
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({
keywords: keywords,
_token: '{{ csrf_token() }}'
})
});
}
}
})),
templates: {
empty: '<div class="empty">No result found</div>',
suggestion: function (data) {
return '<div>' + data.title + '</div>';
}
},
}).on('typeahead:asyncrequest', function(event) {
$('.js-typeahead').before('<i class="fas fa-spinner fa-spin loading"></i>');
}).on('typeahead:asyncreceive', function(event) {
$('.js-typeahead').prev('.loading').remove();
}).on('typeahead:selected', function(event, selection) {
// window.location.href = selection.token;
});
I hope this may come in handy for someone...
You're code is practically correct. And the best thing is that you can also get the result without using bloodhound.
from the initial code you state, you are calling it synchronously. thats why it does not yield any result.from typeahead docs. here is the highlight
Expected to be a function with the signature (query, syncResults, asyncResults). syncResults should be called with suggestions computed synchronously and asyncResults should be called with suggestions computed asynchronously (e.g. suggestions that come for an AJAX request)
so your initial code part
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
are running synchronously, and because you are fetching data from ajax, you should make it asynchronously like this (i added asyncresult)
source: function(keywords, result, asyncresult) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
asyncresult($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
hope it helps!

Django CSRF 403

Getting a CSRF 403. The console.log statements below confirm that I'm grabbing the token. I'm submitting the request to the same domain on my local server.
internal.csrfToken = $.cookie('csrftoken');
internal.csrfSafeMethod = function(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
console.log("ajaxSetup");
console.log(internal.csrfToken);
if (!internal.csrfSafeMethod(settings.type)) {
console.log("Settings type");
xhr.setRequestHeader("X-CSRFToken", internal.csrftoken);
}
}
});
external.submitPayment = function (app_id, charge_now_amount, stripe_plan_id) {
// Submit a payment to the server and handle any errors.
$.ajax({
url: URLS.postPayment,
type: 'POST',
data: {
'app_id': STRIPE_CONFIG.app.id,
'amount': charge_now_amount,
'stripe_plan_id': stripe_plan_id
},
dataType: 'json',
success: function(response) {
alert("Success!");
},
error: function(jqXHR, textStatus, errorThrown ) {
alert("Error!");
}
});
};
not sure if this will help you. I had a similar problem. And fixed it by making a beforeSend functions that's add the X-CSRFToken
$.ajax({
url: url,
data: JSON.stringify({'name': value }),
type: 'POST',
dataType: 'json',
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
},
success: function(response) {
alert("Success!");
}
})

Push info to the store in a success after an ajax request in ember

I'm new with ember and I wanted to know if it was possible to push some information that I've got back from my server into the store in ember.
I've tried this :
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
model: function() {
this.store.push() {
id: data.session.user.id,
username: data.session.user.username
}
}
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});
But obviously I'm wrong, and I don't really know how to do it :/
thanks for your help !!
EDIT:
Here is the new working code. I just forgot a small thing... such as the name of the model..
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
login.store.push('user', {
id: data.session.user.id,
username: data.session.user.username,
firstname: data.session.user.firstname,
lastname: data.session.user.lastname,
email: data.session.user.email,
domainid: data.session.user.domain,
role: data.session.user.role,
status: data.session.user.status
});
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});

Uncaught TypeError: Cannot call method 'request' of undefined in sencha touch2 external webservice

Hi i am new to sencha touch2. i have to consume external web service. i have written code as below in console it is giving error like this Uncaught TypeError: Cannot call method 'request' of undefined. what is the problem, please provide the solution. Thank you
Ext.util.JSONP.request({
url: 'http://localhost/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});​
Add this:
requires: ['Ext.data.JsonP'],
Try using Ext.data.jsonP.request
Ext.data.JsonP.request({
url: 'http://localhost/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});​
DEMO
Hope this helps
Try -
Ext.data.JsonP.request({
url: 'http://A-Valid-Domain/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});​