I have successfully designed and implemented Google reCaptcha Version 2 but now my Manager wants that to be of version 1 with numbers to be entered and validated. Is there a way to switch from later to former i.e.- from 2 to 1. I am using following library for reCaptcha:
<script src='https://www.google.com/recaptcha/api.js'></script>
Update..
To implement Captcha inside form i am using following HTML..
<form class="contact_form" action="#" method="post" name="contact_form">
<div class="frm_row">
<label id="lblmsg" />
<div class="clear">
</div>
</div>
<div class="g-recaptcha" data-sitekey="6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></div>
<div class="login-b">
<span class="button-l">
<input type="button" id="Captcha" name="Submit" value="Submit" />
</span>
<div class="clear"> </div>
</div>
</form>
As i need to get the Captcha inside the above form to Validate and get the response on button click but as now i am using <script src="http://www.google.com/recaptcha/api/challenge?k=6Lduiw8TAAAAAOZRYAWFUHgFw9_ny5K4-Ti94cY9"></script> , so not getting the Captcha inside the form ..Please help me to get that ..Also here is the Jquery Ajax code to send the request on Server side code..
$(document).ready(function () {
alert("hii1");
$('#Captcha').click(function () {
alert("Hii2");
if ($("#g-recaptcha-response").val()) {
alert("Hii3");
var responseValue = $("#g-recaptcha-response").val();
alert(responseValue);
$.ajax({
type: 'POST',
url: 'http://localhost:64132/ValidateCaptcha',
data: JSON.stringify({ "CaptchaResponse": responseValue }),
contentType: "application/json; charset=utf-8",
dataType: 'json', // Set response datatype as JSON
success: function (data) {
console.log(data);
if (data = true) {
$("#lblmsg").text("Validation Success!!");
} else {
$("#lblmsg").text("Oops!! Validation Failed!! Please Try Again");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
}
});
}
});
});
Please help me ..Thanks..
You have to verify the reCaptcha at "http://www.google.com/recaptcha/api/verify" on Server side.
The parameters of this are:
privatekey: Your Private Key
remoteip: User's IP Address
challenge: Value of input[name=recaptcha_response_field]
response: Value of input[name=recaptcha_challenge_field]
Therefore, you have to post them on your server-side method like this:
cshtml file:
var recaptchaResponseField=$("input[name=recaptcha_response_field]").val();
var recaptchaChallengeField=$("input[name=recaptcha_challenge_field]").val();
// ajax block
$.ajax({
url: '/api/VerifyReCaptcha/', // your Server-side method
type: 'POST',
data: {
ipAddress: '#Request.ServerVariables["REMOTE_ADDR"]',
challengeField: recaptchaChallengeField,
responseField: recaptchaResponseField
},
dataType: 'text',
success: function (data) {
// Do something
},
Since you are using .NET so an example of C# code is as follows:
cs file:
using System.Net;
using System.Collections.Specialized;
[HttpPost]
public bool VerifyReCaptcha(string ipAddress, string challengeField, string responseField)
{
string result = "";
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://www.google.com/recaptcha/api/verify", new NameValueCollection()
{
{ "privatekey", "{Your private key}" },
{ "remoteip", ipAddress },
{ "challenge", challengeField },
{ "response", responseField },
});
result = System.Text.Encoding.UTF8.GetString(response);
}
return result.StartsWith("true");
}
Related
I am facing issue with Axios, if I post simple form data it is all working fine. But if I add file input and configures Axios to post files as well, then Server returns error in response "405 - Method not allowed".
Axios configuration which works with simple data:
const httpClient = axios.create({
baseURL: document.location.origin,
headers: { 'X-Requested-With': 'XHR'}
});
Axios configuration which is NOT working in case of post files
const httpClient = axios.create({
baseURL: document.location.origin,
headers: { 'X-Requested-With': 'XHR', 'Content-Type': 'multipart/form-data'}
});
Razor Page Post Method:
public async Task<IActionResult> OnPostAsync()
{
//await Mediator.Send(Command);
return RedirectToPageJsonResult("./");
}
Cshtml snippet:
<form method="post" data-os-trigger="xhr" class="form-horizontal form-groups-bordered" enctype="multipart/form-data">
<input type="text" asp-for="#Model.Command.Status"/>
<input type="file" asp-for="#Model.Command.FileField" />
<div class="row button">
<div class="col-md-12 text-center">
<button id="btnSave" type="submit" class="btn btn-warning">Save</button>
<button type="reset" class="btn btn-light">Clear</button>
</div>
</div>
</form>
JS event which post data:
let formData = new FormData($this[0]);
let formParams = new URLSearchParams(formData);
httpClient.post($this[0].action, formParams)
.then(function (response) {
})
.catch(function (error) {
});
I found the issue with my code. If you see in my code there are two lines to get params of Form:
let formData = new FormData($this[0]);
let formParams = new URLSearchParams(formData);
I was passing formParams as argument in AXIOS call, which was causing the issue. Instead I had to use formData parameter. Once I did that, it was all working fine for me.
Here is a simple working demo you could follow:
Model
public class Command
{
public string Status { get; set; }
public IFormFile FileField { get; set; }
}
View
#page
#model IndexModel
<form asp-page="Index" method="post" data-os-trigger="xhr" class="form-horizontal form-groups-bordered" enctype="multipart/form-data">
<input type="text" asp-for="#Model.Command.Status"/>
<input type="file" asp-for="#Model.Command.FileField" />
<button id="btnSave" type="button" onclick="PostFile()" class="btn btn-warning">Save</button>
</form>
#section Scripts
{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function PostFile()
{
const httpClient = axios.create({
baseURL: document.location.origin,
headers: {
'X-Requested-With': 'XHR',
'Content-Type': 'multipart/form-data',
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
}
});
let formData = new FormData();
formData.append("FileField", $("#Command_FileField")[0].files[0]);
formData.append("Status", $("#Command_Status").val());
httpClient.post($('form').attr('action'), formData)
.then(function (response) {
})
.catch(function (error) {
});
}
</script>
}
PageModel
public class IndexModel : PageModel
{
[BindProperty]
public Command Command { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync()
{
//do your stuff...
}
}
I have a form with file upload. I am using vue, axios and laravel 7 at the moment.
My form is as given below:
<form v-on:submit.prevent="createTask" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title" v-model="task.title" />
<label for="content">Content</label>
<textarea v-model="task.content" class="form-control" id="content" name="content" rows="4" ></textarea>
<button type="submit" class="btn btn-sm btn-primary
pull-right" style="margin:10px; padding:5 15 5 15; background-color:#4267b2">Save Task</button>
<span>
<button #click="removeImage" class="btn btn-sm btn-outline-danger" style="margin:10px; padding:5 15 5 15; ">Remove File</button>
</span>
<input type="file" id="image" name="image" />
</div>
</form>
Axios submission
createTask() {
console.log(document.getElementById('image').files[0])
axios({
headers: { 'Content-Type': 'multipart/form-data' },
method: 'post',
url: '/api/tasks',
data: {
task_id : this.task.id,
title : this.task.title,
content : this.task.content,
created_by : this.$userId,
image : document.getElementById('image').files[0],
}
})
.then(res => {
// check if the request is successful
this.$emit("task-created");
this.task = {}
})
.catch(function (error){
console.log(error)
});
}
My controller code
public function store(Request $request)
{
$task = $request->isMethod('put') ? Task::findOrFail($request->task_id) : New Task;
$task->id = $request->input('task_id');
$task->title = $request->input('title');
$task->content = $request->input('content');
$task->views = $request->input('views');
$task->created_by = $request->input('created_by');
$task->image = $request->image->store('images');
//$task->image = $request->file('image')->store('images');
if($task->save()) {
return new TaskResource($task);
}
}
The request payload
{task_id: "", title: "test", content: "test content", created_by: "1", image: {}}
We can see the image attribute is empty
The response error message
"Call to a member function store() on null"
The output of console.log(document.getElementById('image').files[0])
File {name: "test.jpg", lastModified: 1590920737890, lastModifiedDate: Sun May 31 2020 11:25:37 GMT+0100 (British Summer Time), webkitRelativePath: "", size: 436632, …}
lastModified: 1590920737890
lastModifiedDate: Sun May 31 2020 11:25:37 GMT+0100 (British Summer Time) {}
name: "test.jpg"
size: 436632
type: "image/jpeg"
webkitRelativePath: ""
proto: File
I solved this problem by changing the axios post request as follows. I used FormData to append and send data to server
createTask() {
let data = new FormData;
data.append('image', document.getElementById('image').files[0]);
data.append('task_id', this.task.id);
data.append('title', this.task.title);
data.append('content', this.task.content);
data.append('created_by', this.$userId);
axios({
headers: { 'Content-Type': 'multipart/form-data' },
method: 'post',
url: '/api/tasks',
data: data
})
.then(res => {
// check if the request is successful
this.$emit("task-created");
this.image = '';
this.task = {}
})
.catch(function (error){
console.log(error)
});
}
Assuming the image column has the right structure, you could try with somenthing like this:
<?php
public function store(Request $request)
{
$task = $request->isMethod('put') ? Task::findOrFail($request->task_id) : New Task;
$task->id = $request->input('task_id');
$task->title = $request->input('title');
$task->content = $request->input('content');
$task->views = $request->input('views');
$task->created_by = $request->input('created_by');
$task->image = $request->hasFile('images')
? $request->file('images')
: null;
if($task->save()) {
return new TaskResource($task);
}
}
laravel 5.4 upload image read here for more information
I have a problem with my controller - it doesn't return a view. I am sending some data to the same controller, creating a new object with this data and I would like to send this object to the Create view but for some kind of reason I am staying on the same page.
View name: Create.cshtml
Controller name: ReservationController
Here is my controller action:
public IActionResult Create(int selectedTime, string selectedDate, int selectedRoomId)
{
TimeSpan time = TimeSpan.Parse($"{selectedTime}:00:00");
DateTime date = DateTime.ParseExact(selectedDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
DateTime combine = date + time;
Reservation reservation = new Reservation();
reservation.RoomId = selectedRoomId;
reservation.ReservationTime = combine;
return View(reservation);
}
And my view:
#model Escape.Models.Reservation
#{
ViewBag.Title = "title";
}
<h2>My create reservation view</h2>
This is the original view I am coming from:
#using Escape.Controllers
#model Escape.Models.Room
#{
ViewData["Title"] = "Details";
}
<h4 class="title">Booking for room: #Model.Name</h4>
<div>
<p>#Model.Description</p>
<a class="btn btn-link" asp-action="Index">Back to all rooms</a>
<hr />
</div>
<div>
<input id="datepicker" type="text" name="datepicker"
onchange="onDateChange(#Model.Id)" />
</div>
<div>
<div id="displayTimes"></div>
<a id="btn-create" class="btn btn-sm"></a>
</div>
#section Scripts {
<script>
var dateToday = new Date();
$(function () {
$("#datepicker").datepicker({
minDate: dateToday
});
});
</script>
}
Ajax function on my btn-create:
function onButtonClick(val, date, room) {
var btnBack = document.getElementById("btn-create");
btnBack.innerHTML = "Create reservation";
$(btnBack).addClass('btn-outline-primary');
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json"
});
});
}
If the link <a id="btn-create" class="btn btn-sm"></a> is supposed to make a call to the Create method of the ReservationController, then it is incomplete, and this is what you would need to change it to:
<a asp-controller="Reservation"
asp-action="Create"
id="btn-create" class="btn btn-sm">Create</a>
Update:
Your click handler does seem to send a request to the Controller, but nothing happens after that request, and the response (which contains the HTML from the View) is discarded.
Since you want to show the HTML, maybe you shouldn't even be using AJAX, and use my original answer above instead.
If for some reason you need the AJAX, then you need to create a success handler that displays the HTML:
btnBack.addEventListener("click",
function () {
$.ajax({
type: "GET",
data: { selectedTime: val, selectedDate: date, selectedRoomId: room },
url: "/Reservation/Create",
contentType: "application/json",
dataType: "json",
success: function (data) {
// ... put processing here
}
});
}
);
I am using asp.net MVC 5 to do a simple single file upload using the HTML element.I make an AJAX post request.The form has other fileds in addition to the file element.I tried diffrent methods available on the internet ,but nothing seems to be working.Is this really possible using the element?Using a jQuery plugin is my last option.I like to make things simple in my application
my HTML
#using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { id = "form-person-edit-modal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="row">
<div class="small-4 columns">
#Html.GenericInputFor(m => m.Name, Helpers.HtmlInputType.Text, new { id = "input-name" })
</div>
<div class="small-4 columns">
#Html.GenericInputFor(m => m.Description, Helpers.HtmlInputType.TextArea, new { id = "input-description" })
</div>
<div class="small-4 columns">
<label>Choose File</label>
<input type="file" name="attachment" id="attachment" />
</div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="submit" id="image-submit" value="Save"/>
</div>
</div>
}
-- C# ViewModel
public class Person
{
Public string Name{get;set;}
Public string Description{get;set;}
public HttpPostedFileBase Attachment { get; set; }
}
-- Jquery Ajax Post:
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (data.Success) {
success(data, textStatus, jqXHR);
} else {
if (error) {
error();
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (error)
error();
}
});
-- Javacsript where I try to get the file content,before passing that data to the above method
function getData(){
return {
Name:$('#input-name').val(),
Description:$('#input-description').val(),
Attachment:$('#form-ticket-edit-modal').get(0).files[0]
};
}
But the Attachment on the controller is null.I tried this as below,but doesnt seem to be working
[HttpPost]
public ActionResult Edit(ViewPerson person,HttpPostedFileBase attachment)
{
}
Is this still possible,or should I use a jQuery plugin(If so,which one do you recommend?)
I have used your code to show how to append image file,Please use Formdata() method to append your data and File and send through ajax.
Try Changing as per your requirement.
$("#SubmitButtonID").on("click",function(){
var mydata=new Formdata();
mydata.append("Name",$("#name").val());
mydata.append("Image",Image.files[0]);
alert(mydata);
$.ajax({
url: "#url.Action("ActionMethodName","ControllerName")",
type: 'POST',
contentType:false,
processData;false,
data: mydata,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (data.Success) {
success(data, textStatus, jqXHR);
} else {
if (error) {
error();
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (error)
error();
}
});
});
<input type="file" id="Image" name="file">
<input type="button" id="SubmitButtonID" value="submit"/>
I am new in knockoutjs, i am trying to bind the view, but cannot. Data from server is fetching fine, ajax is working fine, but not binding issue.
Here is my js code:
var UserViewModel = function () {
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("0");
self.FirstName = ko.observable("");
self.LastName = ko.observable("");
//The Object which stored data entered in the observables
var UserData = {
Id: self.Id || 0,
FirstName: self.FirstName || '',
LastName: self.LastName || ''
};
//Declare an ObservableArray for Storing the JSON Response
self.Users = ko.observableArray([]);
GetUser(12); //This is server side method.
function GetUser(userId) {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/api/Users/" + userId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert("success");
UserData = response.data.UserData;
alert(UserData.FirstName); //This is showing me correct name.
self.Users(response.data.UserData); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status);
}
});
//Ends Here
}
}
ko.applyBindings(new UserViewModel());
Here is my view:
<form class="form-horizontal" data-bind="with: UserData">
<div class="row">
<div class="control-group">
<label class="control-label">First Name</label>
<label class="control-label" data-bind="text: FirstName"></label>
</div>
</div>
<div class="row">
<div class="control-group">
<label class="control-label">Last Name</label>
<input type="text" placeholder="Last Name" data-bind="value: LastName">
</div>
</div>
Your problem is that you are trying to two-way data-bind against a non-observable property, so when you update it it isn't notifying the UI. Make your user an observable and set it to an instance of an object or create a model to derive your properties from.
function userModel(user) {
var self = this;
self.Id = ko.observable(user.Id);
self.FirstName = ko.observable(user.FirstName);
self.LastName = ko.observable(user.LastName);
}
var viewModel = function () {
var self = this;
//The Object which stored data entered in the observables
var UserData = ko.observable();
GetUser(12);
function GetUser(userId) {
//Ajax Call Get All Employee Records
$.ajax({
type: "GET",
url: "/api/Users/" + userId,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert("success");
UserData(new userModel(response.data.UserData));
alert(UserData().FirstName()); //This is showing me correct name.
self.Users.push(UserData()); //Put the response in ObservableArray
},
error: function (error) {
alert(error.status);
}
});
}
}
ko.applyBindings(new viewModel());
Here, take from the following fiddle ::
http://jsfiddle.net/9ZCBw/
where you have a container model which owns the collection of users and has the function (ajax stripped for usability under fiddle)
function ViewModel () {
var self = this;
self.Users = ko.observableArray();
self.GetUser = function (userId) {
var UserData = {
Id: userId,
FirstName: 'Bob',
LastName: 'Ross'
};
self.Users.push(new UserModel(UserData));
}
}
Here, you have instances of Users which can then be bound to you model...as also shown.