How to write code inside ajax without xhr - javascript

I have a code like this before:
<script>
function()
{
//*code*
fxajax.sendData
({
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
But my manager wants me to put my code inside the ajax so i put it inside beforeSend
<script>
function()
{
fxajax.sendData
({
beforeSend: function()
{/*code*/}
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
My problem is beforeSend is not executed but url, data, success and error works fine. Then I think maybe its because I don't have an XHR request.
Any idea how I should implement this code?

Here is a simple way
$(document).ready(function(){
// set a 1 second to fire ajax request
setTimeout(function () {
// url of the image
var url = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg';
$.ajax({
url : '', // url request
type : "GET", // type of request,
beforeSend : function () {
var i = new Image();
i.src = url;
i.onload = function () {
// change it to div
$('div').append(i);
}
console.log("ajax is firing");
},
success: function () {
},
error : function (xhr, txtstatus, text) {
console.log(txtstatus);
console.log('error');
// any error from request
}
});
}, 1000);
});
Here is a simple DEMO

Related

Jquery Ajax Upload with progress is reloading page

I have strange stuf with a Jquery form submit.
After the upload completed, the page is reloading even in the server has not finished to process.
The server just return a json succes status, so It's not on server side.
Here"s the code:
$form.on('submit', function (e) {
console.log('Submit form ' + fileNumber);
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
e.stopPropagation();
var ajaxData = new FormData($form.get(0));
var $input = $form.find('input[type="file"]');
if (fileToUpload) { ajaxData.append($input.attr('name'), fileToUpload); }
console.log('FileTo Upload: ' + fileToUpload);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: 'json',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
},
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr,settings) {
},
complete: function (xhr, status) {
xhr.
//$form.removeClass('is-uploading');
//fileNumber++;
//fileToUpload = droppedFiles[fileNumber];
//if (fileToUpload) { $form.submit(); }
},
success: function (data,status,xhr) {
//$form.addClass(data.success === true ? 'is-success' : 'is-error');
//if (!data.success) $errorMsg.text(data.error);
},
error: function (xhr,status,error) {
}
});
} else {
// ajax for legacy browsers
}
});
The issue is here:
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
If I remove return myXhr The page is not reloading after upload, but I have no progress report.
I don't know what to do to prevent reloading.
Thanks.
I found out the issue.
There was no worry with the xhr object.
The issue was coming from Visual Studio Browser Link.
After shuting it down, everything worked perfectly.
Browser link, for an obvious reason was fire a reload of the page.
Will see with the ASP.NET Core team
try change buttin type submit to button and implement click function
eg:
$( "#buttonID" ).click(function() {
//your code
});

MVC5 Ajax update

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

How to finish loading condition that a function to execute another function in jquery?

I have the following script to add a new value to the array of my session variable, and show me the varible totally live session
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
});
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (data) {
session = data;
alert(session);
});
});
}}
})( jQuery );
the problem is that the POST shipping takes longer than the call GET ALERT then shows me the session variable not updated.
Is there a way to put an IF condition for shipping only when POST is complete return the response I GET?
thanks
Actually, what you want do do is to use a callback - that is, a function that is called as soon as your POST ajax request returns.
Example:
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
})
.done(
//this is the callback function, which will run when your POST request returns
function(postData){
//Make sure to test validity of the postData here before issuing the GET request
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (getData) {
session = getData;
alert(session);
});
}
);
});
}}
})( jQuery );
Update per Ian's good suggestion I've replaced the deprecated success() function with new done() syntax
Update2 I've incorporated another great suggestion from radi8

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources