Anti Forge Token and Ajax JSON Post Does not Work - ajax

I am running MVC3, .Net 4 and VS2010. I have following sample project to illustrate the problem.
My controller code
namespace AntiForgeAjaxTest.Controllers
{
public class IndexController : Controller
{
public ActionResult Index()
{
MyData d = new MyData();
d.Age = 20;
d.Name = "Dummy";
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyData data)
{
NameValueCollection nc = Request.Form;
return View(data);
}
protected override void ExecuteCore()
{
base.ExecuteCore();
}
}
}
My view and JavaScript code
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
alert(JSON.stringify(myObject));
$.ajax({
type: 'POST',
url: '/Index/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myObject),
success: function (result) {
alert(result);
},
error: function (request, error) {
alert(error);
}
});
});
});
</script>
</body>
</html>
Here I have 2 buttons, the first one triggers form post, the second one triggers Ajax post. The form post works fine, but the Ajax one does not, the server complains A required anti-forgery token was not supplied or was invalid. even though I have included the token in my JSON already.
Any idea what is wrong with my code?

This code works.
#model AntiForgeAjaxTest.Models.MyData
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("Index", "Index"))
{
#Html.AntiForgeryToken()
<table>
<tr>
<td>Age</td>
<td>#Html.TextBoxFor(x => x.Age)</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBoxFor(x => x.Name)</td>
</tr>
</table>
<input type="submit" value="Submit Form" /> <input type="button" id="myButton" name="myButton" value="Ajax Call" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
post();
});
});
function post() {
var myObject = {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
Age: $('#Age').val(),
Name: $('#Name').val(),
};
$.post('/Index/Index/', myObject);
}
</script>
</body>
</html>

Related

angular js ng-repeat is not working

In ng-repeat do not show any data but the data is available in response.
The loop is not working properly.
<html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.passward}}</td>
</tr>
</form>
</div>
</body>
console.log(response) show the data in console
<script>
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http) {
$http.get("show.php")
.then(function (response) {
$scope.names=response.data;
console.log(response)
} );
});
</script>
</html>
So I tried your code and have a few corrections, the reason you are not able to see any data may be due to, usage of tr and td tags without the table tag as the parent, please check my below code, where I have added the table and tbody tags, Also, inorder to simulate a http request, I have use the $timeout which will set the data after 3 seconds, please study the example and implement it to your code!
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http, $timeout) {
var data = [{
name: "one",
email: "one#one.com",
password: "1234"
}, {
name: "two",
email: "two#two.com",
password: "1234"
}, {
name: "three",
email: "three#three.com",
password: "1234"
}, ]
$timeout(function() {
$scope.names = data;
}, 3000);
/*$http.get("show.php")
.then(function(response) {
$scope.names = response.data;
console.log(response)
});*/
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<table>
<tbody>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.password}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

Select2 The Result Cannot Be Load in CodeIgniter

When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.
Here is my controller
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
function search_book(){
$booksClue = $this->input->get('booksClue');
$data_book = $this->admin_model->get_book($booksClue, 'id_book');
echo json_encode($data_book);
}
}
?>
Here is my model
<?php
class Admin_model extends CI_Model{
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->like('id_book', $booksClue);
$data = $this->db->from('book')->get();
return $data->result_array();
}
}
?>
And here is my view
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('.searchingBook').select2({
placeholder: 'Masukkan ID Buku',
minimumInputLength: 1,
allowClear: true,
ajax:{
url: "<?php echo base_url(); ?>/admin/searchbook",
dataType: "json",
delay: 250,
data: function(params){
return{
booksClue: params.term
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.id_book,
text: item.id_book
});
});
return{
results: results
};
}
}
});
});
</script>
<table>
<tr>
<td><b>ID Buku</b></td>
<td> : </td>
<td>
<select class="searchingBook" style="width: 500px">
<option></option>
</select>
</td>
</tr>
</table>
<br><br>
</body>
</html>
Big thanks for your help!
Update your model function like below:
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->from('book');
$this->db->like('id_book', $booksClue);
return $this->db->get()->result_array();
}

asp.net mvc + Ajax.BeginForm OnBegin not firing

After reading several posts regarding this issue, it is mostly related to including
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
and the proper order of including jquery first.
<script src="~/Scripts/jquery-1.12.4.js"></script>
I think I did properly, but OnBegin is not firing still.
_Layout.cshtml:
<head>
<meta charset="utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<title>Test</title>
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/respond.min.js"></script>
<script src="~/Scripts/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js"></script>
<script src="~/Scripts/light-bootstrap-dashboard.js"></script>
<script src="~/Scripts/bootstrap-notify.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#RenderSection("scripts", required: false)
</head>
So the order of process is:
School View:
#model Test.Models.School
<div class="editorRow">
#using (Html.BeginCollectionItem("schools"))
{
#Html.ActionLink("New Employee", "NewEmployee", "Test", new
{
#class = "btn btn-info btn-md",
data_toggle = "modal",
data_target = "#modal-container-employee"
})
</div>
<div id="modal-container-employee" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>
Controller:
public ActionResult NewEmployee()
{
var newEmployee = new Employee();
return View(newEmployee);
}
Employee view:
#model Test.Models.Employee
#{
Layout = null;
}
#using (Ajax.BeginForm("PostEmployee", "Employee", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "closeModal"
}))
{
#Html.AntiForgeryToken()
<div id="test" class="">
<div class="modal-title title">
<input type="submit" id="submit" value="Save" /><span id="closes">x</span>
</div>
#Html.EditorFor(model => model.FullName)
</div>
}
<script>
function closeModal() {
$('#modal-container').modal('hide');
}
</script>
controller:
[HttpPost]
public ActionResult PostEmployee(Employee model)
{
try
{
var newEmployee = new Employee
{
FullName = model.FullName
};
db.Employees.Add(newEmployee);
db.SaveChanges();
return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = "error", errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
As a result, "success" Json is returned, but ajax is not catching it, it directly goes to the other page where it shows JSON array {"status":"success"}.
Can anyone find the problem?

passing datetime value from the view to controller using ajax call

I am using timepicki (one of the jquery timepickers) to pass DateTime value in the view to the controller, especially to the ActionResult Create method. I have tested under Sources tab using F12 for ajax call written in javascript in the view, and in fact, the value is successfully stored in the variable inside of the function, but doesn't seem to be passing its value to the controller. Can you guys help me why it is not passing its value to the controller? Any help is appreciated.
View:
#model test.Models.Employee
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.MondayId, "Monday: ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
Start: <input type="text" name="timepicker" class="time_element" id="monStart"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="submit" onclick=""/>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/timepicki.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/timepicki.css")" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function(){
$(".time_element").timepicki();
});
</script>
<script type="text/javascript">
$("#submit").click(function () {
var monStart = $('#monStart').val();
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
})
});
</script>
}
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee, DateTime? monStart)
{
//codes
}
You are just missing the AntiForgeryToken on your ajax call. So your call:
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart},
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
Should be:
var myToken = $('[name=__RequestVerificationToken]').val();
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart, __RequestVerificationToken : myToken },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});

Uploadify in MVC3 does not work

Can't get this to do anything. When I click 'Upload File' absolutely nothing happens as well as I don't see any of the flash rendered to the screen. I believe this is somehow related to the jquery, but I am not sure. PLEASE HELP! If someone can mail me a simple VS2010 solution with uploadify working to infinitimods at gmail.com that actually works I'd appreciate even more! Thanks a bunch!
My Layout file:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link type="text/css" rel="Stylesheet" media="screen" href="/Scripts/uploadify/uploadify.css" />
<script type="text/javascript" src="/Scripts/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript" src="/Scripts/uploadify/jquery-1.4.2.min.js"></script>
</head>
<body>
#RenderBody()
</body>
</html>
My index file:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<script type="text/javascript">
$(document).ready(function () {
$("#file_upload").uploadify({
'uploader': '~/Scripts/uploadify/uploadify.swf',
'cancelImg': '~/Scripts/uploadify/images/cancel.png',
'buttonText': 'Upload foto',
'script': '/Home/UploadFiles',
'folder': '/Content/upload',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'scriptData': { 'thisGuid': $("input#Id").val() },
'multi': false,
'auto': true,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$("#btnSave").button().click(function (event) {
$('#file_upload').uploadifyUpload();
});
});
</script>
<input id="file_upload" type="file" />
<input type="button" id="btnSave" value="Upload file" />
<input id="Id" name="Id" type="hidden" value="5168e-yada-yada" />
}
My controller:
public class HomeController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Index()
{
return View("Index");
}
/// <summary>
///
/// </summary>
/// <param name="fileData"></param>
/// <param name="form"></param>
/// <returns></returns>
[HttpPost]
public string UploadFile(HttpPostedFileBase fileData, FormCollection form)
{
return "ok";
}
}
Uploadify requires jQuery. This means that you need to include the jQuery script before the uploadify script. If you had looked in your javascript debugging console you would have seen this error.
So, the layout:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Scripts/uploadify/uploadify.css")" type="text/css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/swfobject.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery-1.4.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/uploadify/jquery.uploadify.v2.1.4.min.js")"></script>
</head>
<body>
#RenderBody()
</body>
</html>
The controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData, string thisGuid)
{
if (fileData != null && fileData.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var file = Path.Combine(appData, Path.GetFileName(fileData.FileName));
fileData.SaveAs(file);
}
return Json(new { status = true });
}
}
and the view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': false,
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
$('form').submit(function () {
$('#file_upload').uploadifySettings('scriptData', { thisGuid: $('#id').val() });
$('#file_upload').uploadifyUpload();
return false;
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
<input type="submit" value="Upload file" />
}
And if you want to kick the uploading process when the user selects a photo you could get rid of the form and the submit button and set the auto property to true:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/uploadify/uploadify.swf")',
'cancelImg': '#Url.Content("~/Scripts/uploadify/images/cancel.png")',
'buttonText': 'Select photo',
'script': $('form').attr('action'),
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png; *.txt;',
'multi': false,
'auto': true,
'scriptData': { thisGuid: $('#id').val() },
'onError': function (event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}
});
});
</script>
<h2>Index</h2>
<input id="id" name="id" type="hidden" value="5168e-yada-yada" />
<input id="file_upload" type="file" name="fileData" />
Also don't forget to checkout the uploadify documentation to better understand what the different options are used for and also you can see some examples.
You need to work around a bug with asp.net and flash.
This article helped me once: Working around flash cookie bug
Maybe this is a better solution: jquery file upload

Resources