I load data set by Jquery AJAX as
$(function(){
$('#next').submit(function(e){
e.preventDefault();
var form = $(this);
var page = form.attr("action")
$.ajax({
type: 'POST',
url: page,
success: function(html){
$("#results").append(html);
}
});
});
});
The form is a single button with action="load.php?page=2".
When pressing submit button of the form, it will load data from load.php?page=2. How can I remember this action to load data from load.php?page=3 upon next click? and reading subsequent pages?
In fact, I want to introduce a new variable for the page number will be increased upon every click.
I would use an RegEx to slice the number from the end of the action attribute and replace the action in the success handler with the incremented page number.
I've also changed the line b.attr("action") to form.attr("action") as I think that is a typo in your version. If not stay with the original version of that line :)
$(function(){
$("#next").submit(function(e){
e.preventDefault();
var form = $(this),
page = form.attr("action"),
page_nr = (/\d+$/.exec(page) || ["2"])[0];
$.ajax({
type: 'POST',
url: page,
success: function(html){
form.attr("action", page.substring(0, (page.length - page_nr.length)) + (+page_nr + 1));
$("#results").append(html);
}
});
});
});
Example: http://jsfiddle.net/WfrU7/
you could just set a javascript var to represent page and then increment it on submit...
var page = 1;
$(function(){
$('#next').submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST',
url: page,
success: function(html){
$("#results").append(html);
page += 1;
}
});
});
});
I don't know what your original page var had in it, but obviously you would tailor this response to fit your needs. your url param would not just be a single number, obviously, so update that part as you need.
The best way to handle these "need to keep history of" is, believe it or not, a dom element. We get so tied to programming, variables, and literals that we just forget the simple side of things. And, apparently, simple is what no one has in mind.
So, the "simple" solution is on the script of the page being loaded, save your querystring parameter (page=2 ... the 2) on a
<span id='curPageNumber' style='display:none; '>
in the loaded page. In the next call, all you have to to is, for example, onSubmit='functionSubmit(); ' and
function functionSubmit() {
var action="load.php?page="+$('#curPageNumber').text()*1+1;
$('#formID').attr('action',action);
$('#formID').submit();
}
Related
I am using window.history.pushState() to change the url of the page and put it in the history list, everything works but I have a problem, if for example in a page I execute an operation (ajax), which changes the values in the db and textually update a part of the page, if I browse elsewhere and return to this page, I find what was originally there and not the changes made, to see them correctly I have to refresh the page.
I don't currently use any caching systems
Some contents are loaded with ajax others are directly on the page
window.history.pushState() is used only in the home page in the others I don't need it even if it happens on all
in the example page I have this code
function init() {
$('#weekDays').on('show.bs.modal', function(event) {
var modal = $(this);
$.ajax({
type: 'post',
cache: false,
url: '/my_account/get_giorni_chiusura_sett',
dataType: 'html'
}).done(function(data) {
modal.find('.modal-content').html(data);
});
});
$('body').on('click', '#save-closing-days', function() {
var dataString = $('#form-weekdays-close').serialize();
$.ajax({
type: 'post',
cache: false,
url: '/my_account/set_giorni_chiusura_sett',
data: dataString,
dataType: 'json'
}).done(function(data) {
if (data.update === 'ok') {
var daysClose = $.map(data.giorni, function(v) {
return '<strong>' + v + '</strong>';
}).join(' - ');
$('#list-days-close').html(daysClose);
$('#weekDays').modal('hide');
}
});
});
}
when I arrive in the page the content is loaded without ajax and generated by php, the first function loads the content in the modal upon opening, the second one saves / updates the data on the database and updates the text on the DOM
Closing days: Saturday - Sunday
Update and become
Closing days: Sunday
Now I move to other pages from the menu and back, but I find it again:
Saturday - Sunday
If I reload the page, the data is updated
The History API doesn't maintain the state of the DOM for you. You need to do that yourself. MDN has a good guide but the short version is:
When the user clicks a link then your JS should prevent the default behaviour and call pushState to change the URL and use DOM methods to update the page to match what the server would send for that URL.
When the user presses the back button in their browser and a popstate event fires then your JS should read the URL (and state data if applicable) from the event and using DOM methods to update the page to match what the server would send for that URL (i.e. undoing the changes from the previous paragraph).
There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.
I recently started learning javascript, and I'm currently trying to make a small script to automate a login procedure by filling the user name/password fields, and then clicking the 'Submit'-button.
My code is as follows:
window.open("");
document.getElementById('ctl00_Username').value = "XXXX";
document.getElementById('ctl00_Password').value="XXXX";
document.getElementById('ctl00_ButtonLogin').click();
If I run it once, the site is opened but no text fields are filled.
If I run the code twice (when the site is already opened) the login is successful.
I tried putting "console.log" after "window.open", but for some reason that never seems to get called.
What might I be doing wrong?
Edit: Removed unnecessary code. I am also no longer sure that the document-object actually points to the newly opened window. Calls to "console.log" and "alert" don't seem to do anything, either.
Is it possible to get the correct document-object from the window?
Is it even possible to use "window.open" and then access the new document-object?
Help would be greatly appreciated!
A reference to the window is returned from the window.open call, you can use it to modify the window.
win=window.open(...);
win.document.doYourThing
You also probably need to wait until the document is ready (aka loaded). Using jquery below
$(win.document).ready(function() {
//the document is loaded by here, this is probably where you should do your stuff.
});
1.Pass your values as query string. Example: www.test.com?username=bro&password=bro.
2.On the other page paste the below code.
$(function () {
$(document).ready(function () {
var amount = $('money').val();
var from = "INR";
var to = "SGD";
$.ajax({ type: "POST",
url: "WebService.asmx/CurrencyConversion",
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var money = $(".money").val();
$(".money").replace(money, data.d);
}
});
});
});
3.Now paste this code too.
var uname = getUrlVars()["username"];
var psw = getUrlVars()["password"];
4.You will be having values in the above variables.Enjoy doing whatever you want.
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();
}
});
I am pretty new to this, so go easy on me:
I am building an image gallery with a main index page which allows users to select different categories of projects, a sub-index page which allows users to select specific projects within their selected category, and then the gallery page for that project.
The code below is for the main index page. I am trying to pass the value of the src attribute of the first image of the first gallery page to the main index page to use as a thumbnail.
I have effectively been able to load the correct URL into the imageLoc variable, but I need to pass it outside of the Ajax request to pass it into my HTML document.
Simply put, I am trying to pass the value of the imageURL variable to the imageLoc variable.
Thanks for your help.
$('.galleryIndex a img').hide().each(function(){
var destination = $(this).parent('a').attr('href');
var imageLoc = $.ajax({
url: destination,
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src');
return imageURL
}
});
}
});
alert(imageLoc);
});
This will cause troubles do to the way the callback function is handled. It's a closure block that is called after the request has returned, so it runs apart from your main code in the function. If you want to alert the imageURL variable, alert it inside the callback function, or call another function to handle it. Since it is a callback function for an asynchronous server request, the part that alerts "imageLoc" will have run long before you ever get your async request back.
Edit: The only way to achieve what you're trying to do is to not make the ajax request asynchronously. If you set async:false, then you can call on the "responseText" property like this:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
But be warned...this will halt browser operation while the request is pending. It's usually best to block user interaction by other means if you don't want them to screw with the page while something is loading.
I was able to get what I wanted as follows:
$('.galleryIndex a img[id!="fp"]').hide().each(function(){
var destination = $(this).parent('a').attr('href');
$.ajax({
url: destination,
context: $(this),
success: function(data){
var pageLoc = $(data).find('.galleryList a:first').attr('href');
$.ajax({
url: pageLoc,
context: $(this),
success: function(data){
var imageURL = $(data).find('.galleryBox img:first').attr('src'); //returns the src for the thumbnails
$(this).attr('src', imageURL);
$(this).load(function(){
$(this).show();
});
}
});
}
});
});