Yii2 - Ajax CSRF Token: Unexpected token "-" - ajax

In yii advanced template, I am trying to send something via ajax without disable csrf validation.
However, _csrf-frontend caused an error called " Unexpected token - "
$.ajax({
type: "POST",
url: "'.Url::to(["testctrl/testact"]).'",
data: {prod_id:id,_csrf-frontend:'.Yii::$app->request->csrfToken.'}
});
What should I use instead?
Thanks in advance!

Change to this format.
'_csrf-frontend':'".Yii::$app->request->csrfToken."',
I think this will work for you

Related

$http.post data format in AngularJs

Problem Question:
I am making a post call to my API but keep on getting 500 server error. After doing some debugging API is expecting data in different format
API excepting --
user[email] -- json would be {user =>{email=>'test#test.com'}
I am sending as
return $http.post(urlBase + '/users/password',{email: email});
json is like {"user":"test#test.com"}
Recently started learning. So please guide me or provide me with any resources.
Try to send this:
{"user": {"email":"test#test"}}
This is similar to:
user.email = "test#test";
In your case:
return $http.post(urlBase + '/users/password',{user:{email: email}});
This is a good reference for this: JSON Syntax
try this one,
$http({
method: 'POST',
url: urlBase + '/users/password',
data: $.param({email: email})
});
OR
$http({
method: "POST",
url: urlBase + '/users/password',
params: {email: email}
);

Pass Codeigniter CSRF string to server via AJAX

I have enabled Codeigniter's CSRF protection on my site that uses AJAX to submit a user form and handles some other user interaction which require data submission via AJAX. As a result I came up against the "action not allowed" server side error. I quickly worked out that only the data my javascript collected and submitted via AJAX was passed to the server and as a result the CSRF code was not being sent.
The generated token tag looks like:
<input type="hidden" name="csrf_test_name" value="dsflkabsdf888ads888XXXXXX" />
So it seems to me the simplest way to submit the token to the server for verification is using a jQuery selector on csrf_test_name to get the value and then adding this to my post data for the server to verify. As per the code below:
//get CSRF token
var csrf = $('[name="csrf_test_name"]').val();
//build the form data array
var form_data = {
csrf_test_name: csrf,
... ... ...
... ... ...
}
//send the form data to the server so it can be stored
$.ajax({
type: "POST",
data: form_data,
url: ...,
dataType: "html",
success: function(msg){
... ... ...
}//end success
});//end ajax
I have followed this procedure for every ajax submission that sends data to the server and the server side error is fixed and everything works fine.
To test this I have hard coded in an incorrect CSRF token and the server detects the inconsistency and returns an erro code 500 so on the surface this works.
My question is this, is this a safe way to do this and is there an expected best practice to follow? I have done some google searching on this and it seems all the other methods are more complex and I am wondering if my way creates an attack vector that I can't see/workout.
I like to add it to the Ajax setup. Set it once and have it automatically add it to the post data for all of your requests.
$.ajaxSetup({
data: {
csrf_test_name: $("input[name='csrf_test_name']").val()
}
});
an easier method is to pass that csrf to $.ajaxSetup() that way it's included with any $.ajax() request afterward.
var csrf = $('input[name="csrf_test_name"]').val();
var data = {};
data[CSRF] = csrf;
$.ajaxSetup({ 'data': data });
then no need to include data: { csrf_test_name: 'xxx', ... } in requests after setup.

sending data from angularjs to django

I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:
$http({
method: 'POST',
url: '/url/',
data: 'test data'
}).
success(function(data, status, headers, config) {
doSomeStuffWhenSuccess();
});
The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.
<QueryDict: {u'test data': [u'']}>
I don't have a clue why. What am I missing?
I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.
I resolved this with jQuery param function. I think it's more elegant solution.
$http({
method: 'POST',
url: '/url/',
data: $.param({test: data})
})
Now it works like I wanted.
I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...
if you'd try:
$http({
method: 'POST',
url: '/url/',
data: 'test=data'
})
You should get
<QueryDict: {u'test': [u'data']}>
You can always obtain the data (raw body content) as follows:
request.body
Hope this is what you are looking for.

Sending javascript dictionary with array values via ajax through a bookmarklet

I have data that I want to send through an ajax GET request in following format -
{'url':['www.google.com','www.yahoo.com']}
Here is the ajax request - $.ajax({type:'GET',url:'http://www.example.com/',processData:false,data:JSON.stringify({'url':['www.google.com','www.yahoo.com']})
And since I am doing this in a bookmarklet it looks like this -
<a href="javascript:function iprl5() { $.ajax({
type:'GET',
url:'http://www.example.com/',
processData:false,
data:JSON.stringify({'url':['www.google.com','www.yahoo.com']}),
dataType:'json',
contentType: 'application/json',
success: function(json){$('#confirm').html('<p>Thanks!</p>');},
error: function(){$('#confirm').html('<p>Something went wrong :( please reload</p>');} })}} iprl5(); void(0)">BLAH</a>
The problem is that when I hit the bookmarklet browser sends a get request like this -
GET http://www.example.com/?{"url":["www.google.com","www.yahoo.com"]}
I want to send a json as a string but unable to do so, I also tried encodeURIComponent to encode string but that didn't work either.
I would try: data: 'url=' + JSON.stringify(['www.google.com','www.yahoo.com']),

Kanbanpad API calls (jQuery AJAX)

I'm having an issue getting this jQuery.ajax call to work. When the script executes I get an error (textStatus = "error"), but no error message (errorThrown = "").
$.ajax({
type: 'GET',
url: 'http://www.kanbanpad.com/api/v1/projects.json',
username: 'user#example.wtf',
password: 'myAPIkey',
dataType: 'json',
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus+': '+errorThrown);
}
});
If I manually hit the API URL (above) and type in my login credentials, I do get the proper JSON response. So, I'm not sure what I'm doing wrong. Is my code malformed?
If you need more information about the API, go to http://www.kanbanpad.com/api/v1
That page is using HTTP basic auth but you are simply posting a username/password in your request. You have to properly set up the auth tokens and pass them in a header. Here is a simple tutorial on HTTP basic auth over AJAX--notice there is a jQuery specific example for the AJAX part.
Here is the fix:
Change URL value to http://username%40domain.com:apikey#www.kanbanpad.com/api/v1...
For whatever reason, jQuery (1.5.1, also tried with 1.4.4) is not passing the username and password parameters to the web server correctly (or not at all?), so rather than use those parameters, it can authenticate by including the credentials in the URL string.
use secured protocol for URL: https://www.kanbanpad.com/api/v1/projects.json, not http

Resources