jQuery Form plugin doesn't calls Method in IE 8 - ajax

I am trying to upload files to server, but when i am submitting form it doesn't calls ActionResult. It works in chrome, FF but not in IE. When i am removing enctype="multipart/form-data" attribute from form in IE, then it calls method, but without file uploading...
I have such input:
<input id="jqueryfileupload" type="file" name="files" data-upload-id="#documentUniqueId"
data-url="#Url.Action(MVC.Profile.Documents().AddRouteValue("documentUniqueId", documentUniqueId))" multiple>
jQuery code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
//input itself is not in the form tag, so i am creating form here and
//submitting it this way
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="POST"></form>');
$this.appendTo(formContainer);
var contentTypeOption = $.browser.msie ? 'text/html' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
//contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
$(formContainer).ajaxSubmit(options);
return false;
});
There are no errors and alerts are not throwing at all in IE. Just method is not called...
Action Method:
[HttpPost]
public virtual ActionResult Documents(IEnumerable<HttpPostedFileBase> files, string documentUniqueId)
{
var result = new ContentResult();
if (files != null)
{
foreach (var item in files)
{
string docName = documentUniqueId + "_" + item.FileName;
var filename = Path.Combine(Server.MapPath("~/App_Data"), docName);
item.SaveAs(filename);
}
var docs = files.Select(x => new
{
url = Url.Action(MVC.Profile.Documents(documentUniqueId + "_" + x.FileName, x.ContentType)),
name = x.FileName,
contentType = x.ContentType,
id = documentUniqueId + "_" + x.FileName
});
result.Content = new JavaScriptSerializer().Serialize(docs);
return result;
}
result.Content = new JavaScriptSerializer().Serialize(new { success = false });
return result;
}
[HttpGet]
public virtual ActionResult Documents(string fileName, string contentType)
{
var docPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
return File(docPath, contentType);
}
I use this plugin : http://malsup.com/jquery/form/

I think you are not inserting the form in the page. that's the problem. you have to add formContainer.appendTo(container);
try this code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var container = $this.parents('.documents-upload-container').addClass("current-container");
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="post"></form>');
$this.appendTo(formContainer);
formContainer.appendTo(container);
var contentTypeOption = $.browser.msie ? 'text/plain' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
//data: { 'isIE': iframeOption },
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
formContainer.ajaxSubmit(options);
return false;
});

Related

jquery $.ajax call for MVC actionresult which returns JSON triggers .error block

I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).

ajaxfileupload problemajaxFileUpload is not a function

I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
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(e);
}*/
}
)
return false;
There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .
This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.
add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});
this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

How do I update foreign key with odata json

Expected behavior: User clicks on Register button and record is created in related entity. This has worked up til now but now we have requirement to update the foreign key based on a lookup on the current form. How do I accomplish this? The pasted code below throws error in browser "Error on the creation of record; Error – Bad Request"
// JScript source code
CreateButton = function () {
var fieldTable = crmForm.all.new_registerbutton_d;
var html = "<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY><TR><TD width=0px>" + fieldTable.innerHTML + "</TD><TD width=200><INPUT style='BACKGROUND-COLOR: #d8e8ff' onclick=Button_OnClick() value='Register' type=button></TD></TR></TBODY></TABLE>";
fieldTable.innerHTML = html;
document.all.new_registerbutton.style.display = 'none';
crmForm.all.new_registerbutton_c.innerText = "";
}
Button_OnClick = function () {
//var new_se_registration = new Object();
var invitationName = Xrm.Page.getAttribute("new_name").getValue();
//new_se_registration.new_name = invitationName;
var invitationGUID = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
alert(invitationGUID);
var value = new Array();
value[0] = new Object();
value[0].id = invitationGUID;
value[0].name = invitationName;
//var invitation = {
//id: invitationGUID, name: invitationName, entityType: "new_se_registration"
//};
//var invitation= { Id: invitationGUID, LogicalName: "new_se_registration", Name: invitationName };
//value[0].entityType = Xrm.Page.data.entity.getEntityType();
//new_se_registration.new_new_se_invitation_new_se_registid.setValue([{ id: invitationGUID, name: invitationName, entityType: "new_se_registration"}]);
//new_se_registration.new_new_se_invitation_new_se_registid = invitation;
//new_se_registration.new_eventname= Xrm.Page.getAttribute("new_eventname").getValue();
//new_invitationid is the Event id
var lookupItem = new Array;
lookupItem = crmForm.all.new_invitationid.DataValue;
var eventname = lookupItem[0].name;
//new_se_registration.new_eventname = eventname;
lookupItem = crmForm.all.new_invitationid.DataValue;
var new_se_registration = {
new_new_se_invitation_new_se_registid: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
//alert ( eventname);
// end Ek - adding event name
//deleteRecord(new_se_registration.new_name, "new_se_registrationSet");
var reg = Xrm.Page.getAttribute("new_registered").getValue();
if (reg == null) {
reg = "N";
}
if (reg != "Y") {
//Xrm.Page.getAttribute("new_registered").setValue("Y");
//alert(reg);
//return;
createRecord(new_se_registration, "new_se_registrationSet", RegisterCompleted, null);
Xrm.Page.getAttribute("new_registered").setValue("Y");
//Xrm.Page.data.entity.attributes.get("new_registered").setSubmitMode("always");
//Xrm.Page.data.entity.save();
}
else {
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered already.");
}
}
function RegisterCompleted(data, textStatus, XmlHttpRequest) {
var new_se_registration = data;
Xrm.Page.data.entity.save();
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered successfully.");
}
function checkDuplicate() {
alert("test");
}
function deleteRecord(id, odataSetName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("Record deleted successfully!");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error while deletion – " + errorThrown);
}
});
}
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – " + errorThrown);
}
});
}
Solved. Case sensitivity. Was using wrong case for new_new_se_invitation_new_se_registId.
var new_se_registration = {
new_new_se_invitation_new_se_regist**I**d: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};

Jquery and live act wired but act ok after force refresh in IE

somthing is wrong with my code and i can't get what it is...
i have a div id = "personaltab"
i have a form in side it to login the user with username and password. if success the jquery empty the div and puts in the form of the bidding.
if the user try to bid the other ajax that assign to the button is working but for some reason skips the empty and just adding the responded ajax to the div
i have checked that in IE and chrome and it is working fine in chrome
here are my codes
$("#login").click(function() {
var id = $("input#pid").val();
var user = $("input#puser").val();
var pass = $("input#ppass").val();
var dataString = 'id='+ id + '&user='+ user + '&pass=' + pass;
if (user == "") {
alert("error");
$("input#puser").focus();
return false;
}
if (pass == "") {
alert("error");
$("input#ppass").focus();
return false;
}
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
if (msg=="False") {
alert("error");
$("#personaltab").show();
}
else {
$("#personaltab").fadeOut("normal",function(){
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").slideDown();
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
return false;
});
$("#sendbid").live("click", function(){
var startat = $("input[name=startat]").val();
var sprice = $("input[name=sprice]").val();
if (parseInt(sprice)<=parseInt(startat)) {
alert("error");
$("input[name=sprice]").focus();
return false;
}
else {
var payment = $("select[name=payment]").val();
if ($('input[name=credit]').is(':checked') ){
var credit = true;
}
var prodid = $("input[name=id]").val();
var dataString = 'id='+ prodid + '&price='+ sprice + '&payment=' + payment + '&credit=' + credit;
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
}
return false;
});
Solved:
i had inside a and for some reason the div that need to get the ajax by his id was duplicated
don't ask :-)

Resources