I'm trying to close a modal div with AJAX search results, but nothing works.
I have tested several solutions on SO but nothing works?!
This is the code I have right now:
<form action="/search" method="get">
<input type="hidden" name="qt" value="main">
<div class="searchBox" id="search">
<input type="text" name="q" id="find" placeholder="Search here..." class="mainSearchField" />
<div class="searchBoxResults" id="search_items"></div>
</div>
</form>
<script>
$(document).ready(function() {
$( "#find" ).keyup(function(){
fetch();
});
});
function fetch() {
var val = document.getElementById("find").value;
$.ajax({
type: 'post',
url: '/include/functions/searchFetch.php',
data: {
q:val
},
success: function (response){
document.getElementById("search_items").innerHTML = response;
}
});
}
</script>
UPDATE
This is what I have tried to add, to the above:
window.onclick = function(event) {
if (event.target.id != "search_items") {
$("search_items").hide();
}
}
Related
I have a single form which has two button one to upload image using ajax call & other is main submit button which saves all the data.
I am still very new to asp.net core and trying different thing to learn asp.net core with razor page.
I read lot of article about multiple form submit but most of then where using two form with submit button for each.
My issue is when i hit the submit button it fails to find the handler method, after full days troubleshoot nothing worked and last few article point to error/failure to antiforgery, i not sure how to implement it in below code as i tried few but they gave error may be article where old referencing core 2.2 etc example1 example2
I am not sure about the what exactly is causing the issue any help would be appreciate.
I am trying to upload Image using Ajax method in asp.net core Razor pages, I am main form in will all input fields are kept and with the form for Fileupload i am also added addition button which is for file upload using Ajax, When i hit the
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
i want it to call OnPostUploadImage method in pageModel file but it alway goes to default OnPost method. when i rename the OnPost to OnPost2 nothing happend..
How can i call OnPostUploadImage() on button btnUploadImage click event.
When i hit click btnUploadImage it generates following error on browser console
Error in FF
XML Parsing Error: no root element found Location:
https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage
Line Number 1, Column 1:
Error in Chrome
jquery.min.js:2 POST
https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage
400 (Bad Request)
event though path looks fine but it cant find it as per error message
#page
#model BookListRazor.Pages.Admin.News.NewsCreateModel
#{
ViewData["Title"] = "News Create";
Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
}
<div class="border container" style="padding:30px;">
<form method="post" enctype="multipart/form-data">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<input hidden asp-for="News.NewsImage" />
<input id="fileName" hidden value="" />
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsHeading"></label>
</div>
<div class="col-10">
<input asp-for="News.NewsHeading" class="form-control" />
</div>
<span asp-validation-for="News.NewsHeading" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsImage"></label>
</div>
<div class="col-10">
#*<input asp-for="News.NewsImage" type="file" class="form-control" id="NewsImage">*#
#*Photo property type is IFormFile, so ASP.NET Core automatically creates a FileUpload control *#
<div class="custom-file">
<input asp-for="NewsImageForUpload" class="custom-file-input form-control">
<label class="custom-file-label">Click here to change photo</label>
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
</div>
</div>
<span id="imageStatus" class="text-danger"></span>
<span asp-validation-for="NewsImageForUpload" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<input id="btnSave" type="submit" value="Create" class="btn btn-primary form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSave").addClass("disable-button");
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
$("#fileName").val(fileName);
$("#btnSave").removeClass("disable-button");
});
if ($("#fileName").val() == "") {
//alert("Select Image...");;
}
});
</script>
</div>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "OnPostUploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
.cs file CODE
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return Page();
}
else
{
return Page();
}
}
public IActionResult OnPostUploadImage()
{
//Some code here
}
Verify that you add the following code to the ConfigureServices method of startup.cs:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
If you want to enter the OnPostUploadImage method, the url of the Ajax request needs to be changed to #Url.Page("", "UploadImage") without adding OnPost.
And the Ajax request should send the anti-forgery token in request header to the server.
Change your ajax as follow:
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "UploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
You can refer to this for more details.
Script:
$(document).ready(function () {
$('#btnNext').click(function (e) {
e.preventDefault();
});
var options = {
beforeSend: function () {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');
},
success: function () {
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function (response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function () {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#form1").ajaxForm(options);
});
HTML:
<form id="form1" method="post" enctype="multipart/form-data">
<div>
<input type="file" size="60" name="myfile" />
<input type="submit" value="Ajax File Upload" />
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div>
</div>
<br />
<div id="message"></div>
</div>
I was tested with Webform (C#). It worked. But, Dotnetnuke not working. (Postback and nothing is changed). Have a different way for Dotnetnuke to get percentage of progress of page load?
-- Thank for reading--
Try removing the <form> tag around your module because DNN is already writing a form tag to the page surrounding the theme and modules. You can change the last line in your jquery logic to reference the form already loaded by DNN.
$("form:first").ajaxForm(options);
I am using chosen.js and jquery validation pluging but below code is not working,I am not get any error.please help me how to validate this using jquery validation pluging.
<form:form method="post" id="clienteditform" action="updateClient.htm" name="clienteditform" cssClass="form-horizontal" modelAttribute="eReg" role="form">
<div class="form-group">
<label class="col-sm-2 control-label">Country</label>
<div class="col-sm-10">
<form:select cssClass="chosen-select" cssStyle="width:450px;" id="country" name="country" path="cusDTO.client.cl_country_id">
<form:option value="0">Select country</form:option>
<form:options items="${countryList}" itemValue="country_id" itemLabel="country_name"/>
</form:select>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".chosen-select").chosen();
$.validator.addMethod("validateCountry", function(value, element) {
return this.optional(element) || value != '0' ;
}, " Please select country");
$("#clienteditform").validate({
rules: {
"cusDTO.client.cl_country_id":{
validateCountry : true
}
}
});
});
$(document).ready(function(){
$(".chosen-select").chosen();
$.validator.addMethod("validateCountry", function(value, element) {
return this.optional(element) || value != '0' ;
}, " Please select country");
$("#clienteditform").validate({
rules: {
"cusDTO.client.cl_country_id":{
validateCountry : true
}
}
});
$('#country').rules('add', {validateCountry:true});
});
hope it solve your problem
I am a little new to JQuery. let's suppose that we have this jquery function :
var f = $("#myForm");
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
and this form :
<form id="myForm" action="/Monitor/Test/FormPost" method="post">
<div>First Name: <input name="FirstName" type="text" value="Bob" /></div>
<div>Last Name: <input name="LastName" type="text" value="Cravens" /></div>
<div>Age: <input name="Age" type="text" value="43" /></div>
<input type="submit" value="Save Contact" />
<div id="postResult">?</div>
</form>
How can I bind the save button with the jquery function ? Thank you
One simple way would be to bind to the click event of the button. Something like this:
$('#myForm input[type="submit"]').click(function () {
var f = $("#myForm");
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
});
This specifically looks for the submit input that's a child of the form of id "myForm" (in case there are other buttons, etc.) and responds to its click event with the function in question.
Just to be safe, since you're essentially short-circuiting the form and posting via AJAX, you should also probably change the submit to a normal button:
<input type="button" value="Save Contact" />
Or perhaps:
<button value="Save Contact" />
Which would change your jQuery selector to:
$('#myForm input[type="button"]')
Or:
$('#myForm button')
$(document).on("click","input[type=submit]",function(e)
{
e.preventDefault();
var form = $(this).closest("form");
$.post(form.attr("action",form.serialize(),function(d){
//result
});
});
more general way.
//this handler can work on any form that need to post all values
$("form input[type='submit']", f).click(function(e){
e.preventDefault();
var $this = $(this);
var f = $this.parents('form');
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
return false;
})
In this code you are subscribing click event.
[e.preventDefault();][1] will stop your form from premature submittion and you can do the work you want.
I am new to knockout.js. I am following this tutorial. It is working fine on knockout site but not for me. Error console is also not showing any error.
Below is my code
View:
Tasks
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<div >
<ul data-bind="foreach: tasks, visible: tasks().length > 0" id="testing">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
</div>
View Model:
<script>
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.remove(task) };
}
ko.applyBindings(new TaskListViewModel(),document.getElementById("testing"));
</script>
The problem is that the ko.applyBindings doesn't apply to all data-bind attributes. Move your "testing" id to a place where it covers all the HTML code with the relevant "data-bind" attributes.