I have two variables in my script view page, one called products and the other sites.
I have declared them like that.
Add.cshtml View:
$(function () {
products;
sites;
GetProductsAndSites(productsURL, sitesURL, '#Model.Key', false);
});
I call an ajax function, in another .js file.
People.js
function GetProductsAndSites(productsURL, sitesURL, secondLevelSiteKey, flag) {
$.ajax({
type: "POST",
url: productsURL,
async: false,
success: function (returndata) {
if (returndata.ok) {
**products = returndata.dataNames;**
//var tempProducts = returndata.dataNames;
$('#select-product').autocomplete({
delay: 0,
minLength: 1,
source: returndata.dataNames,
select: function (event, ui)
{
$.ajax({
type: "POST",
url: sitesURL,
data: { "productID": selectedProductID, "siteID": secondLevelSiteKey },
async: false,
success: function (returndata) {
if (returndata.ok) {
//products = tempProducts ;
**sites = returndata.dataNames;**
$('#select-site').autocomplete({
delay: 0,
minLength: 1,
source: returndata.dataNames,
select: function (event, ui) {
$("#select-site").val(ui.item.label);
});
}
});
}
}
});
}
it throws "Object doesn't support this property or method" exception at (products = returndata.dataNames;) line...at first I thought it can not see the products vairalble, but then I realized that it can see the "sites" variable, so I commented the products line and expected that it would throw the same exception at the sites line, but it works just fine.
I have tried creating a local variable and store the returndata.dataNames in it instead of products vairalbe and then set products value before the sites line, but still it throws an exception. I tried to put the products line after the sites lines it threw the same exception at the products line also.
Help!
After searching and searching, I finally found my solution. Tested with IE8.
Override
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
jQuery.ajaxSettings.xhr = function() {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) { }
jQuery.support.cors = true;
}
}
Make the ajax request
$.ajax({
type: 'GET',
url: "your-url",
async: true,
cache: false,
crossDomain: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json'
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('ERROR: ' + errorThrown);
})
.always(function() {
// Do stuff
});
For me this answer helped, where I detect the IE browser and if its lower than 7 or so then set ActiveXObject else XMLHttpRequest.
jQuery.ajaxSettings.xhr: function() {
// detect if IE and older versions of IE
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 7)
return new ActiveXObject("Microsoft.XMLHTTP");
else
return new XMLHttpRequest();
}
Reference:
Detect IE 7 or lower.
Difference between ActiveXObject and XMLHttpRequest.
Related
I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).
In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}
I have an AJAX call in cordova application.I have checked the availability of internet connection before actual call. But some times in mobile internet connectivity is lost for few seconds after the call is made and thus device does not read any reply from web-service. It goes to error part of Ajax call. I wants to make this Ajax call again so that DOM should get created
call AJAX function is
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if(isOnline == false)
{
alert('Internet is not running. Please reconnect and try');
return 0;
}
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
// alert(JSON.stringify(response));
errorFunction(response);
}
});
}
If you want to retry after an error, you can just re-call your function recursively, or do something like this to prevent too many retries:
function callAjax(type, mainurl, dataType, data, successFunction, errorFunction){
if (isOnline == false) {
alert('Internet is not running. Please reconnect and try');
return 0;
}
function tryAjax(retryCount) {
$.ajax({
crossDomain: true,
async:false,
type: type,
url: mainurl,
dataType: "json",
data: data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data) {
successFunction(data);
},
error: function(response) {
if (retryCount > 10) {
errorFunction(response);
} else {
tryAjax(retryCount + 1);
}
}
});
}
tryAjax(0);
}
I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}
I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.