Morning people. How to make my javascript or jquery works in dynamically generated content.
Basically, i have created web page that generates contents, base on what user clicks on the navigation menu.
The problems i am facing:
when main page generate contents from content-page, jquery or javascript won't work.
but when i open up the content-page alone, everything works.
Information collected through searching:
jQuery.load() method ignores the script tag that comes together with the that content generated dynamically.
So i try the following:
Put the tag that i need in main page, not in content-page. it doesn't work. seem like the jquery can't find the content element, because they are dynamically generated.
Since jQuery.load() ignores script tag, I tried pure javascript ajax like how w3schools.com teaches, the xmlhttp way, to generate the content. It doesn't work.
When a button is clicked. no response in console.
Example contact.php
<script type="text/javascript">
$(function() {
$("#submitUser").click(function(e) {
var fname = $("#fname").val();
$("#theresult").text(fname);
e.preventDefault();
});
});
<form id="contactForm">
<label for='fname' >First Name</label><br/>
<input id="fname" type="text" name="fname" maxlength="100" />
</form>
<div id="theresult"></div>
When this contact.php is dynamically generated into other page, it doesn't work. When I click "submit" button, console shows no response. seem like the jquery is not exists.
But when I open it alone in browser, it works.
For dynamically generated elements you should delegate the events, you can use the on method:
$(function() {
$(document).on('click', '#submitUser', function(e) {
var fname = $("#fname").val();
$("#theresult").text(fname);
e.preventDefault();
});
});
live() method is deprecated.
Taking a wild stab in the dark here since your question isn't very well-described, but perhaps you're trying to use .click() and so on to bind events to things that are getting dynamically loaded into the page?
If so, you probably want to look at .on() instead.
You need to use live event.
As an example, if your generated content contain a click event, you could do this:
$(".something").live("click", function({
// do something
)};
For dynamically generated fields use .on() JQuery method:
$(document).on('click', '#MyID', function(e) {
e.preventDefault(); // or you can use "return false;"
});
Related
I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});
My question may sound confusing but actually it's not. Let me clear you the things. The scenario is I've following HTML code:
/*This is the hyperlink I've given for example here. Many such hyperlinks may present on a webpage representing different question ids' */
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21679" title="Fixed" href="#fixedPopContent" class="fixed" data-q_id="21679" id="fix_21679">Fixed</a>
/*Following is the HTML code for jQuery Colorbox pop-up. This code has kept hidden initially.*/
<div class="hidden">
<div id="fixedPopContent" class="c-popup">
<h2 class="c-popup-header">Question Issue Fix</h2>
<div class="c-content">
<h3>Is question reported issue fixed?</h3>
Yes
No
</div>
</div>
</div>
Now upon clicking on this hyperlink I'm showing a pop-up(I've used jQUery Colorbox pop-up here. It's ok even if you are not familiar with this library.) On this pop-up there are two buttons Yes and No. Actually these are not buttons, these are hyperlinks but showing as a buttons using CSS. Now my issue is when user clicks on hyperlink 'Yes' the page is redirecting to the href attribute value and the page reloads.
Actually I want to get to the page mentioned in href attribute but the page should not get reload or refresh. How to achieve this? Following is the jQuery code for colorbox pop-up as well as for Yes and No buttons present on this pop-up. I've tried this much but it didn't work for me. The page is getting redirected and reloaded.
My code is as follows:
$(document).ready(function() {
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$('#fixedPop_url').attr('href', action_url1);
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").click(function(event) {
event.preventDefault();
$("#fix_"+qid).hide();
$("#notfix_"+qid).show();
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
});
So you need to load the page at the url but not navigate to it.
You can use .load() .
So in your case, lets say that your pop container div class is .popup, and the div where you want to load the urls content has an id say #container.
$(".popup a").on('click', function(e){
e.preventDefault();
var url = $(this).attr('delhref');
$("#container").load(url);
});
Few things to keep in mind,
This will mostly not work for urls pointing to any other domain. (Same Origin Policy)
Any content loaded with this function (.load()) shall be inserted within the container and all the incomming scripts if any shall be executed.
You can do that with history.js. Here is an example;
HTML:
Delete
Update
<div id="content"></div>
JS:
var History = window.History;
if (!History.enabled) {
return false;
}
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
$('#content').load(State.url);
});
$('body').on('click', 'a', function(e) {
var urlPath = $(this).attr('href');
var Title = $(this).text();
History.pushState(null, Title, urlPath);
return false;
});
You can see code here: jsfiddle code
You can see demo here: jsfiddle demo
Note: Urls in example cannot be found. You need to update it according to your needs. This simply, loads content in href without refreshing your page.
I have a simple PHP file with some HTML (got a list in the form of UL>LI>UL>LI, which uses the toggle() function. The function opens the ULs and shows or hides the LIs). The page also has an input form that works correctly (adds data to the database).
Once the AJAX form has been successful, I delete the entire div and reprint it from the database.
My problem: once the new page is printed, the toggle() function stops working until the page is refreshed.
The toggle function (in external JavaScript file):
$(document).ready(function() {
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
});
The form:
<form id="addPForm">
<section id="product_input">
<input id="list_add_product" type="text" placeholder="Add a new product" onkeyup="checkProducts()">
<input id="list_add_product_button" type="button">
</section>
</form>
The form sending function:
$("#list_add_product_button").click(function(event){
var txt=$("#list_add_product").val();
$.ajax({
type: "POST",
url: "addproduct2.php",
cache: false,
data: {product: txt},
success: onSuccess,
error: onError
});
// IF THE SUBMIT WAS SUCCESFULL //
function onSuccess(data, status)
{
console.log(data);
clearInput();
$('#main_list').empty();
$('#main_list').html(data);
}
function onError(data,status){
// something
}
});
What I get printed in the console.log(data):
<div class="product_category"><li id="baked" onclick="showBakedList();"><a class="list_text" id="baked_text">Baked [2]</a></li><ul id="ul_baked" class="inner_list"><li class="product" id="bread"><a class="liText">Bread | 0 Unit</a> </li><li class="product" id="croissant"><a class="liText">Croissant | 0 Unit</a> </li></ul>
Now, the toggle() function works great before I add a product. The lists opens and closes without any problems. I do not get any errors in the console and I load jQuery in the page head (first item).
I would like to note that looking at the source code before and after the code print looks exactly the same, except the new additional LI that is printed.
Am I missing something? Do jQuery functions stop working after a div data refresh?
If your element is been removed after click event binding, it will not call the event handler function.
Use $.on() insted of .click():
$(document).on('click', '.product_category', function(event) {
// Your function here
}
Explained:
$(".product_category").click() binda a function to the .product_category elements at that moment. If one or all elements are removed, then the event bind also will be removed.
$(document).on() will bind an event to entire document, and will filter every click to check if the click occurred in a '.product_category' element.
Try this:
$(document).ready(function() {
checkForDOMElements();
});
And a function...
function checkForDOMElements(){
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
}
In your AJAX request, after success add:
checkForDOMElements();
Does this work for you?
The main problem is this:
When you load page you have one DOM tree with all elements. Javascript save this DOM. After this you remove all elements from DOM tree and load new. But for javascript the elements are only removed and js can't detect new elements for your toogle() function..
You have to reload javascript function to refresh new DOM tree (new HTML) with new elements.
I found this solution while having the exact same problem. I am building a complex webtool that uses Ajax/JSON that contains HTML with JS events built into the JSON.
To be more fine grained on the calls, I wrapped each specific JS event that had to do with the specific Ajax/JSON HTML replace and call it on load as well as after the AJAX success.
If there is a more "up to date" way of doing this, I would love to hear about it, but this worked GREAT for me.
Do you know a way to display a php result inside a div dynamically, without refreshing the page?
For example, we have 2 divs: one on the top half of the page and one on the bottom of the page. The top one contains a form with 3 input fields. You type some values inside, then press a button. When you press the button, the bottom div displays the values without refreshing the page.
You can't do it with pure PHP because PHP is a static language. You have to use Javascript and AJAX. I recommend using a library like Zepto or jQuery to make it easy to implement like this:
<form>
<input name="search" />
<input type="submit" />
</form>
<div id="div2"></div>
<script>
// When the form is submitted run this JS code
$('form').submit(function(e) {
// Post the form data to page.php
$.post('page.php', $(this).serialize(), function(resp) {
// Set the response data into the #div2
$('#div2').html(resp);
});
// Cancel the actual form post so the page doesn't refresh
e.preventDefault();
return false;
});
</script>
You can accomplish it using AJAX. With Ajax you can exchange data with a server, make asynchronous request without refreshing the page.
Check this out to see how it can be implemented using Jquery:- http://api.jquery.com/jQuery.ajax/
I have a form inside a DIV (normally the div is hidden using "display:none;")
The user open the DIV with: onclick='$("#Details").show("slow");
Fills out the form and save the data.
I don't want the entire page to be reloaded, and I need only this DIV to be reloaded
I tried:
function(data) {
$('#Detalils').load(location.href + ' #Detalils');
});
and:
$("#Detalils").load(location.href + " #Detalils, script");
and:
$('#Detalils').load(location.href + ' #Detalils', function() {
$('#script').hide();
})
where in #script I put my script
In this div I have some script, and because of the jQuery on load script execution, the script is not executed.
I cannot put the script in an external file, it must be in the page body.
Is there a way to execute the script a well?
Thanks
Your actual Javascript code should not be within the div, that is the issue. If you wish to reload the form for the user to enter new data, then use ID's on the elements within your forms and write your JQuery code outside of it or in an external file, here is a simple example :
Instead of something like :
<form>
<input type="button" onclick="alert('hello');"> Click me ! </input>
</form>
Do something like :
<form>
<input id="myButton" type="button"> Click me ! </input>
</form>
<script type="text/javascript">
$("#myButton").click(function()
{
alert('hello');
});
</script>
You will have to adapt your code to this, of course, but you don't have another choice. HTML code can be removed and added at will, but Javascript code must not be treated the same way. There are many reasons for this, but one reason is that the browser will only load the Javascript functions once, for obvious optimization reasons.
The works within my local environment. Give it a shot in yours.
The HTML:
<div id="wrapper">
Remove
Reload
<div id="Details">my details box</div>
</div>
The jQuery:
<script type="text/javascript">
function mload() {
/*LOAD IN MY EXTERNAL STUFF*/
mtarget = $('#Details'); //the element on your page, that houses your external content
mscript = 'external.js'; //the js script required for your plugin to work
mtarget.load("external.html", function(){
$.getScript(mscript, function() {
//run the plug-in options code for your external script here
});
});
//*/
}
function madjustments() {
/*ADJUST THE LOADING PROCESS*/
//remove the load request on click from your remove button
$('#mremovebtn').on("click",function(e) {
e.preventDefault();
$('#Details').children().remove();
});
//reload the request on click from your reload button
$('#mreloadbtn').on("click", function(e) {
e.preventDefault();
mload();
});
//*/
}
(function($){
mload();
madjustments();
})(jQuery);
</script>
You will obviously need 2 additional files. One called external.html and another called external.js, for my demo code to work. But you can change the naming process to whatever works for you.
Extra:
Set a class in your external html file (on the parent element), for example #external. And by default, set the CSS to display:none in the style sheet. Then when the page loads in, simply show() it in the jQuery code.