I will try to walk you through this very slow. I am trying to make a poll that are subject to change often so I have to make it dynamical. I also need to have this without page reload, so I would need to use Ajax to submit the form. So what I did was to create a PHP script that will echo the poll for me. This works nicely and I get the poll just the way I want it. Oh yeah, forgot to tell that it is a multi step poll. I navigate through 2-4 questions at a time by hiding/showing divs within a JQM 'page'. And by that I mean:
<div data-role='page'>
At the last page I do have a submit button instead of a next button since the poll obviously has no "next" div to show. This submit button does in no way, shape or form work, and thus is the issue here.
$("#submit").click(function()
{
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
}
else
{
return false;
}
})
This is supposed to send my form data to another PHP file that is named add.php, when then is supposed to post it to the div shown abit underneath. (It's really supposed just to save to database but I try to echo it until I see that it works). Now, the twist is that I did another identical piece of code on a non-dynamical form that was not created through PHP, but merely plotted down in HTML. This was also a multi step poll that span out over 3 divs/'pages'. And this had no problems submitting at all.
So to summarize: I had 2 different projects that each handled half my problem. One generated the form dynamically and the other saved a static form that I made. Both forms consisted of a variety of checkboxes, radiobuttons and textareas. Problem is, they won't work together. When I click the submit button I expect the form to echo out the answers into this div (the one you read about a few lines up):
<div data-role="content" id="answers">
Answers comes here:
</div>
Nevertheless, this div remains the same. I stripped down the $("#submit").click(function()) to alert('test'); and I still could not get a reaction. I've quadrillion-checked the variable names and div names and any other names that are relevant, and I've made various minor adjustments on each separate part (both generating the poll and posting it with ajax) as well as to my attempt to combine them without success. So, the million dollar question is what could be wrong? My last remaining hypothesis is that somehow the JavaScript function for $("#submit").click ... is loaded before the script that generates the poll. This would make sense that when the submit click function is declared it would not be linked up to any button like shown here:
<input type="button" id="submit" name="Submit"/>
Does anyone have any clue on how I can make this submit button to work, or even have a clue as to why it does not work? Thanks to anyone who read this far and I hope you posess and are willing to share some knowledge that could help me. Also thanks to the creators of Stack Overflow for implementing an alt+z function for this as I accidentally clicked alt+a then random letters while writing the sentence before this one. Have a nice day!
EDIT: Tried this after a tip from Kevin an answer below, but even the first alert button doesn't react:
$("#submit").click(function()
{
alert("it works");
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
return false;
}
});
}
else
{
return false;
}
})
});
You need a return false; under $("#answers").html(response); inside the scope of the success function. Let me know if this works. Good luck, Kevin
I just tried the script above without the post and it worked fine. Do you have jquery loaded before this script executes, and/or do you have or do you have any javascript errors in your console?
Related
I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {
I am working on a survey that will go at the bottom of a FAQ page. My problem is that everytime a form is submitted, it sends you to a different page. I was wondering - is there a way to submit the form and have a little message that replaces the survey that says "Thanks for your feedback" instead of sending the user to another page or refreshing the page?
So far, I have a file that contains the HTML form, CSS, and jQuery and another file that contains the PHP connection to database and insertion of data to the database.
I would appreciate an explanation that is dumbed-down and an example would help since I am relatively new to programming.
An important note: My jQuery is set up to automatically submit if a user answers very helpful/extremely helpful. If not, two more questions appear below with a submit button at the bottom.
More specifically it looks like this:
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
$('#questions').submit();
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
What you want is the jquery post function: http://api.jquery.com/jQuery.post/
Make sure your data is JSON.
$("#formdiv").click(function(){
$.post("somepage",{ yourformdata} );
$("#formdiv").replacewith("Thanks for filling out the form!");
});
You can use the replaceWith function to replace the desired content with the thankyou message.
Alex,
from the code you supply, the reason for leaving the page is due to the fact that you don't preventDefault() on the click event. Your page will always reload after that submit unless you take abortive action. No guarantees, but try a quick refactor to:
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
This should get you a stage closer. You then just have the ajax logic to define, which should come good with a quick search to match your needs.
(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});
The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});
Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.
I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response
For a website I'm making for school, I'm trying my hand at using Jquery extensively for the first time, and even though I managed quite a bit so far, I'm stuck at two (most likely related) problems.
I'm aware that the upcoming case is somewhat long, but I feel it's necessary to submit all relevant code for everyone reading this to get a good image of what is happening.
Basically, the website is one index.html file, with the CSS thrown in, a few buttons, and one div with the ID content. I use this code to make this work:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
Then there is one content page, named search.html, which only contains a form that submits a search string to a search.php page (through ajax) that should then place the search results immediately back into a div called search_results in that same search.html file. The jquery that I use for this:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("Functions/search.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
The issue that I'm having is as followed:
Before I had the first line of code: if ($('#content').innerHTML == " "){; implemented, I would open the site, main_text.html would nicely be loaded in, I could navigate to other subpages fine. But typing in something in the form field in search.html did not display any results (just typing should already trigger the function). When I hit the search button on this form, instead of seeing query results, the main_text.html file load again in the #content div. This made me assume that perhaps, somehow, that the code:
$(document).ready(function(){
$('#content').load('main_text.html');
});
was being called again unwanted. Hency why I implemented that check for whether innerHTML existed.
However, now, when I first load the page, the #content div does not load any initial content at all. (The section on the webpage just becomes black, like my page background) I have to click any button to get some content loaded again in my main content div. Also, when I now go back to the search.html, the typing anything to get results, like previously, still does not work. If I now hit the search button, I get the initial result again of what I'd see when I just opened the page: a blacked out #content div.
So somehow, the biggest issue is in the fact that the jquery to get results from my PHP do not seem to work. My problem with the content.innerhtml check might well be obsolete if the issue with the searchresults not displaying in the #search_result div on the search.html is fixed.
Anyone have any idea's what I could do to fix this. Or otherwise, what other approaches I could take for the kind of website I'm making. Since I'm trying to learn jquery here, better approaches are always appreciated, I'd rather learn myself doing this the right way and all. :)
Thanks for your time.
Few things to note here:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
In the above, you are testing to see if there is a space in the innerHTML of the element with an id of content.
jQuery uses .html() or .text() to make comparisons against the data being held within a container, so if you want to maintain using jQuery principles, change this line. Going along the same thought process, you are preparing an IF statement on an element before the document is actually ready and loaded.
You should move the document.ready function to the outside of the if statement. This will allow you to ensure that the element is available at DOM, and you can indeed perform checks against this element.
<script type="text/javascript">
$(document).ready(function(){
if ($('#content').html("")){
$('#content').load('main_text.html');
}
});
</script>
Also, while being readily provided and fully functional, I would recommend starting off using $.ajax instead of $.get / $.post. I have personal preferences as to why I think this, but I won't go into that, it's just that, personal.
$.ajax({
url: "Functions/search.php",
type: 'POST',
data: "search_term="+search_val,
success: function(data){
if (data.length>0){
$("#search_results").html(data);
}
});
Lastly, you should be using the GET method and NOT the POST method. Based on REST/SOAP practices, you are retrieving data from the server, and not posting data to the server. It's best practice to follow those two simple ideas. This isn't because web servers will have a difficult time interpreting the data; but, instead, it's to prepare you for working on larger scale application deployment, or future team-environments. This way everyone on the team has an expectation as to what method will be used for what purpose.
Anyway, long story short, you also leave semicolons off of the end of your closing }) brackets. While this is not an issue, nor will it cause flaws in your development, coding is all about uniformity. You've used the closing ; everywhere else, so try and maintain that same uniform design.
Best of luck.
I am having a couple of problems involving PHP & AJAX using jQuery. To make the whole explanation easier I am going to simply give a link to the site I am working on and if you use the "quote calculator" tab and follow the steps you should hopefully understand my problem
http://bothrealities.very-dev.co.uk/green-it
Just in case you do not, here is an explanation:
When I am clicking on a radio button; the radio buttons in the model section (which calls back data from a PHP file and db through AJAX), the info box to the right does not always populate, sometimes it seems as if the data is stuck in the cache. You can click on a model and then when you click again the model you choose prior populates in the info-box (as if it is one click behind)
Now I am not sure if it is a case of the speed in which the user clicks the buttons, thus breaking to original AJAX call?
I don't know if I need to have the page disable/grey out and have a loading wheel until the data comes back, so users cannot interfere with the process, or not?
Apologies if the above explanation is confusing, I do urge you visit the link above and try it for yourself, it is so much easier to understand that way.
Thank you very very much in advance anyone who can sort this out, I might even pop a small bounty on this post.
Thanks,
Dan.
P.s Am not sure how to add a bounty yet, sorry.
EDIT :::
function productString(product, box) {
$.get("http://<? echo ROOT; ?>includes/forms.php", { product: product }, function(data) {
$("#loadingModel").append(data);
});
$.get("http://<? echo ROOT; ?>includes/forms.php", { box: box }, function(data) {
$("#content-right").empty();
$("#content-right").append(data);
$("#content-right").jScroll();
});
}
function modelString(model, boxModel) {
$.get("http://<? echo ROOT; ?>includes/forms.php", { model: model }, function(data) {
$("#loadingData").empty().append(data);
});
$.get("http://<? echo ROOT; ?>includes/forms.php", { boxModel: boxModel }, function(data) {
$("#boxModel").empty().append(data);
});
}
Sometimes your http://bothrealities.very-dev.co.uk/includes/forms.php?boxModel=1 ends before the http://bothrealities.very-dev.co.uk/includes/forms.php?model=xxxxx has ended so the returned data from the second request isn't what you want to get.
You can try by passing model parameter in the second "GET" too.
"loading wheel" will certainly help out the user (on what's going on).
I haven't looked at the code but here's how you can debug this.
"erase" the box on right before the AJAX call.
in the callback function, use console.log(ajaxcontent) to make sure, you got the intended content from ajax. (this is nice feature of firebug -- a firefox plugin)
update the box.
I hope this helps.