How to ajax post on URL parameter change without page refresh - javascript

Depending on the change in URL parameter my values in the html changes. So basically i am passing these values to a json file. Since the page is refreshing because of the post my values are getting erased.I tried event prevent default, but its not working for me.
var carryOver ={"Jan":"","Feb":""};
var parameters = getParameterByName('month')//gets the current URL parameter
if(parameters == '01-2017'){
$('#monthQuota').html(janQuota);
carryOver["Jan"] = 300;
}
else if(parameters == '02-2017'){
carryOver["Feb"] = 400;
}
$(function() {
$('parameters').on('change', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "utilization-2017-test.php",
data: {
json: JSON.stringify(monthBalances)
}
})
})
})

sir, javascript or jquery can detect the #(hash)change but not the parameter change.If you clicked on a link and #tag changed then the script or event will detect that and page will not get reloaded but to change parameters you are going for an entry in the browser Url, so your values getting refreshed.
So please do one thing that keeps a text box and enter values in that then you get the value from textbox and go for service call instead of taking input from URL

Related

My recaptcha render doesn't work and return 0

I currently have a problem with Google's Invisible Captcha.
It refuses to load properly despite all my attempts.
The situation:
I have a form which is added to the DOM via jQuery when clicking on a button. The form is then displayed in an overlayer which covers the entire screen.
At first, no worries but once the form is displayed, I try to render the captcha without success, which prevents doing the execute and thus using the captcha on the form.
Here is the insertion code of my form (which works):
$('.js-event-subscribe').click(function(e){
e.preventDefault();
var event = $(this).data('event');
clearTimeout(ajxTimeout);
if(typeof ajx != "undefined")
ajx.abort();
ajxTimeout = setTimeout(function(){
ajx = $.ajax({
type: 'POST',
url: langPath + '/ajax/event-subscribe/',
data: 'id='+event,
success: function(content){
if($('body').find('#js-event-subscribe').length)
$('body').find('#js-event-subscribe').remove();
$(content).insertAfter('footer');
$('html, body').addClass('opened');
//var test = grecaptcha.render('js-recaptcha-event');
//console.log(test);
//grecaptcha.execute('js-recaptcha-event');
}
});
}, 500);
});
So far it works, the form is correctly added and functional.
The grecaptcha.render (according to the documentation) should return the widgetID but reply 0.
The "js-recaptcha-event" parameter corresponds to the ID of the DIV captcha in the form (added to the DOM therefore).
<div id="js-recaptcha-event" class="g-recaptcha" data-sitekey="xxxxxxxxx" data-size="invisible"></div>
Therefore the grecaptcha.execute ('js-recaptcha-event') returns an error
Uncaught Error: Invalid site key or not loaded in api.js: js-recaptcha-event
I tried adding the sitekey in render parameters with the same result. :(
The recaptcha API is loaded via (also tested with async & defer in attributes)
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
Can you tell me what I need to make it work?
Thank you in advance
As far as I know 0 is a valid response to the render event, i.e. the widget ID is an integer starting at 0 for the first widget rendered.
As render is explicit, I would take the approach of specifying all the parameters in the render event:
widget = grecaptcha.render(captcha, {
'sitekey': 'xxx',
'callback': function(token) { ... },
'badge': 'inline',
'size': 'invisible'
});
Given your error response, I would triple-check that your site key is correct, and that it corresponds to the correct entry in your reCAPTCHA admin console, where the domain you are loading from needs to be specified.
Ensure the code for rendering the widget is loaded before the reCAPTCHA script loads.
I would suggest you render the reCAPTCHA immediately on the form appearing, and then execute it upon clicking submit. That may also resolve the issue.

Retain javascript data while Forward and Backward browser button click

I have following dropdown which calls javascript showTable method.
<select name="any_name" id="any_id" onChange="showTable()">
I have following showTable method which calls a php method via post to populate data in my showData div.
function showTable()
{
$.ajax({
type: "POST",
url: "sample.php",
data: {"Id" : myId},
success: function (data)
{
document.getElementById("showData").innerHTML= data;
}
});
}
It works fine. Now the problem arises when I hit FORWARD and then BACKWARD browser button. On hitting BACKWARD button, I get my previous page but my showData div is empty. How can I retain data in this div which I got from my PHP script? I think I have made it clear what I want to ask.
Look for local storage w3schools.com/html/html5_webstorage.asp and manage to save and retreive values between your back/forward behavior.
;)

How to store/remember the data fetched from ajax call?

I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}

Using the value recieved from within a click handler that is inside a ajax request outside the function

It was suggested that I try to explain my problem with no code so here it goes. I have a webpage that lists a bunch of links with project names as seen in this jsfiddle. What I want to do next is display a second webpage after a project link is clicked by a user. The second webpage would need to make a second ajax request like in this Second page jsfiddle to get new information to display a project summary, citations and names for that particular project. The part that's killing me is the ajax request for the second page currently has a number 504216b6e4b04b508bfd333b in the url which means it will only use that project for the second page to display summary, citations and names. I need that ajax request to take a variable for any id number. However to compound the problem the id number comes from a user clicking a link on the first page. So my problem is getting the value of the id once a link is clicked and putting it into the ajax request for the next page. I have all the work done for what the pages will display but I can't get the value from the one file to the next. Any help is appreciated, Thanks.
wouldn't let me save without putting some code so this is just the bare bones,
// The ajax request is in another file but it works good
promise.done(function (json) {
// Make some links
// Which link was clicked? I need to see some id please
$('#sbItems a').on('click', function (e) {
e.preventDefault();
// Do stuff to find the id for the link the user clicked
// Assign the id to a variable that I can use in the next ajax request
// that is called in a seperate file
testId = json.items[itemId].id;
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
second file has,
// Need to somehow, someway get the testId variable that holds the id
// into this file
var url = 'https://www.sciencebase.gov/catalog/item/ + THE TESTID + ?format=
jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
complete: onComplete,
success: function(json) {
// Display some stuff based off this url
}
});
If you're trying to get a number from the first page and into the second page when you click a link that takes you to the second page so you can use it in the second page ajax call, then there are several options:
Attach the value onto the URL when requesting the second page as a search parameter like this: http://www.sample.com/mypage?id=504216b6e4b04b508bfd333b. The in the second page, parse that id value out of the URL and use it for your ajax call. This is the safest of these three options because it works properly even if the user has multiple windows open clicking on different pages in your site.
When clicking on the link in the first page, store the id value as a cookie. In the second page, retrieve the id from the cookie.
Same as option 2, but store the value in local storage.

POST using XMLHttpRequest with existing source

What I am trying to do only using XMLHttpRequest, is this:
The script downloads a web page, that has only one form in it.
The script inserts text into a field.
The script submits the form, while keeping all details about input tags.
I did the first part, but I have no idea how to finish with the next two steps.
Note: I do not have control over the page downloaded, and it is not well-formed XML/HTML.
Could someone explain to me how I can get this done?
This is for a Google Chrome extension, so I have all permissions needed.
EDIT: this is my current code:
$.ajax({ url: "http://www.mysite.com/my/testpage.aspx",
type: "POST",
data: {
html: http0.responseText.between("<body>", "</body>")
},
success: function(data) {
var dom = $(data),
form = dom.filter('form');
form.attr('onsubmit', 'document.getElementById("error").value = "I\'m done!"; document.getElementById("helpmebutton").disabled = false;');
form.attr('action', 'http://www.mysite.com/my/testpage.aspx');
$('#tempdiv').append(form);
form.find('input[name="ctl00$ctl00$cphSite$cphMySiteContent$linkLocation"]').val(document.getElementById("result").value);
form.submit();
}
});
I would really use jQuery to save yourself time and headaches.
Create a temporary div with id tempdiv and put everything in that div. Then, fill in appropriate elements and submit the form, like this:
$.ajax({ url: "http://...",
success: function(data) {
var dom = $(data),
form = dom.filter('form');
$('#tempdiv').append(form);
form.find('input:text').val(123);
// all input[type=text] get value 123
form.submit();
}
});

Categories

Resources