jquery and page reload - javascript

I have this code in my asp.net webform, I call a webmethod to load data from database:
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url: "index.aspx/Iniciar",
data: JSON.stringify({}),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
$("#wait").hide();
var result = response.d;
cargardatos(result );
}
});
}
I call this function in ready event:
$(document).ready(function () {
Inicializar();
});
the first time it works, the problem is that when I press F5 and reload the page data is not loaded, and if I press back working again.
I do not know if I'm doing something wrong.
Sorry for my English..Xd
Thank you. Greetings!

JavaScript is CaSe SenSitIve. So change your code to:
$(document).ready(function () {
Inicializar();
});
But this way, it doesn't even work on the first time. And do check what is wrong with your output using the Network or Console.
Disable Caching if Needed
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
})

Turn off caching
function Inicializar() {
$("#wait").show();
$.ajax({ type: "POST",
url : "index.aspx/Iniciar",
cache : false,
datatype : 'json'
}).done(function (response) {
$("#wait").hide();
cargardatos(response.d);
});
}
$(document).ready(function () {
Inicializar();
});

Related

How to show loading icon when queries are executed in background?

I have AJAX request which runs when user click the button. I want to show loading icon during the execution of AJAX request. I used next code but it works not as I expected.
Let me try to explain the situation. When user click the button, in terminal I notice requests in the same time user don't see loading icon. When all requests are completed in terminal I see 200 OK status. Only after that I see icon but for shot time. So my question is how to show icon when queries are executed in background?
$("#btn").click(function(){
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
})
.always(function (dataOrjqXHR, textStatus, jqXHRorErrorThrown){
$('#loading-icon').fadeIn();
})
.done(function (data, textStatus, jqXHR) {
$('#loading-icon').fadeOut();
});
});
Your code in the always() handler will be executed once the request completes.
Start showing the loading icon before sending the request:
$("#btn").click(function(){
$('#loading-icon').fadeIn();
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
})
.done(function (data, textStatus, jqXHR) {
$('#loading-icon').fadeOut();
});
});
You create Simple funcetion like:
function loader() {
if ($('#dv_Loading').css('display') == 'none') {
$('#dv_Loading').fadeIn("slow");
}
else {
$('#dv_Loading').fadeOut('slow');
}
}
Use This funcation like:
$("#btn").click(function(){
loader();
$.ajax({
url: "some url adress",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: jsonData,
success: function (data) {
loader();
}
});
});
Try this one
https://stackoverflow.com/questions/48611821/how-to-show-a-hidden-element-with-jquery/48611918#48611918
I hope works fine atleast for me
Similary in your case,
$("#btn").click(function(){
$.ajax({
url : "URL",
data: { data },
beforeSend: function(){
$("#loading-icon").show();
},
complete: function(){
$("#loading-icon").hide();
},
success: function (response) {
});
});
});

Display page only if ajax call succeeds?

I have a subdomain protected by a service similar to cloudflare. It checks if a visitor is human or not. To save bandwidth usage I want only one file to be loaded from this subdomain as indicator if the visitor is a bot or not. If it is not loaded, the service has blocked it as bot, and nothing should be shown.
I already thought of an ajax request before the page loads to check this.
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html"
});
request.done(function() {
// Load page, because the request was successfull
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
dataType:'json', // add json datatype to get json
data: ({load: true}),
success: function(data){
console.log(data);
}
})
});
Is there a better way to do this?
You may try this:
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html",
success: function(){
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
data: dat,
success: function(data){
console.log(data);
},
error: function(data){
console.log('Error!');
}
});
},
error: function(data){
console.log('Error!');
}
});
}

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

Ajax not being called in javascript function

In the success function I want to call a function. The problem is that ajax does not fire, so the data is never triggered and display. Here is my ajax call with a javascript function call in the success function.
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
window.location = "api/home.php";
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: handleData
});
}
function handleData(data) {
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
}
I cant figure out why the ajax in the retrieveUserBlogData() function is not being triggered.
Any help would be appreciated Thanks.
Even if the AJAX succeeds, you are redirecting the browser to a different page after the first AJAX request:
window.location = "api/home.php";
So I would suggest removing that.
Try the following code for redirecting to another window
window.location.assign(URL);
then it may work.
Try it like this
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: function(data){
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
window.location = "api/home.php";
}
});
}

AJAX request not working properly

Hey guys and gals,
I have a form that I would like to use AJAX to submit. For the callback function basically what I want to happen is, the form elements disappear (.hide) and are replaced by a div element (which will ready success or something of that nature). I then want the function to pause for 5 seconds and then redirect to a different URL.
The AJAX request successfully submits (as I receive an e-mail to the specified address as I should) but the callback function is not carrying out properly. Any suggestions?
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(5000);
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
}
})
}
}
**
UPDATE #1
**
This is the only error code that I am getting when I initially load the website (I've heard these errors only pop up in the dev tools and do not affect the user?)
But then when I submit the form I get this error code
I've also updated my JavaScript to the below code, taking advice from a few people who posted, it's still not working 100% though
$(document).ready(function() {
var $form = $('form');
$form.submit(function(){
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
}
});
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000)
});
});
Joey
setTimeout usage is wrong.
See :
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000);
}
})
}
});
Further, the following should ideally be declared separately, if you want the user to click a link and go after ajax success.
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})

Categories

Resources