csrf token is changing where it shouldn't be changed - javascript

I'm running code below to prevent CSRF vulnerability
if (!isset($_POST['_token'])) {
$_SESSION['_token'] = bin2hex(random_bytes(20));
}
and i am using the token in hidden inputs named _token. I use the following code in my main.js file so that the user can add the product to their favorites.
const wishlist = {
'add': function (id) {
$.ajax({
url: 'api/wishlist?method=add',
type: 'post',
dataType: 'json',
data: 'id=' + id + '&_token=' + $('input[name="_token"]').val(),
success: function (response) {
console.log(response)
}
})
},
'remove': function (id) {
$.ajax({
url: 'api/wishlist?method=remove',
type: 'post',
dataType: 'json',
data: id,
success: function (response) {
console.log(response)
}
})
}
};
Below is the code in wishlist.php which ajax request goes to
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location:' . site_url('404'));
}
if (!isset($_POST['_token']) or $_POST['_token'] != $_SESSION['_token']) {
die('Invalıd CSRF Token!');
}
if ($_GET['method'] == 'add') {
$json['method'] = "adding to favorites";
}
if ($_GET['method'] == 'remove') {
$json['method'] = "removeing from favorites";
}
The all code is this but sometimes this code works sometimes it gives Invalid csrf token error and sometimes it works for 3-5 times and gives error again.

I found the solution. It was because client is trying to access to an non-exist file
so that that request executes init.php

Related

My AJax Request Not Woking On click of an icon

i want to send a ajax call on click of a icon.
Admin.js
$('.user-status').click(function() {
var userId = this.id;
var userStatus = $(this).attr('data-status');
alert('clicked');
$.ajax({
type: "get",
url: siteUrl + 'admin/change-user-status',
data: { userId: userId, userStatus: userStatus },
dataType: 'html',
success: function(data) {
console.log(data);
}
})
})
Route.php
Route::get('/admin/change-user-status', [AdminController::class, 'changeUserStatus']);
But when I click on icon I am getting the alert clicked, but the ajax call is not being initiated.
The alert is coming
But no ajax request initiated
No error in console
i am using webpack
mix.js(['resources/js/dashboard-template.js', 'resources/js/admin.js'], 'public/js/admin.js');
You can use a tool: "Network" (see screenshot)
And you will be able to see if it is well sent.
An ajax request is by default sent with "xhr", so I advise you to sort by xhr as I did on the screenshot
Network screenshot
You should also add the error method and a timeout (to be sure that the server returns a response)
$('.user-status').click(function() {
var userId = this.id;
var userStatus = $(this).attr('data-status');
alert('clicked');
$.ajax({
type: "get",
url: siteUrl + 'admin/change-user-status',
data: { userId: userId, userStatus: userStatus },
dataType: 'html',
timeout: 5000, //ms
success: function(data) {
console.log(data);
},
error: function(a,b,c){
console.log(a,b,c)
}
})
})

I am struggling to pass data to controller through Ajax

Trying to hit DeleteJobQuote controller through Ajax but no luck. Please guide me if anyone has any idea about it. The code seems OK but not able to do so. I am writing this code to delete a particular record from database.
Controller
[HttpPost]
public ActionResult DeleteJobQuote(int jobQuoteid)
{
using (var db = new KeysEntities())
{
var delJob = db.JobQuote.FirstOrDefault(x => x.Id == jobQuoteid);
if (delJob != null)
{
delJob.Status = "Delete";
db.SaveChanges();
return Json(new { success = true, Message = "JobQuote SuccessFully Deleted!" });
}
else
{
return Json(new { success = false, Message = "Delete UnSuccessFul " });
}
}
}
And JavaScript and Knockout code for this
self.deleteJobQuote = function (jobQuote) {
debugger;
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
};
Change "data : ko.toJSON(this)" to "data: JSON.stringify({ jobQuoteid: 1 })". I have hardcoded jobQuoteid value to 1. Get it from jobQoute object.
complete code:
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ jobQuoteid: 1 }),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});

error in ajax request to action controller asp mvc

i have button that when you click on it
it run ajax that send id to controller
now controller do something and its ok no error in server side,,
but in the action in controller i have code with restsharp that
send request to rest web service its work fine too(),
but this part() is in foreach and run for 5 or ... time
and when i do this things sometime ajax takes to long and the error part of ajax code is run
what should i do ?
ajax code:
$(document).on("click", "#btn-submit", function () {
$.ajax({
type: 'POST',
url: '/Panel/CheckRefOrderCode',
data: JSON.stringify({
factorrefid: $("#ref-check").val()
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.DntSuccess) {
} else {
}
},
error: function () {
}
});
});
action code
foreach(string s in str)
{
var client = new RestClient("http://**.com/api/v1/orders/status?support_code=71GD4A");
var request = new RestRequest(Method.POST);
request.AddHeader("token", "15befa43");
IRestResponse response = client.Execute(request);
RefOrderJsonViewModel.RefOrderJson reforderbackJson =
JsonConvert.DeserializeObject<RefOrderJsonViewModel.RefOrderJson>(response.Content);
if (reforderbackJson.status.ToLower() == "ok")
{
performed += reforderbackJson.data.performed;
order_status += reforderbackJson.data.order_status + "^";
}
}
and i add this to web.config
<httpRuntime executionTimeout="100000000" maxRequestLength="262144" />
Add a timeout to the ajax call:
$(document).on("click", "#btn-submit", function () {
$.ajax({
type: 'POST',
url: '/Panel/CheckRefOrderCode',
data: JSON.stringify({
factorrefid: $("#ref-check").val()
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
**timeout: 10000 // sets timeout to 10 seconds**
success: function (result) {
if (result.DntSuccess) {
} else {
}
},
error: function () {
}
});
});
Check out this post on how to handle timeout error.
the problem still is on;
but i use this
Parallel.ForEach(myEnumerable, obj =>
{
// ...
});
instead regular
foreach
and do the body of foreach in parallel,
and the time is decreasing,
the problem solved

Repeating an AJAX request after login

I'm sending some information via AJAX to a PHP-Script to get some text, which should be displayed. So far there is no problem. But if the user is logged out, the result would be false and a modal with a login-form is shown.
If the user gets logged in, the first information (var data) should be send one more time, as the first sending wasn't accepted.
$.ajax({
url: "script.php", type: "POST", data: data, dataType: "json"
})
.done(function( json ) {
if (json.result === false) {
showModal("login"); return;
}
else {
$('#result').html(json.result);
}
});
The showModal function is also connected to an ajax request, so the user is getting logged in... After that the first data should be send one more time...
function showModal() {
$('body').append('<form>...'); // Show Modal with form to login
}
// With submit form, the user will be logged in
$('body').on('submit','#loginform',function(event){
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
// User is now logged in
// Now repeat first request
});
});
Put your code inside a function. You can call a function whenever you need it:
var sendData = function() {
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.result === false) {
showModal("login"); return;
}
else {
$('#result').html(json.result);
}
});
};
// now run sendData() when you want to trigger it
Where to call sendData() the second time depends on how your login (showModal) works. Find a way to catch a 'successful login' event.
You can pass sendData to the showModal function and call it there. This way showModal does not need to know anything about data:
var sendData = function() {
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.result === false) {
// The function sendData is passed as a parameter - will be called after a successful login
showModal("login", sendData); return;
}
else {
$('#result').html(json.result);
}
});
};
Then, where showModal is defined:
function showModal(dialog, loginCallback) {
$('body').append('<form>...'); // Show Modal with form to login
// With submit form, the user will be logged in
$('#loginform').on('submit', function(event) {
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
// User is now logged in
// Now repeat first request
loginCallback();
});
});
}
You can have the ShowModal function to accept another argument as ajax Options. The if ajax options are defined just call them in the done.
function showLoginModal(ajaxOptions){
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
if(ajaxOptions!== undefined){
$.ajax(ajaxOptions);
}
});
}
Then pass the ajaxOptions from your calling function
$.ajax({
url: "script.php", type: "POST", data: data, dataType: "json"
})
.done(function( json ) {
if (json.result === false) {
showLoginModal(this);
}
else {
$('#result').html(json.result);
}
});

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

Categories