Script Execution with .load() - php

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.

Related

jQuery toggle function stops working after AJAX HTML data load

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.

jQuery's GET is acting up for me. Using CodeIgniter. It returns source code for a view instead of one value

I am trying to test the jQuery GET method, but what I am getting as result is completely insane. All I am trying to do is call a function from my controller with jQuery and then display the echoed value in a div within my view. Below is my code and finally a breakdown of the problem I am encountering.
Controller
public function generate_suggestions2() {
echo "James";
}
View views\suggestions_v.php
<body>
//This DIV is used a button to call the jQuery function
<div id="next_btn">
<p>Click here to display a name</p>
</div>
//In this div the value retrieved by the jQuery should be displayed
<div id="listB"></div>
//This is the function that calls the function within my controller
<script type="text/javascript">
$( "#next_btn" ).click(function() {
$.get("core/generate_suggestions2/",
function(data) {
$( "#listB" ).html(data);
});
});
</script> //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
</body>
Now the problem is that when I click the DIV next_btn it does NOT display the James in the DIV listB.
Instead it populates the DIV listB with my source code from my main view views\core_v.php
I have no idea how this is even remotely possible, so please if you have a clue or even better you know what I am doing wrong please tell me. I am trying to get this to work for the past three days without any success or progress :(
Try using this code in your view
<script type="text/javascript">
"$( "#next_btn" ).click(function() {
$.get("<?php echo site_url().'/core/generate_suggestions2';?>",
function(data) {
$( "#listB" ).html(data);
});
});"
</script>
Also delete the </script> tag just right before this block comment.
Regarding this comment you have:
//For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
It is because the DOM is not yet fully loaded and Javascript executes its code when the browser has finished loading the DOM you are referring to. So you either have to put it after the DOM element you want to edit, like you do now or you could use $(document).ready(function(){
}
); .
Read more about it here
This line is pretty strange:
</script><script type="text/javascript">
Try to delete first closing tag 'script' on it.

javascript or jQuery doesn't work in dynamically generated content

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;"
});

Jquery load data from URL or go to URL

I have 2 php pages named "personal_info" and "portfolio". I load them via php functions in codeigniter http://www.mysite.com/controller/personal_info and http://www.mysite.com/controller/portfolio.
I have a page with menu tabs linked to personal_info and portfolio and I want to load the pages via ajax when a tab is clicked. If js is turned off in the browser the tabs should just go to the url.
I am using the jquery .load() function to load the pages.
<script type="text/javascript">
$(document).ready(function(){
$('#personal_info').click(function() {
$('#result').load('personal_info #load'); //load fragments from #load div
});
$('#portfolio').click(function() {
$('#result').load('portfolio #load');
});
});
</script>
HTML
<div id="tab">General Info</div>
<div id="tab">Portfolio</div>
<div id="result"></div>
Issue: When I click on a tab it treats it as a link and goes to the URL instead of loading the page via jquery. How can I disable the link if javascript is on? Also, I noticed that javascript is not loaded from fragments in the pages, and if I put the javascript in the page I load data it doesn't pick it up.
What is a good solution for this?
EDIT:
For loading js, I just wrapped the entire page in the result div and am loading the other pages with the js and header, footer.
For the first issue: put return false; at the end of each 'click' function:
$('#personal_info').click(function() {
$('#result').load('personal_info');
return false;
});
Edit: For the second issue, maybe pull out any jquery/javascript and run it from a central application.js file?
You need to prevent the default action of the <a/> element. You can accomplish this by using event.preventDefault()
$('#personal_info').click(function(e) {
$('#result').load('personal_info');
e.preventDefault();
});
$('#portfolio').click(function(e) {
$('#result').load('portfolio');
e.preventDefault();
});
To stop the default action from occurring (following the link) you need to use return false at the end of your jQuery click() functions.
With regard to your second issue ("javascript is not loaded from the [dynamically loaded] pages"), ensure that you are using jQuery's .live functionality to attach handlers.

Open a url, in jquery php

when I click on "Click Here" then a page must open inside
<script....>
$('yahoo').html('<a href=desc.php>');
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>
Thanks
Dave
I think you're looking for AJAX to fetch the page for you. Something like this might work:
<script type="text/javascript">
$(function() {
$('#clickhere').click(function() {
$('#yahoo').load('desc.php');
});
});
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>
First you need to wrap the script inside $(function() { ... }) to execute your code on page load. This is equivalent to $(document).ready(function() { ... }).
Next you have to bind a click event to the #clickhere element so you can actually do something when the user clicks on it.
When the user clicks on the #clickhere div, load() will fetch the contents of the given url inside the element you call it from. So, this snippet means that when the #clickhere div is clicked, desc.php is loaded inside #yahoo div.
ID selector is #ID, not just ID
Use jQuery AJAX load method to load desc.php page
You should execute your jQuery code after DOMContentLoaded event
Wrap your code in $(document).ready(function() { });, which will insure that the code executes after the DOM is available to your code. Otherwise, $('yahoo') will likely return no matched elements.
Why not try target_self ? I also fixed some code
<script....>
$('yahoo').html('<a href=desc.php target='>self'>Click here</a>');
</script>
<div id='yahoo'></div>
<div id='clickhere'>Click here</div>

Categories