The script called New script is suppose to output 2 integer variables anchor and signed.
I would like to replace Old script with New script, but as you can see, they are very different.
Question
How do I submit/post anchor and signed in New script?
New script
$(window).load(function() {
$('form').delegate('input:submit', 'click', function() {
var anchor = this.name;
var checkboxState = $('#' + anchor).find('input:checkbox').is(':checked');
var signed = 0;
if (checkboxState == true) {
signed = 1;
}
alert(anchor + ' ' + signed);
return false;
});
});
Old script
// sends the form content to server side, and stay on page
$('form').live('submit', function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
// do something here on success
}, 'json');
// don't redirect
return false;
});
HTML
<form action="/cgi-bin/receiver.pl" method="post">
Put this
$.post($(this).prop('action'), {anchor: anchor, signed: signed}, function(response) {
// do something here on success
}, 'json');
in place of alert
Here is the proper one, and running ok.
http://jsfiddle.net/ergec/pJgyu/16539/
Related
I made an ajax website calling pages from /pages folder inside an ajax-container div in my index.php.
Now i want to make a second ajax request after the first ajax request success but the second request will be only on certains page,
for example: i call the page work.php and inside this page i want to call a page work-slider from the same folder and replace the work.php page by work-slider.php in my ajax-container div when i click on images link-in
but i can't find a solution for make it,
This is my actual code:
index.php:
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.php";
}
} else {
include $d . "home.php";
}
?>
</div>
Ajax function:
var afficher = function(data) {
$('#ajax-container').fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: f$.ajax({
url: "pages/" + page,
cache: false,
success: function(resultFirst) {
afficher(resultFirst);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
$.ajax({
// How can i define pageIn variable ??
url: "pages/" + pageIn,
cache: false,
success: function(resultSecond) {
afficher(resultSecond);
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
// link inside index.php
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
// second link inside called page
$('.link-in').bind('click', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});
If that .link-in tag if dinamically inserted into the DOM after the page loads, the bind() method will fail: bind() attach listeners to elements it find when called. If you add a new elemenent after the bind call, it will not receive the listener binding.
In order to prevent that when dinamically inserting html code in a page, you should use the on() method:
$('body').on('click' , '.link-in', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});
And now, every .link-in tag you push dinamically inside body will respond to the click listener. A discussion on using on() by default instead of bind() is in fact found in the bind() documentation.
So I have a one page site, that only shows a login with username and password.
I have the $.ajax fire on the submit click.
What I want is for it remove the login box and load in the page that will have all the content ready for the ajax content to go into.
$.ajax function works and was tested by alert(n); the number for my json array.
What happens is after the box disappears and the page loads, it reverts back to the login box.
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
});
});
This is a pretty common problem. When you bind to a submit event, you are effectively able to run some logic, but unless you stop it, the event will continue to propagate and will also run the normal submit logic, which causes a full page refresh. This is fairly easy to prevent:
$(document).ready(function() {
$('#launchform').on('click', function(e) {
e.preventDefault(); // Add this
});
});
As stated in another answer, you can also return false;. That is sometimes a better way to do it when using jQuery as it effectively cancels everything. Although, in non-jQuery solutions, it doesn't stop the event bubbling. You can read more details about why here: event.preventDefault() vs. return false
If you are performing this within a <form> element then the form is probably submitting after the ajax call and reloading the page. Try adding:
return false;
to the end of the click event function to prevent the form submitting.
So the above code would look like:
$(document).ready(function() {
$('#launchform').click(function() {
$.ajax({
url: 'campaign.json',
dataType: 'JSON',
type: 'GET',
success: function (data) {
console.log(data);
var string = JSON.stringify($('form').serializeArray());
var login = JSON.parse(string);
var username = login[0].value;
var password = login[1].value;
var n = '';
for (var i = 0; i < data.result.length; i++){
if (data.result[i].name == username){
if (data.result[i].id == password){
var n = i;
}
}
}
if(n!=='') {
$(".container").remove();
$("#loginfade").load("test.html");
} else {
alert('Invalid Username/Password Combination.');
}
}
});
return false;
});
I understand that I can get the facebook id by doing:
FB.api('/me', function(response) {
alert('Your id is ' + response.id);
});
However, I want to have the user login and then grab that id in a different file so I can handle it. Right now I have:
var id = "";
var fburl = "http://graph.facebook.com/" + id + "?callback=?"
$(function(){
$("#fb-profile-picture")[0].src = "http://graph.facebook.com/" + id +"/picture";
$.getJSON(fburl, function(data){
console.log(data);
$("#name").append(data.name);
$("#user-id").append(data.id);
});
});
and if I manually enter the id in the id var it works however I'd like to be able to grab that response.idas the value and use it in this other javascript file but I haven't figured out how to.
Assuming you
cannot control which of the scripts is executed first
you are working in an environment with a global window object
part one is only executed once
you are using jQuery
making a global and firing an event might be a solution, although not considered best practice.
Script 1:
FB.api('/me', function(response) {
window.fbCustomId = response.id;
console.log(window.fbCustomId);
$(window).trigger('fbResponseLoaded');
});
Script 2:
function renderProfile() {
var fburl = "//graph.facebook.com/" + window.fbCustomId + "?callback=?"
$(function () {
$("#fb-profile-picture")[0].src = "//graph.facebook.com/" + window.fbCustomId + "/picture";
$.getJSON(fburl, function (data) {
console.log(data, window.fbCustomId);
$("#name").append( $('<span>').text(data.name) );
$("#user-id").append( $('<span>').text(data.id) );
});
});
}
if (window.fbCustomId) {
renderProfile();
} else {
$(window).on('fbResponseLoaded', renderProfile);
}
I have a form and after user is successfully filled the form I want the actual message
to "bounce" from the top about 30px and show the actual message. The problem is that my
form's height is huge, about 900px so I'll never see the actual message unless I scroll on top of my page which is impossible because the page reloads itself after 3 seconds. How should I implement this? Here's my AJAX code for now:
<script type="text/javascript">
$(document).ready(function() {
// Process the form with AJAX
$("form").on('submit', function(e)
{
e.preventDefault();
var from = $("form");
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
}).done(function(data) {
if(data.result == 0) {
$("#new_survey_success").hide();
for (var key in data.error) {
var value = data.error[key];
var output = '<p>' + value + '</p>';
}
$("#new_survey_error").fadeIn(1000).show().html(output);
}
if(data.result == 1) {
$("#new_survey_error").hide();
$("#new_survey_success").fadeIn(200).show().html("<p>" + data.success + "</p>");
window.setTimeout(function(){location.reload()},3000)
}
}, 'json');
return false;
});
});
</script>
Thanks in advance!
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be and how can I solve this issue? I do not want to use any plug-ins either.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
When you reload the page, the reason that the results are missing is because they aren't in the document source; they've been added to the DOM later.
I reckon you have two choices, the first of which I generally use.
When you execute your search, have either the search criteria or the search results stored at the server so that when the page is next rendered, the results are rendered with it. I use ASP.NET MVC 3 and do this using a PartialView. When I use jQuery to execute the search, it causes the server to render the same PartialView and inserts the resulting HTML fragment into the results div.
Alternatively, you need to fire your jQuery search again when the page is reloaded.
Whether it's better to resubmit the search or to cache the results depends on how expensive the search is and how big the result set is likely to be.
The hash should stay after the reload of the page because it is part of the browser history.
So you can parse document.location.hash to gain knowledge about the selected query type and search.
//$(function() {
if(document.location.hash) {
var hash = document.location.hash;
var split = hash.split('/');
var queryType = hash[1];
var searchTerm = hash[2];
$('#type_'+queryType).addClass('selected');
$('#query').text(searchTerm);
$('#query').keyup();
}
//});
behind your setup routines.