I have a web Api that allow me to add a multiple Image with with another parameter
(place_Id , is_Main)
I use this code bellow to upload the image
[Route("api/Image")]
[HttpPost]
public async Task<IHttpActionResult> PostImage()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/Images/Places");
var provider = new CustomMultipartFormDataStreamProvider(root);
try
{
// Read the form data.
var task = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = provider.FileData.Select(d =>
{
var info = new FileInfo(d.LocalFileName);
//return new FileDesc(info.Name);
return new FileDesc(info.Name);
});
return fileInfo;
});
int placeId = int.Parse(provider.FormData["placeId"]);
bool isMain = Convert.ToBoolean(provider.FormData["isMain"]);
var listOfAttchments = task.ToList();
string attachmentsPath = Request.RequestUri.Scheme +
System.Uri.SchemeDelimiter +
Request.RequestUri.Host +
(Request.RequestUri.IsDefaultPort ? "" : ":" + Request.RequestUri.Port) +
"/Images/Places/";
Images i = new Images();
if (listOfAttchments.Count > 0)
{
foreach (var item in listOfAttchments)
{
i.FileLocation = item.name;
i.FromUser = true;
i.TableName = "Places";
i.IsMain = isMain;
i.TableId = placeId;
db.Images.Add(i);
}
}
await db.SaveChangesAsync();
return Ok(new
{
result = true,
listAttachmment = listOfAttchments
}
);
}
catch (System.Exception e)
{
return BadRequest(e.StackTrace + "\nTest" + e.Data + "\nTest" + e.InnerException + "\nTest" + e.Message + "\nTest" + e.Source + "\nTest" + e.TargetSite);
}
}
The previous api is in another domain,
and I have a web forms application , that want to upload image from it, using the previous api
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function (i, file) {
data.append(" placeId: 7, isMain: 1");
data.append('image1' + i, file);
});
$("#btn2").click(function () {
jQuery.ajax({
url: '{url}/api/api/Image',
data: data,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function (data) {
alert(data);
}
});
});
I used the above code to invoke it, but I have a problem,
can you help me
Please ensure that you are not receiving XSS Error message (normally other domains are configured that you will not be able to trigger calls from a different domain addresses).
In the below code, i am not sure why do you have /api/api
url: '{url}/api/api/Image',
Please post us the error message you are receiving
Related
I am not that much efficient in mvc. I want to continuously try pinging the IPs in the list and then render the data in Index view using Viewbag. but problem here is I have to refresh the page manually each and every time to get the current status of each and every IP.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<string> IPlist = new List<string>();
IPlist.Add("10.0.1.151");
IPlist.Add("www.google.com");
IPlist.Add("192.168.0.1");
Ping myping = new Ping();
StringBuilder sc = new StringBuilder("Ping Status:");
foreach (string c in IPlist)
{
PingReply replytest = myping.Send(c, 1000);
if (replytest != null)
{
sc.Append(" Status : " + replytest.Status + " \n Time: " + replytest.RoundtripTime.ToString() + " \n Address : " + replytest.Address + " \n ");
}
else
{
sc.Append("Request Failed");
}
}
ViewBag.result = sc.ToString();
return View();
}
}
Add new action which return a JsonResult from a controller to the ajax query. Simply convert the string to JsonResult by using Json(stringvalue);
public class HomeController : Controller
{
public JsonResult GetCurrentStatus()
{
List<string> IPlist = new List<string>();
IPlist.Add("10.0.1.151");
IPlist.Add("www.google.com");
IPlist.Add("192.168.0.1");
Ping myping = new Ping();
StringBuilder sc = new StringBuilder("Ping Status:");
foreach (string c in IPlist)
{
PingReply replytest = myping.Send(c, 1000);
if (replytest != null)
{
sc.Append(" Status : " + replytest.Status + " \n Time: " + replytest.RoundtripTime.ToString() + " \n Address : " + replytest.Address + " \n ");
}
else
{
sc.Append("Request Failed");
}
}
return Json(sc.ToString());
}
}
Add javascript function which call new action. And call this function every 5000 milliseconds with setInterval. On success of ajax I am setting retrieved value to
element with id divPintStatus. You can change it as per your actual code. Also set #Url.Action as your own code.
setInterval(getCurrentStatus, 5000);
function getCurrentStatus() {
$.ajax({
url: '#Url.Action("GetCurrentStatus")', // Or '#Url.Action("GetCurrentStatus", "ControllerName")',
type: "GET",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
$('#divPintStatus').val(data);
}
});
}
I am working over async web method (asmx file) and I need to call this method throughout an ajax jquery method however I am facing a lot of issues because the method uses also Entity Framework to run some other things.
Here is JavaScript:
function SubmitStripeForm() {
// event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
// stripeTokenHandler(result.token);
console.log();
var myToken = result.token.id;
$.ajax({
type: "POST",
url: "http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment",
crossDomain: true,
async: false,
data: '{Tok: "' + myToken + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d) {
console.log("Good");
}
else {
console.log("Bad");
}
},
failure: function (response) {
console.log("HORRIBLE");
}
});
}
});
Here is the web method in asp.net c#:
[WebMethod(EnableSession = true)]
public async void MyStripePayment(string Tok)
{
string MyToken = Tok;
using (var context = new CompanyEntities())
{
var collection = (from p in context.COMPANY where p.Id == Company_Id select p);
foreach (var item in collection)
{
// Validation of the object
BillingManagement.Michael Maik = new BillingManagement.Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
#region Send Information To Stripe
CancellationToken Token = new CancellationToken();
string Url = "http://localhost:5000/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Token)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
string resString = await response.Content.ReadAsStringAsync();
JObject jObject = JObject.Parse(resString);
string message = (string)jObject["message"];
}
}
}
#endregion
}
}
and this is the error displayed:
POST http://localhost:54355/Account/API/Stripe.asmx/MyStripePayment 500 (Internal Server Error)
have you tried using Try/Catch to get more information about the error? obviously it is something internal, better used it like that and try again to see what error it is.
try
{
// Code
}
catch (Exception ex)
{
console.writeLine(ex);
}
OR
You put an intervention in the catch to be able to see in local variables the values of the "Ex" or save the error somewhere to read it later.
I have a canvas element in a web site that I'm uploading using the FormData API. Here's how I do it:
upload: function (e) {
var file = this.imagePreview.ui.canvas.get(0).toDataURL("image/jpeg")
.replace('data:image/jpeg;base64,', '');
if (file) {
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: app.getApiRoot + 'UserFiles/',
type: "post",
data: formData,
processData: false,
contentType: false,
error: function () {
$("#file_upload_result").html('there was an error while submitting');
}
});
}
}
where I'm replacing the whole data:image/jpeg;base64, business as per this post.
On the backend I have the following multipart controller:
public async Task<IHttpActionResult> PostUserFile()
{
string imageDir = ConfigurationManager.AppSettings["UploadedImageDir"];
var PATH = HttpContext.Current.Server.MapPath("~/" + imageDir);
var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var files = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new UserFile(User.Identity.GetUserId(), info.Name, rootUrl + "/" + imageDir + "/" + info.Name, info.Length / 1024);
});
db.UserFiles.AddRange(files);
db.SaveChangesAsync();
});
return Ok();
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
Where I implement a CustomMultipartFormDataStreamProvider as follows:
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path)
{ }
public override string GetLocalFileName(Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ?
headers.ContentDisposition.FileName :
"NoName";
// This is here because Chrome submits files in quotation
// marks which get treated as part of the filename and get escaped
return name.Replace("\"\"", string.Empty);
}
}
Sadly, the FileData on the streamProvider fed into the ReadAsMultipartAsync method is empty:
And another thing I find interesting is that the uploaded binary file is escaped, as I notice from the watch window:
The %2f is the escape sequence for the / character.
I simply can't pinpoint the problem. Anyone have any suggestions?
Mixing ContinueWith and async/await leads to problems, just do await Request.Content.ReadAsMultipartAsync(streamProvider); and everything in the .ContinueWith would just go after the await like normal code.
Or remove async/await and add:
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith...
Also you can look this link: Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME
I have webApplication in MVC Framework..
i have situation where i have to provide user to export some data to csv file
for that i have written following code ..
[HttpPost]
public ActionResult ExportReportToFile(ReportCriteriaViewModels posdata, string name)
{
string strQuery = GetReportQuery(posdata, name);
IEnumerable<REP_MM_DEMOGRAPHIC_CC> lstDemographics = ReportDataAccess.GetReportData<REP_MM_DEMOGRAPHIC_CC>(strQuery);
if (lstDemographics.Count() > 0)
return new CsvActionResult<REP_MM_DEMOGRAPHIC_CC>(lstDemographics.ToList(), "LISDataExport.csv");
else
return view(posdata);
}
Above code works fine... if in listResult Count is Greater than zero then i returns File to download.. but if i dont get any records in lstDemographics then i returns view..
My problem is when i dont get any result in lstDemographics, i dont want to return view coz it refreshes whole view.. so is there any way where we can stop execution of Action Method and browser doesn't refresh the view and stay as it is..
Thanks..
You will have to make an AJAX call to stop page refresh.
To achieve file export, we actually broke the process in two AJAX calls. First call sends a request to server, server prepare a file and store it in temp table. Server return the file name to AJAX call if there is data. If no data or error, it return a JSON result to indicate a failure.
On success, view make another AJAX request to download the file passing file name.
Something like this:
[Audit(ActionName = "ExportDriverFile")]
public ActionResult ExportDriverFile(int searchId, string exportType, string exportFormat)
{
var user = GetUser();
var driverSearchCriteria = driverSearchCriteriaService.GetDriverSearchCriteria(searchId);
var fileName = exportType + "_" + driverSearchCriteria.SearchType + "_" + User.Identity.Name.Split('#')[0] + "." + exportFormat;
//TempData["ExportBytes_" + fileName] = null;
_searchService.DeleteTempStore(searchId);
var exportBytes = exportService.ExportDriverFileStream(driverSearchCriteria, searchId, exportType, exportFormat, user.DownloadCode, user.OrganizationId);
if (exportBytes != null)
{
var tempStore = new TempStore
{
SearchId = searchId,
FileName = fileName,
ExportFormat = exportFormat,
ExportType = exportType,
DataAsBlob = exportBytes
};
var obj = _searchService.AddTempStore(tempStore);
return Json(fileName);
}
else
{
return Json("failed");
}
}
[HttpGet]
public ActionResult DownloadStream(string fileName, int searchId)
{
var tempStore = _searchService.GetTempStore(searchId);
var bytes = tempStore.DataAsBlob;
if (bytes != null)
{
var stream = new MemoryStream(bytes);
// TempData["ExportBytes_" + fileName] = null;
_searchService.DeleteTempStore(searchId);
return File(stream, "application/vnd.ms-excel", fileName);
}
_logger.Log("Export/DownloadStream request failed", LogCategory.Error);
return Json("Failed");
}
At client side, we do something like:
function ExportData(exportType, exportFormat) {
var searchId = document.getElementById('hfSelectedDriverId').value;
var model = { searchId: searchId, exportType: exportType, exportFormat: exportFormat };
//$('div[class=ajax_overlay]').remove();
//alert("The file will be downloaded in few minutes..");
$.ajax({
url: '#Url.Action("ExportDriverFile", "Export")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function (result) {
result = result.toString().replace(/"/gi, "");
if (result == "" || result == "failed")
{
alert("File download failed. Please try again!");
}
else
{
window.location = '/Export/DownloadStream?fileName=' + result+"&searchId="+searchId;
}
})
.error(function (xhr, status) {
//
//alert(status);
});
//$('div[class=ajax_overlay]').remove();
}
You should create javascript function with $.getJSON method.
On controller side you just have to check, if you get data from database then return file path else return message.
Your JS code should be something like this:
$.getJSON(url)
.done(function (data) {
if (data.filePath) // If get data, fill filePath
window.location = data.filePath;
else
alert(data.msg);
});
And from controller you can create a HTTPGET Action method that return JSON data like:
return Json(new { msg = "No data found" }, JsonRequestBehavior.AllowGet);
Based on condition you can simple change msg with filePath.
I am using the below code to view the uploaded file using javascript. It display the fake path so i can't able to upload the files to server path. please help me to upload the images to server.mappath folder.
<input type='file' name='file' id='file' value='Choose Photo' accept='image/png,image/jpeg' onchange='handleFileSelect(this);' />
<script type="text/javascript">
function handleFileSelect(input) {
try {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('hf_image').value = e.target.result
$('#preview').attr('src', document.getElementById('hf_image').value);
}
reader.readAsDataURL(input.files[0]);
}
}
catch (ex) {
alert('Image Preview : ' + ex.Message);
}
}
</script>
var attachments={};
function imageSelected(myFiles){
for (var i = 0, f; f = myFiles[i]; i++) {
var imageReader = new FileReader();
imageReader.onload = (function(aFile){
return function(e){
var tempFileData=e.target.result;
attachments[aFile.name]={};
attachments[aFile.name]["content_type"]=tempFileData.split(",")[0].split(":")[1].split(";")[0];
attachments[aFile.name]["data"]=tempFileData.split(",")[1];
};
})(f);
imageReader.readAsDataURL(f);
}
}
<input type='file' onchange="imageSelected(this.files)">
the above code may be helpful for you
attachments json holds the file details
Why you don't use AjaxFileUploader, that is easy to use
Follow this steps to approach your target,
Step 1:
dRAG Jquery files to Head tag.
add this code to a JavaScript file and dragged it into the head of your page.
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if (window.ActiveXObject) {
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function (id, fileElementId, data) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if (data) {
for (var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {}
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function (isTimeout) {
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
// If a local callback was specified, fire it and pass it the data
if (s.success)
s.success(data, status);
// Fire the global callback
if (s.global)
jQuery.event.trigger("ajaxSuccess", [xml, s]);
} else
jQuery.handleError(s, xml, status);
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if (s.global)
jQuery.event.trigger("ajaxComplete", [xml, s]);
// Handle the global AJAX counter
if (s.global && ! --jQuery.active)
jQuery.event.trigger("ajaxStop");
// Process result
if (s.complete)
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
jQuery(form).attr('encoding', 'multipart/form-data');
}
else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback);
return { abort: function () { } };
},
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
})
something like this:
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="Scripts/fileUploader.js" type="text/javascript"></script>
Step 2:
Add this tags into body page.
<input id="fileToUpload" type="file" size="45" name="fileToUpload" />
<button id="btnUploadNewLicense" onclick="return ajaxFileUpload('New');">
Upload</button><br />
<div id="loading" style="display: none;">
Please wait...</div>
Step 3:
Add a generic handler file named "FileUpload.ashx" into the your project root,
add this following code into "FileUplod.ashx"
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string action = request["Action"];
switch (action)
{
case "New":
string result = "failed";
try
{
string fileName = SaveCaper(context);
result = "successed";
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
catch
{
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
break;
default:
throw new Exception("Invalid sort column name!.");
}
}
private string SaveCaper(HttpContext context)
{
string fileName = string.Empty;
string path = context.Server.MapPath("~/NewImages");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
try
{
var file = context.Request.Files[0];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
try
{
file.SaveAs(fileName);
}
catch (Exception exp)
{
//log the exception
}
}
catch (Exception exp)
{
//log the exception
}
return fileName;
}
public bool IsReusable
{
get
{
return false;
}
}
also you need to add System.IO in top of the handler code behind.
Step 4:
Add this script to your head after your JS files prototype
<script language="javascript" type="text/javascript">
$(document).ready(function () {
function ajaxFileUpload(mode) {
var fupl = 'fileToUpload';
var fileName = $('#fileToUpload').val();
if (fileName == "" || fileName == null)//if user doesn't select an image
{
$("#loading").html("");
$("#loading").append("<br/><b>Please select an image...</b>");
}
else {
var vars = fileName.split("."); //get file extension.
if (vars[1].toString().toLowerCase() != "jpg") {//check the file extension.
$("#loading").html("");
$("#loading").append("<br/>The image format is not valid !.");
return false;
}
$("#loading").ajaxStart(function () { $('#dialogUpdateLicense :input').attr('disabled', true); $(this).show(); })
.ajaxComplete(function () { $('#dialogUpdateLicense :input').removeAttr('disabled'); });
$("#loading").html("");
$("#loading").append("<br/><b>Please wait...</b>");
$.ajaxFileUpload
({
url: 'FileHandler.ashx',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { Action: mode },
success: function (data) {
if (data.result == "successed")
$("#loading").html("The image uploaded successfully!.");
},
error: function (data, e) {
$("#loading").html("An error occured!.");
}
})
}
return false;
}
</script>
All thing was tested and works properly for me
I hope it will help you.