php javascript partial page reload - php

I have a page set-up, with several divs.
For now all we need is
<div id="main">...</div> & <div id="sidebar">...</div>
Each div has code such as:
<?php include("page.php") ?>
The main div does all the work, and includes a JavaScript function. E.g. at the moment the user can click a button to remember an item displayed in a table.
Am I able to only reload the sidebar instead of the whole page when the user calls this function?
I am posting the function here, and all I need now is to be able to refresh the sidepanel and its included php files if that is possible? I assume something along the lines of this could do the job? or am I wrong? load("#sidebar")
function saveToFavorites(code)
{
$.ajax({
async:false,
type: "POST",
url: 'formPostsUser.php?reqtype=addToFavorite',
data:'coursecode='+ code,
success: function(data)
{
$('.result').html(data);
if(data != "")
{
alert(data);
load("#sidebar")
}
}
});
}
Kind regards
Alex
Happy about any and every reply and hint ;)

First thing
<div="sidebar">..</div>
The above markup is wrong HTML. You should give the sidebar as the value of your properties such as id or class
<div id="sidebar">..</div>
Loading the Sidebar content
You can use jQuery ajax to load content of this div using jQuery load method like this
$(function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
Assuming yourPHPPageToReturnSideBarContent.php is the PHP page which renders the HTML Markkup for the sidebar. Note that this will load the content on the document ready event.
Loading the side bar content on an event
If you want to load it on a purticular event like a button click you can do it like this
$(function(){
$(document).on("click","yourButtonId",function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
});
The above script will load the side bar content on a button click. The button's id is e "yourButtonId" in this example.
Note that i used jQuery on here to bind the function because it will take care of current element and future element in case if you want to load the markup which contains the button dynamically.

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.

Targetting a link to load inside a DIV

I have created a menu which is simply a series of DIVs and am using the following code
$(".menu_item").click(function(){
window.location = $(this).attr("data-href");
return false;
});
to make the entire DIV for each item clickable. I have a "container" DIV setup with content initially loaded via php-include, but want different content to load when a different menu item is clicked.
I know I can use JQuery.load to target the loading of an external file into a sepcific DIV but it looks that would mean coding separate instances of jquery for each link? I would also rather stick to using php includes if possible. Can I use jquery.load to load via php include?
Any help on how to achieve this would be appreciated.
Here's the rest of the code:
/* Menu Item */
<div class="menu_item" data-href="link1.html">
Link 1
</div>
/* Container to load link into */
<div id="myContentDiv"></div>
You can use the jQuery AJAX shorthand method load() which makes the ajax request and on completion populates the element with response
$(".menu_item").click(function(e){
var url= $(this).data('href')
$('#myContentDiv').load( url);
return false;/* edit to prevent browser following link*/
});
API Reference: http://api.jquery.com/load/
$(".menu_item").click(function(e){
e.preventDefault();
$.ajax({
url: $(this).attr("data-href"),
context: $('#div-to-replace-content')
}).done(function(data){
$(this).append(data);
});
});

Showing Information on button click

I am making a test project in PHP. I want to show some information on click of button named 'View Details'. But there are 3 different buttons like this. Each are showing different information. I want to manage like user can see only one information at a time. Can Any one help me?
Thanks in advance.
You will manage flag to show/hide your information.
e.g if any one click on view details button you have set flag=1 in javascript and check this flag on another button click if is already 1 then does not display any information.
You could create a wrapper div say "resultsDiv" and display the response (ajax) from your php file to this DIV. So that only one information is seen at a time, like:
//First ajax call on first button click,
$.ajax({
...
..
success: function(resp) {
$("#resultsDiv").html(''); //clear the DIV html
$("#resultsDiv").html(resp); //place the response
}
});
//Second ajax call on second button click,
$.ajax({
...
..
success: function(resp) {
$("#resultsDiv").html('');
$("#resultsDiv").html(resp);
}
});
//more ajax calls
//your div that will hold response of ajax call on various button clicks
<div id="resultsDiv"></div>
Did you mean something like this

PHP and AJAX - make ajax call on load of a document

Can I make an AJAX call immediately after loading a page? To be more specific, I have an ajax action on click of some html tag (say in page 1). Now when I come to the same page (page 1) from some other page (say page 2), (i.e.. on ready of the document) can I make that ajax call which is present in the onclick of that appropriate html tag? I am using PHP as server side script..
There were confusion on my question.. Let me explain more.
I have an phtml page where there are lot of ajax calls on click of various tags.
Lets say, tag1 has send-message functionality ajax call which on click loads a compose message part of html.
Similarly tag2 has photo display funcitonality ajax call which on click loads the photo display part of html.
Now I'm in page 2 which is a search result page Where I have a link for page 1. That link is send-message link. So now I have to come to page 2 and with compose message part html loaded. I want to load it via ajax which will be performed on clik of the send-message link (tag 1)in page 1. How to accomplish this? How will I inform to page 1 to load the compose message part of html through ajax?
you can call that function explain below
<script type="text/javascript">
function_name();
</script>
Im not sure what you want to achieve here but if you're asking if you could do AJAX on ready of the document, then i think you can..
Check this out in jquery
$(document).ready(function(e) {
$.ajax({
type:'POST',
url:g_site_path+'search/agentpopup',
dataType:'html',
data:data,
success:function(html){
$("#agentpopup").html(html);
}
})
}
$_SERVER['HTTP_REFERER']
Is the php data-feild that will tell from where the page request is coming (Ex. Page 2 has requested Page 1). Note that HTTP-Referer is by its very nature risky and can easily be spoofed. To test for document ready, you can use something like jQuery
$(document).ready(function() {
$.ajax('your_ajax_script.php', function(result) {
/* Do what ever you want to do of result*/
console.log(result);
});
});

How to initiate javascript in jQuery ajax-loaded content in IE8

I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome
It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.

Categories