Transferring data from the js script to the controller - javascript

In the view (Index.cshtml) I have a button, when I click on that, the script that in the selectedItems writes the data is triggered. how are selectedItems transferred to the controller?
Button:
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
JS:
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
}
Controller (Users):
[HttpPost]
public async Task<ActionResult> Delete(string[] selectedUsers)
{
...
return RedirectToAction("Index");
}
I tried to use ajax, but something does not work out:
function SelectedCheckbox()
{
$.ajax({
url: "/Users",
contentType: "application/json",
method: "POST",
data: { parameters: parameters },
success: function (data) {
var data = new Array();
$("input[id='check']:checked").each(function () { data.push($(this).val()); });
alert(data.result);
},
error: function (data) { alert(data.responseText); }
})
}
#model IEnumerable<Task1.Models.User>
#{
ViewBag.Title = "Список пользователей";
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="btn-toolbar nl container col-md-12" role="toolbar" aria-label="Menu">
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" name="delete" id="delete" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
<form method="post" asp-controller="Account" asp-action="LogOff">
<button type="submit" class="col-md-2 col-md-offset-3 " role="group" aria-label="LogOff" />LogOff</button>
</form>
</div>
<form asp-action="Delete">
<div class="nl">
<table class="table table-striped table-bordered ">
<tbody class="table-responsive ">
<tr><th><input type="checkbox" class="all" data-id="d1" title="Выбрать все"></th><th>Login</th><th>Date of registration</th><th>Date Last Login</th><th>Block disabled</th></tr>
#foreach (var user in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedUsers"
id="#user.Id" value="#user.Id"
class="styled">
</td>
<td>#user.UserName</td>
<td>#user.DateOfRegistration</td>
<td>#user.DateLastLogin</td>
<td>#user.LockoutEnabled</td>
</tr>
}
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
alert(selectedItems);
return (selectedItems);
}
</script>
I need to pass the value of the selected Item from the script in the method of removing the controller

Related

How to call api path in thymeleaf to reload table data in javascript function

I need click the submit button to reload table data,
But in javascript function , I don't known how to call the url pass parameters in thymeleaf.
I call this web page is below:
.....[menu partial code]....
<a class="dropdown-item" th:href="#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}">user list</a>
.....
the query and content Page:
<form >
<div class="col-sm-3 my-1">
<label class="sr-only" for="inlineFormInputName">Name</label> <input
type="text" class="form-control" id="inlineFormInputName"
placeholder="user name">
</div>
<div class="col-auto my-1">
<button type="submit" class="btn btn-primary query-submit"
id="querySubmit">Submit</button>
</div>
</div>
</form>
.....
<div class="row mt-5" th:fragment="table_content">
<div class="col">
...
<table class="table table-responsive table-hover">
<tbody>
<tr th:each="users,iter : ${response.content}">
<th scope="row" th:text="${iter.index+1}"></th>
<td class="text-info text-center"
th:text="${users.name}"></td>
</tr>
</tbody>
</table>
</div>
</div>
.....
I don't know the syntax in thymeleaf , if I need pass the params and call api in the js function. If the url will write #{/registeredUserList(type=0,userId=id0001,page=0,size=10)} like menu path, how can I write the syntax in the js function at url.
thank you~
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: url, // here , I don't know syntax, I can't use [#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}] the path in here . how can I write the syntax.
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>
Use th:inline="javascript" and the /*[[#{/url/}]]*/ syntax:
<script th:inline="javascript">
$(function() {
$('#querySubmit').click(querySubmitClickAction);
querySubmit.addEventListener('click', querySubmitClickAction);
function querySubmitClickAction(e) {
$.ajax({
url: /*[[#{/registeredUserList(type=0,userId=id0001,page=0,size=10)}]]*/ 'dummy',
type: 'POST',
success: function (data) {
$(".table_content").html(data);
}
})
}
});
</script>

Submit through a Partial view

I have a Partial View as a Table, that will be refreshed with a Dropdown Selection in the Main View. This dropdown list includes company names. In the table below information matters pertaining to each company, and for each line of this information there is a drop-down list of all the functions that I can do with this line (like deleting or modifying the information) with a Pop-up Modal.
How can I call a Method in the main Model or Submit something? Or can I create a Partial View with Model in my Case?
Here is my Main View:
#page
#model Fachinformationsdienst_Kundenportal.Pages.Information_listModel
#{
}
<form>
<div class="form-row align-items-center">
<div class="form-group col-md-4">
<label for="inputState">Wählen Sie eine Unternehmen aus</label>
<select id="inputState" class="form-control">
#for (int i = 0; i < Model.companies.Count; i++)
{
<option>#Model.companies[i].FirmenKurzBezeichnung</option>
}
</select>
</div>
<div class="form-group col-md-6">
<input class="form-control" id="myInput" type="text" style="margin-top: 31px;" placeholder="Suche...">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-primary" style="margin-top: 31px;">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</form>
<div id="fachinfoContainer">
<partial name="_FachinfoPartial" model="#Model.myViewModel" />
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$("#inputState").change(function () {
var selectcompany = "";
if ($(this).val() != "Wählen Sie die Firma aus...") {
selectcompany = $(this).val();
}
$.ajax({
url: "/Actions/Information-List?handler=fachinfoPartial",
type: "Get",
data: { company: selectcompany },
success: function (result) {
$("#fachinfoContainer").html(""); //clear the fachinfo container.
$("#fachinfoContainer").html(result); //populate the container.
},
error: function (result) {
alert(result);
}
});
});
});
</script>
}
Here is my Partial View
#model Fachinformationsdienst_Kundenportal.Models.MyViewModel
<table class="table table-striped" id="FachinfoTable">
<thead>
<tr>
<th scope="col">Nr.</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Letzte Änderung</th>
<th scope="col">Aktuelle Version</th>
<th scope="col">Auftrag</th>
</tr>
</thead>
<tbody id="myTable">
#if (#Model.Fachinfos != null)
{
#for (int i = 0; i < #Model.Fachinfos.Count; i++)
{
<tr>
<th scope="row">#Model.Fachinfos[i].FachinfoNummer</th>
<td>#Model.Fachinfos[i].FachinfoName</td>
<td>#Model.Fachinfos[i].Status</td>
<td>#Model.Fachinfos[i].Datum</td>
<td>#Model.Fachinfos[i].PdfVersion</td>
<td>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#for (int c = 0; c < #Model.SelectedCompany.Permissions.Count; c++)
{
if (Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ERSTERFASSEN && Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ABFRAGEN)
{
<a class="dropdown-item" data-toggle="modal" data-number="#Model.Fachinfos[i].FachinfoNummer" data-version="#Model.Fachinfos[i].PdfVersion" data-target="##Model.SelectedCompany.Permissions[c]">#Model.SelectedCompany.Permissions[c]</a>
}
}
</div>
</div>
</td>
</tr>
}
}
</tbody>
</table>
<!-- The Delete Modal -->
<div class="modal fade" id="#Models.Company.Permission.LOESCHEN">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Bestätigen</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<span id="deletMessege">Sind Sie sicher, dass Sie diese Fachinformation löschen möchten?</span>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="confirm" type="submit" class="btn btn-primary">Senden</button>
</div>
</div>
</div>
</div>
<script>
$('##Models.Company.Permission.LOESCHEN').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var fiNumber = button.data('number') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('Fachinfonummer ' + fiNumber)
})
</script>
Here is my main model
using Fachinformationsdienst_Kundenportal.Classes;
using Fachinformationsdienst_Kundenportal.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Fachinformationsdienst_Kundenportal.Pages
{
public class Information_listModel : PageModel
{
public List<Company> companies { get; set; }
public List<Fachinfo> fachinfos = new List<Fachinfo>();
public MyViewModel myViewModel = new MyViewModel();
public void OnGet()
{
companies = APIRequester.GetCompanies(User.Identity.Name);
foreach (var company in companies)
{
fachinfos.AddRange(APIRequester.GetFachinfos(company.FirmenKurzBezeichnung));
}
}
public PartialViewResult OnGetFachinfoPartial(string company)
{
//based on the selctedcompany to filter data, then return to the partial view.
companies = APIRequester.GetCompanies(User.Identity.Name);
myViewModel = new MyViewModel()
{
SelectedCompany = companies.Find(r => r.FirmenKurzBezeichnung == company), //get the company object here
Fachinfos = APIRequester.GetFachinfos(company)
};
return Partial("_FachinfoPartial", myViewModel);
}
//Submit this Method from Partial view
public IActionResult onDelete(string fiNumber)
{
return Page();
}
}
}
You can use JQUERY AJAX calls for this
$.ajax({
type: "POST",
url: '/Information_listModel?handler=Ondelete',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data.result);
})
your method should return type IActionResult

why document.ready not loaded after ajax request

I want to call java script after clicking <a> tag in my partial view, it is working for the first time but second time after using ajax and rendering my partial view, it doesn't go to <a> tag event. let just show my code to let you grasp it better. this is my parent view:
#using X.PagedList
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Core.Common
#model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
#{
ViewData["Title"] = "RegisteredNurseList";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
// LOT OF HTML TAG CODE HERE I JUST IGNOR THEM...
<section id="table-transactions">
<!-- datatable start -->
<div id="nursesList">
<partial name="PaginatedNurses" model="Model" />
</div>
<!-- datatable ends -->
</div>
</section>
#section modalSection
{
<script>
window.$(document).ready(function () {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
});
</script>
}
as you see I am using <partial name="PaginatedNurses" model="Model" /> to call partial view. and this is my PaginatedNurses partial view :
#using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
#using X.PagedList
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Core.Common
#model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
<body>
<form>
<div id="RegisteredNursePaginated">
<div class="form-group row">
<div class="col-md-3">
از سن <input class="form-control" id="minAge" type="number" name="MinAge" value="#ViewBag.MinAge" />
</div>
<div class="col-md-3">
تا سن <input class="form-control" id="maxAge" type="number" name="MaxAge" value="#ViewBag.MaxAge" />
</div>
<div class="col-md-3">
مرتب سازی بر اساس
<select class="form-control" name="SortOrder" value="#ViewBag.SortOrder" style="width: 200px" id="sortOrder">
<option value="age">
سن
</option>
<option value="registerDate">
زمان ثبت نام
</option>
</select>
</div>
<div class="col-md-3">
نحوه مرتب سازی
<select class="form-control" name="SortType" value="#ViewBag.SortType" style="width: 200px" id="sortType">
<option value=1>
صعودی
</option>
<option value=0>
نزولی
</option>
</select>
</div>
</div>
<input type="submit" value="جست و جو" id="btnSearch" />
<div class="table-responsive">
<table id="table-extended-transactions" class="table mb-0">
<thead>
<tr>
<th>نام</th>
<th>سن</th>
<th>شماره پروانه کار</th>
#*<th>شماره ملی</th>*#
<th>دوره حرفه ای</th>
<th>تاریخ ثبت نام</th>
</tr>
</thead>
<tbody>
#foreach (var nurse in Model)
{
<tr>
<td><i class="bx bxs-circle success font-small-1 mr-50 align-middle"></i><span>#nurse.FullName</span></td>
<td class="text-bold-700">#nurse.Age</td>
<td class="text-bold-700">#nurse.NurseSystemNumber</td>
<td>
#nurse.ProfessionalCourseDescription
</td>
<td>
#nurse.SubmissionDatePersian
</td>
<td>
<div class="dropdown">
<span class="bx bx-dots-horizontal-rounded font-medium-3 dropdown-toggle nav-hide-arrow cursor-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" role="menu">
</span>
<div class="dropdown-menu">
<a class="dropdown-item" href="#Url.Action("NurseDetails", "Admin", new {id = #nurse.Id})"><i class="bx bx-edit-alt mr-1"></i> نمایش جزئیات</a>
<a class="dropdown-item" onclick="setInvitation('#nurse.Id')">تایید</a>
<a class="dropdown-item" onclick="refuseRegister('#nurse.Id')"><i class="bx bx-trash mr-1"></i>عدم تایید</a>
</div>
</div>
</td>
</tr>
}
</tbody>
</table>
<div id="pager">
<input value="1" type="hidden" id="pageGetter"/>
#Html.PagedListPager((IPagedList) Model, page =>
Url.Action("RegisteredNurseList",
new
{
page = page,
SortOrder = ViewBag.SortOrder,
SortType = ViewBag.SortType,
MaxAge = ViewBag.MaxAge,
MinAge = ViewBag.MinAge
}),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new AjaxOptions() {HttpMethod = "GET", UpdateTargetId = "RegisteredNursePaginated"}))
</div>
</div>
</div>
</form>
</body>
as you witness there is html tag helper #Html.PagedListPager((IPagedList) Model,... this is using <a> tag. I Mean after clicking on this, it is going to parent modelSection:
<script>
window.$(document).ready(function () {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
});
</script>
it works first time but after using ajax and rendering it by controller, it will never go to that part again after clicking <a> tag. this is my controller:
public async Task<IActionResult> RegisteredNurseList(int? page, int? sortType, string sortOrder,
int? minAge, int? maxAge)
{
bool isAjax = HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
ViewBag.PageNumber = page ?? 1;
int pageSize = 2;
int skip = (ViewBag.PageNumber - 1) * pageSize;
ViewBag.MinAge = minAge ?? 18;
ViewBag.MaxAge = maxAge ?? 99;
ViewBag.SortType = sortType ?? 1;
ViewBag.SortOrder = sortOrder ?? "age";
var tuple = await _admin.GetNurses(skip, pageSize, sortOrder ?? "age", sortType ?? 1, minAge ?? 18, maxAge ?? 99);
int total = tuple.Item2;
var nurses = tuple.Item1;
var result = new StaticPagedList<NurseDetailsViewModel>(nurses, ViewBag.PageNumber, pageSize, total);
if (isAjax)
{
return (ActionResult)PartialView("PaginatedNurses", result);
}
return View(result);
}
after #steve perfect comment I got his idea and I changed my code like below and then it worked:
<script>
function AjaxInit() {
window.$('#RegisteredNursePaginated').find('a[href]').on('click',
function (e) {
e.preventDefault();
var sortOrder = window.$("#sortOrder").val();
var sortType = window.$("#sortType").val();
var minAge = window.$("#minAge").val();
var maxAge = window.$("#maxAge").val();
var page = getQueryStringValue(this, 0).replace('page=', '');
// window.$("#pageGetter").val(page);
debugger;
console.log(this);
window.$.ajax({
url: "/admin/RegisteredNurseList/",
type: 'GET',
data: {
page: page,
SortOrder: sortOrder,
sortType: sortType,
MinAge: minAge,
MaxAge: maxAge
},
success: function (result) {
debugger;
window.$('#RegisteredNursePaginated').html(result);
}
});
return false;
});
}
</script>
<script>
window.$(document).ready(function () {
AjaxInit();
});
</script>
<script>
$(document).ajaxComplete(function () {
AjaxInit();
});
</script>

How can i store at a time 3 value same textbox?

<script type="text/javascript">
document.getElementById("subcategory").addEventListener("change", function() {
console.log(this.value);
});
$(function(){
$('.categoryList').click(function(){
console.log($(this).attr("name"));
var cat_id = event.target.value;
var url = "http://localhost:8000/api/getSubcategory/"+cat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li class="+'subcategorys'+" value="+key+" name="+value+">"+value+" </li>";
});
$('#subcategory').html($(html).addClass('subcategoryList'));
$('.subcategorys').on('click', function(event) {
console.log($(this).attr("name"));
var subcat_id =event.target.value;
console.log(subcat_id);
});
}
});
});
});
$(document).ready(function() {
$('#subcategory').on('click', function(event) {
var subcat_id =event.target.value;
console.log(subcat_id);
var url = "/api/getSubcategorytwo/"+subcat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li value="+key+">"+value+"</option></li>";
});
$("#subcategorytwo").html(html);
}
});
});
$('#subcategorytwo').on('click', function(event) {
var opt_subcat_two =event.target.value;
var opt = $(event.target).text();
console.log(opt,opt_subcat_two);
$( "#fetchvalue" ).replaceWith("<input type='text' class='form-control' name='subcategorytwo' value="+opt_subcat_two+" id='fetchvalue' data-toggle='modal' data-target='#myModal'> "+opt+"</input>");
$('#myModal').modal('hide');
$('.modal-backdrop').remove();
});
});
</script>
<input type="text" class="form-control" name="subcategorytwo" id="fetchvalue" data-toggle="modal" data-target="#myModal" ></input>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog modal-lg" >
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<a type="button" class="close" data-dismiss="modal" aria-hidden="true">×</a>
</div>
<div class="modal-body">
<div class="row">
<table class="table table-striped">
<thead>
</thead>
<tbody class="table">
<tr>
<td style="background-color: green">
<div class="col-md-7" >
#foreach($categories as $category)
<option class="categoryList" name="{{$category->category}}" value="{{$category->id}}">{{$category->category}}</option>
#endforeach
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" id="subcategory"></ul>
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" name="subcategorytwo" id="subcategorytwo" ></ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
Here is javascript code and modal code...I have total 4 table...
category subcategory
subcategory
subcategorytwo
post table
all are connected to a foreign key
Post table structure
When try to save category value, subcategory value, subcategorytwo value error is
How can I store 3 value at a time different place in db
Modal show like this
Modal like this
MySQL is most likely in STRICT mode try to
change the column to allow null:
ALTER TABLE `posts` CHANGE `subcategory2` `subcategory2` varchar NULL
Or try running
SET GLOBAL sql_mode='' or

File submit failing with jQuery's Form Data() and Ajax

I have created a form to upload two files - questionpaper and the key. But the Ajax request is not working in an intended manner. I have been trying and trying but unable to figure out the bug. Please help.
Here is my form.
<form name="facform" id="facform" data-abide="ajax" enctype="multipart/form-data">
<fieldset>
<legend> All fields are required </legend>
<div class="row">
<div class="large-3 medium-3 columns">
<label> <b> Upload Question Paper </b> </label>
<input type="file" id="qfile" name="qfile" tabindex="7" required>
</div>
<div class="large-3 medium-3 columns end">
<label><b> Upload Key </b></label>
<input type="file" id="kfile" name="kfile" tabindex="8" required>
</div>
</div>
</fieldset>
<div class="row">
<div class="large-6 medium-6 columns">
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/></label>
<input id="form-submit" type="submit" class="button tiny" value="Submit" />
</div>
</div>
</form>
Here goes the javascript part.
<script>
//-----------------------//
$('#facform').on('valid.fndtn.abide', function() {
var fileInput = document.getElementById('facform');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('qfile', file);
formData.append('kfile', file);
var form_url = 'getfiles.php';
$("#form-submit").hide();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: 'POST',
data: formdata,
processData: false,
cache: false,
success: function(returnhtml){
$("#loadingimg").hide();
$("#facform").hide();
$("#smsg").html(returnhtml);
$("#facform")[0].reset();
}
//-----------------------//
});
});
</script>
to upload files using Ajax or jQuery , you need to use hidden iframe
this is full example for ajaxfileupload.js class allow you to use upload form .
or you could create simple function to submit your form into hidden iframe then get the iframe body html or text using jQuery as response .
<html>
<head>
<link href="http://www.phpletter.com/css/general.css" rel="stylesheet" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$.ajaxFileUpload
(
{
//YOUR URL TO RECEIVE THE FILE
url: 'http://localhost/testing/postfile.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(data.error);
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form name="form" action="" method="POST" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" class="tableForm">
<thead>
<tr>
<th>Ajax File Upload</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"></td>
</tr>
<tr>
<td>Please select a file and click Upload button</td>
</tr>
</tbody>
<tfoot>
<tr>
<td><button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button></td>
</tr>
</tfoot>
</table>
</form>
</body>
</html>

Categories