Ajax doesnt hit controller action - html

lam trying to save replycomments to the database
here is my html form,
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</form>
</div>
</div>
and here is my homecontroller action code
public JsonResult ReplyComment(string replycomment, int articleid,int commentid)
{
var UserId = Session["UserId"];
if (replycomment == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
db.ReplyComments.Add(new ReplyComment
{ UserId = Convert.ToInt32(UserId), ArticleId = articleid, CommentId=commentid, Paragraph = replycomment, Date = DateTime.Now });
db.SaveChanges();
return Json(false, JsonRequestBehavior.AllowGet);
}
and my ajax code is here
<script type="text/javascript">
$(document).ready(function () {
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
$.ajax({
cache: false,
url: '#Url.Action("ReplyComment","Home")',
contentType: "application/json; charset=utf-8",
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("İşlemOkey");
}
});
});
})
l cant call the Replycomment action with this code

I have tested this code and it will work for you. since am posting via ajax, i have removed the form tags from the body of the html.
For backend(php), I just test it by sending variables r_comment and r_commentid and it works fine. it should work with your backend code now. Give me a shout if it works for you...........
<html>
<head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
var articleid = '20';
/* lets test with data
var r_comment ='my comment';
var r_commentid = '20';
*/
$('#loader').fadeIn(400).html('Data is being processed');
// assuming that you want query result by posting a variable
var datasend = "r_comment="+ r_comment + "&r_commentid=" + r_commentid + "&articleid=" + articleid;
$.ajax({
type:'POST',
url:'smoke1.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//display image loader or text to alert the use that content is being processed
$('#loader').hide();
// and display result
alert("İşlemOkey");
$('#result').fadeIn('slow').prepend(msg);
}
});
})
});
</script>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
replytext: <textarea id="replytext" name="replytext" class="form-control" rows="3"></textarea>
</div>
<div class="form-group">
astar: <input type="text" class="astar">
</div>
<div id="loader"></div>
<div id="result"></div>
<br>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
</body></html>
my testing backend in php(Try it with yoour backend code)
smoke1.php
<?php
echo "ok";
echo $_POST['r_comment'];
echo $_POST['r_commentid'];
echo $_POST['articleid'];
?>

Related

How to add a button to remove user

I currently have this code that displays users on a team and when you click on the name of a user that is on the list it passes the name that you click to a function which removes them from the team. Instead I would like a button to be next to the name and when you click the button it removes the person that the button is next to. How would I go about doing this
$(document).ready(function() {
$("#your_teams234").change(function() {
var team = $("#your_teams234").val();
$.ajax({
url: 'functions.php',
method: 'post',
data: 'members=' + team
}).done(function(requests) {
console.log(requests);
requests = JSON.parse(requests);
$('#teammates').empty();
if (requests.length != 0) {
$("#teamContainer").css("display", "block");
requests.forEach(function(request) {
$('#teammates').append('<p class="myDivs">' + request.email + '</p>')
})
}
if (requests.length == 0) {
$('#teammates').append(`<p> No teammates </p>`)
}
$('.myDivs').click(function() {
$var1 = $(this).text();
$.ajax({
url: 'functions.php',
type: 'post',
data: {
"callFunc1": $var1,
"teamName": team
},
success: function(response) {
console.log(response);
}
});
});
})
})
})
Here is the html code for my team container
<div id="teamContainer" style="display: none;">
<p style="font-weight: bold; font-size:18px left">Current Team Members (click name to remove)</p>
<div id='teammates'>
</div>
<hr style="margin-left: 350px; margin-right: 350px">
</div>
</div>
First off, you really should be passing ID's rather than names in order to access a user. What if you have 2 users with the same name, or apostrophes/odd characters - or even the lack of a name? At any rate, you didn't show your HTML but here's how it could work.
$('.remover').click(function() {
let $user = $(this).closest('.user-container').find('.myDivs');
let $userid = $user.data('id');
let $username = $user.text();
console.log(`remove user ${$username}, id ${$userid}`);
$(this).closest('.user-container').remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='user-container'>
<span class='myDivs' data-id='1'>John Smith</span>
<button class='remover'>Remove user</button>
</div>
<div class='user-container'>
<span class='myDivs' data-id='2'>Susan Sarandon</span>
<button class='remover'>Remove user</button>
</div>
<div class='user-container'>
<span class='myDivs' data-id='3'>Bill Nye</span>
<button class='remover'>Remove user</button>
</div>

Laravel- Auto fill input after selecting value from dropdown

how to do the auto fill after select the dropdown list. I'm not really good in js or ajax.
When user select doc_no then both rev_no and title field must be filled up. Thanks!
View
<div class="form-group">
{!! Form::label('text', 'Doc No', ['class' => 'col-lg-3 control-label']) !!}
<div class="col-lg-10">
<select name="docNo" id="docNo" class="form-control" style="width:250px">
#foreach ($soplists as $soplist)
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
#endforeach
</select>
</div>
</div>
<input type="hidden" name="carType" value="Internal Audit" class="form-control">
<div class="form-group">
{!! Form::label('text', "Rev No", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-5">
<input type="text" class="form-control" id="rev" />
</div>
</div>
<div class="form-group">
{!! Form::label('text', "Title", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-10">
<input type="text" class="form-control" id="title" />
</div>
<script>
$('#docNo').change(function() {
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
</script>
Controller
---php
public function getDetails($id = 0)
{
$data = sopList::where('doc_no', $id)->first();
echo json_encode($data);
exit;
}
Route
'Route::get('get/details/{id}', 'internalAuditController#getDetails')->name('getDetails');'
Database sop_list table image link
https://ibb.co/SwkJhLc
Dropdown and input image
https://ibb.co/0VN3Z2y
Network tab
https://ibb.co/56w5BLD
Add a route in web.php file:
Route::get('get/details/{id}', 'YourController#getDetails')->name('getDetails');
Controller Function:
public function getDetails($id = 0)
{
$data = sopList::where('doc_no',$id)->first();
return response()->json($data);
}
And in view the script:
$('#docNo').change(function(){
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response){
if(response != null){
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
Make sure to add the id rev and title to the rev and title input fields respectively.
you have to make a rout that returns what you need
for example
/**
* #return \Illuminate\Http\JsonResponse
*/
public function getCategories()
{
$category = Category::where('_id', request()->get('_id'))
->select(['name', '_id'])->first();
return response()->json($category);
}
then call it on change of your select box with ajax and show it every where you want
like this example:
$("#docNo").change(function () {
$.ajax({
url: "{{ route('getCategories') }}",
type: 'POST',
data: {
_token: "{{ csrf_token() }}",
_id: $(this).val()
},
success: function (data) {
var newOption = '';
$.each(data, function (k, category) {
newOption += '<option value="' + category.id + '">' + category.name + '</option>';
});
$('#parent').append(newOption);
},
error: function (error) {
console.log(error);
}
});
});
you can add onChange method on your docNo and then call do ajax call to get the rev_no and title and update the content via document.getElementById()

Why input value is NULL when using Ajax?(ASP.NET CORE)

I do not have access to input values when using Ajax in View(MVC) but I have access to input values when not use Ajax. actually values is empty when use Ajax
When I use Ajax:
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<input type="reset" value="send" id="ajax-button" class="btn btn-success btn-sm waves-effect waves-light submit-btn" />
</form>
Script:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
var data = $('#Form1').serialize();
$('#ajax-button').click(function () {
debugger
$.ajax({
type: "POST",
data: data,
url: url,
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I added tag helpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, SmsWebClient
#using Microsoft.AspNetCore.Razor.TagHelpers;
Value is null before enter to ajax ,image:
Please Move the
var data = $('#Form1').serialize();
to below
$('#ajax-button').click(function () {
In fact, your code should be:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
$('#ajax-button').click(function () {
var data = $('#Form1').serialize();
debugger
$.ajax({
type: "POST",
data: data,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
In your code data set when docuement loaded and for this reason the value
is null
You must write like this
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<div class="form-group">
<button id="ajax-button">Submit</button>
</div>
</form>
And This ViewModel
public class RegisterVm
{
public string Name { get; set; }
public string Number { get; set; }
}
And finally this is the Ajax code
#section Scripts{
<script>
$(document).ready(function () {
var url = $('#Form1').attr("action");
var model = $('#Form1').serialize();
var token = $('input[name=__RequestVerificationToken]').val();
model.__RequestVerificationToken = token;
$('#ajax-button').click(function () {
$.ajax({
type: $('#Form1').attr("method"),
data: model,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
}
Your data are set when docuement loaded, it will not pass the value which you enter.
For a working demo, try code below:
<script>
$(document).ready(function () {
$('#ajax-button').click(function () {
var url = '#Url.Action("Register", "Home")';
var data = new FormData();
data.append('Name', $('#Name').val());
data.append('Number', $('#Number').val());
$.ajax({
type: "POST",
data: data,
url: url,
processData: false,
contentType: false,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>

How can I pass controller scope to a partial html file?

This is my main HTML file.
<div ng-controller="filterController">
<div class="quick-view" id="quickview" data-toggle="modal" data-target="#modal-bar"
ng-click="quickView(quickview)"><i class="fa fa-eye">
</i><span>Quick View</span></div>
</div>
This is my controller.js file
angular.module('myApp',[]).controller('filterController', function($scope) {
$scope.quickView = function quickView(id){
$.ajax({
type: 'GET',
url: 'assets/external/_modal.html',
data: id,
success: function (data) {
// Create HTML element with loaded data
$('body').append(data);
console.log('body append');
},
error:function(jqXHR,textStatus,exception){console.log('Exception:'+exception);}
});
}
$scope.venue = "India";
}
This is _modal.html
<div ng-controller="filterController">
<p>Hi. I live in {{venue}}</p>
</div>
How can I pass the controller scope to the external file _modal.html so that "I live in India" gets displayed instead of "I live in {{venue}}"?
Try angularjs way. Use uib modal. https://angular-ui.github.io/bootstrap
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope,$uibModal, $log, $document) {
$scope.animationsEnabled = true;
$scope.Venue = "India"; // declare venue
$scope.open = function (size, parentSelector) {
var parentElem = parentSelector ?
angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
appendTo: parentElem,
resolve: {
values: function () {
return $scope.Venue; //we are passing venue as values
}
}
});
modalInstance.result.then(function () {
$scope.msg = "Submitted";
$scope.suc = true;
}, function(error) {
$scope.msg = 'Cancelled';
$scope.suc = false;
});
};
});
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope,$uibModalInstance, values) { // inject that resolved values
$scope.Venue= values; // we are getting & initialize venue from values
$scope.ok = function () {
$uibModalInstance.close('ok');
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl" class="modal-demo">
<br>
<form name="form" novalidate>
Type your venue : <input type="text" style="width:200px" class="form-control" name="name" ng-model="Venue" required><br>
<button type="button" ng-disabled="form.$invalid" class="btn btn-default" ng-click="form.$valid && open()">See Venue</button>
</form><br>
<p ng-hide="!msg" class="alert" ng-class="{'alert-success':suc, 'alert-danger':!suc}">{{msg}}</p>
</div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">Your Details</h3>
</div>
<div class="modal-body" id="modal-body">
<p>The venue is <b>{{Venue }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">Submit</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
</body>
</html>

Connection Refused where I want to put my details

I am making a test app on MEAN stack and whenever I try to update information in my database regarding the fields, Google chrome throws Connection refused to the Url where I am posting the stuff.
Code for the controller:
(function() {
angular.module('TimeSuck')
.controller('EditProfileController',['Upload','$scope','$state', '$http', function(Upload, $scope, $state, $http) {
$scope.user = localStorage['Userdata'] || undefined
$scope.$watch(function(){
return $scope.file
},function(){
$scope.upload($scope.file);
});
$scope.upload = function(file) {
if(file){
Upload.upload({
url:'api/profile/editPhoto',
method: 'POST',
data: {userId: $scope.user._id},
file: file
}).progress(function(event){
console.log("Uploaded");
}).success(function(data){
}).error(function(error){
console.log(error);
})
}
};
$scope.updateUsername = function() {
var request = {
userId: $scope.user[0]._id,
username: $scope.username
}
$http.post('api/profile/updateUsername', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
})
}
$scope.updateBio = function() {
var request = {
userId: $scope.user[0]._id,
bio: $scope.bio
}
$http.post('api/profile/updateBio', request).success(function(){
console.log("success");
}).error(function(error){
console.log(error);
});
}
$scope.post = function() {
console.log("successfully Posted.");
}
and the code for the html is here:
<div class="jumbotron">
<div class="col-sm-8 col-sm-offset-2">
<div class="row"> <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
ngf-accept="'image/*'" >Select</div> </div>
<div class="row">
<input class="form-control" ng-model="username" ng-blur="updateUsername()">
</div>
<div class="row">
<textarea class="form-control" ng-model="Bio" ng-blur="updateBio()"> </textarea>
<button type="submit" ng-click="post()"> Post </button>
</div>
</div>
</div>