I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },
Related
I'm trying to get a value from ajax request into my controller. My js function shows desired value in alert but when I try to pass this value as data into the controller, the controller received null.
I'm not sure if this is an error with my app logic or a different problem. I would appreciate any feedback.
The form
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
The Javascript
<script>
function hex2rgb(hex) {
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{hex:hex,_token:_token},
success: function(response){ // What to do if we succeed
if(data == "success")
alert(response);
},
error: function(response){
alert('Error'+response);
}
})
}));
}
return null;
}
</script>
The Controller
public function multiStepStore(Request $request)
{
$input = $request->get('hex');
dd($input);
}
I think that you probles is in your token, the correct form to get a token for send in ajax is:
Blade
<form>
<input type="color" id="bgcolor" name="bgcolor">
<button onclick="hex2rgb()">CLick</button>
</form>
Javascript
<script>
function hex2rgb() { //remove the data you are receiving
var hex = document.getElementById("bgcolor").value;
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return alert(r.slice(1, 4).map(function (x) {
return parseInt(x, 16);
$.ajax({
url:"{{ route('niceActionController.multiStepStore') }}",
method:"POST",
data:{
_token: "{{ csrf_token() }}",
hex:hex,
},
success: function(response){ // What to do if we succeed
console.log(response);
},
error: function(response){
console.log('Error'+response);
}
})
}));
}
return null;
}
</script>
Controller
public function multiStepStore(Request $request)
{
dd($request->all());
}
Route
Route::post('/hex', 'Hexcontroller#multiStepStore')->name('niceActionController.multiStepStore');
to see the console.log you need to open your browser's inspector
I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?
Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})
I am trying to POST to this Spring REST service that I have set up which will accept a Review object. I can easily test this in Java as I can create an actual Review object and it will successfully create into the database. The issue is when I am trying to do it in Javascript I get a 415 Unsupported Media Type error. I know this has to do with how I am creating my Review object in Javascript but I am not sure what I am doing wrong.
index.js code snippet
function submitReview() {
var rating = $('#rating-review input:radio:checked').val();
var newReview = new Review(Number($('#id-review').val()), rating, $('#message-text').val());
console.log(newReview);
$.ajax({
type: "POST",
url: baseUrl + "/review",
data: newReview,
success: function (response) {
if (response == 'success')
alert("Successfully submitted review");
else
alert("Unsuccessful Review Submission");
}
});
}
function Review(carId, rating, review)
{
this.carId = carId;
this.rating = rating;
this.review = review;
}
ReviewRestService.java code snippet
#POST
#Path("/review")
#Consumes(MediaType.APPLICATION_JSON)
public String addReview(Review review) {
reviewService.addReview(review);
return review.getId();
}
I have tried changing my submitReview() to be...
function submitReview() {
var newReview = {
"carId": 123,
"rating": 2,
"review": "testing"
};
$.ajax({
type: "POST",
url: baseUrl + "/review",
data: newReview,
success: function (response) {
if (response == 'success')
alert("Successfully submitted review");
else
alert("Unsuccessful Review Submission");
}
});
}
as a test, but I still receive the same error. Not sure what I am doing incorrectly.
I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>
I need to access the data held in localstorage, server side but that's another story.
I have this button in my view:
<div style="float:right;">
<input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>
This JS function:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
dataType: 'json',
data: JsonLocalStorageObj,
contentType: "application/json; charset=utf-8",
beforeSend: function () { alert('sending') },
success: function (result) {
alert(result.Result);
localStorage.clear();
}
});
};
And this test controller method:
[HttpPost]
[WebMethod]
public ActionResult Test(string JsonLocalStorageObj)
{
string x = JsonLocalStorageObj;
//deserialize here
return RedirectToAction("Index");
}
When I run JSON.stringify(localStorage); in chrome dev tools, I see data as expected, however when I debug my controller JsonLocalStorageObj is always null. As a test I used the test array that is commented out and set the parameter on the controller to accept a List<string> and this came through populated.
Whats the problem with JSON.stringify(localStorage); being passed through?
You haven't specified the parameter name of your action (JsonLocalStorageObj) and your content and dataType were wrong too.
Try change your javascript code to this:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
data: { JsonLocalStorageObj: JsonLocalStorageObj },
success: function (result) {
alert(result);
}
});
}