I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
Related
Can't load my data, i guess something is wrong with getting the date. Here's my ajax:
function refreshdata(page) {
dates = '{ "date": "2017-05-12T09:14:15Z" }';
if (page == 1) {
$.ajax({
url: semRoute,
type: 'GET',
success: function (result) {
var data = JSON.parse(result);
showData(data);
}
});
}
console.log(page);
}
AjaxController:
public string Get(string date)
{
var obj = new DepDate(date);
return Model.balance.GetDataJSON(obj);
}
I'm trying to get the percentage of Ajax requests processed at Mvc. I learned that this should be done with AsyncController.
But when the first request worked, I did not get the percentage because it was on the TaskProgress tail.
Controller:
public class AsyncTestController : AsyncController
{
public void TaskAsync(int id)
{
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(taskId =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
HttpContext.Application["task" + taskId] = i;
}
var result = "result";
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["result"] = result;
return result;
}, id);
}
public ActionResult TaskCompleted(string result)
{
return Content(result, "text/plain");
}
public ActionResult TaskProgress(int id)
{
string asd = HttpContext.Application["task" + id].ToString();
return Json(new
{
Progress = HttpContext.Application["task" + id]
}, JsonRequestBehavior.AllowGet);
}
}
View (javascript):
function async_test_start() {
var taskId = 543;
$.ajax({
url: '#Url.Content("~/IK/AsyncTest/task/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
window.clearInterval(intervalId);
console.log(dt);
}
});
var intervalId = window.setInterval(function () {
$.ajax({
url: '#Url.Content("~/IK/AsyncTest/taskprogress/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
console.log(dt.Progress + '%');
}
});
}, 5000);
}
Result (when ajax request starts):
I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Content/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.
I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.
Is possible with $.ajax otherwise how can I?
Becase following code does not redirect.
[code]
[HttpPost]
public ActionResult Save(RecipeViewModel postdata)
{
Recipe recipe = postdata.GetRecipe(_user.UserID);
int recipeid = _service.AddRecipe(recipe, null, true);
foreach (Ingredient ing in recipe.Ingredients)
{
ing.RecipeID = recipeid;
_service.AddIngredient(ing, null, false);
}
if (!postdata.Comment.IsEmpty())
{
Comment comment = new Comment();
comment.fldComment = postdata.Comment;
comment.RecipeID = recipeid;
comment.UserID = _user.UserID;
comment.EnteredByName = _user.Names;
comment.EnteredOn = DateTime.Now.ToString();
_service.AddComment(comment, null, false);
}
_service.SubmitChanges();
return RedirectToAction("View", "Recipe", new { id = recipeid });
}
u<script type="text/javascript">
$("#Save").click(function () {
var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
return {
ingredientName: $("td.ingredient", this).text(),
units: $("td.units", this).text(),
measure: $("td.measure", this).text()
};
}).toArray();
var json = {
RecipeTitle: $("#recipetitle").val(),
CategoryID: $("#category").val(),
PrepTime: $("#prepTime").val(),
PrepTimePeriod: $("#lstPrepTime").val(),
CookTime: $("#cookTime").val(),
CookTimePeriod: $("#lstCookTime").val(),
Rating: $("#rating").val(),
Method: $("#method").val(),
Comment: $("#comment").val(),
AccessLevel: $("#accessLevel").val(),
Ingredients: ingredients
};
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
Malcolm
You need to send back the Url and redirect it from the client script.
success: function (urlData) {
window.location.href = urlData ;
return false;
}
or you may show an error message based on the response received.