JQuery/AJAX: Loading external DIVs using dynamic content - php

I need to create a page that will load divs from an external page using Jquery and AJAX.
I have come across a few good tutorials, but they are all based on static content, my links and content are generated by PHP.
The main tutorial I am basing my code on is from:
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
The exact function i need is as follows:
Main page contains a permanent div listing some links containing a parameter.
Upon click, link passes parameter to external page.
External page filters recordset against parameter and populates div with results.
The new div contains a new set of links with new parameters.
The external div is loaded underneath the main pages first div.
Process can then be repeated creating a chain of divs under each other.
The last div in the chain will then direct to a new page collating all the previously used querystrings.
I can handle all of the PHP work with populating the divs on the main and external pages.
It's the JQuery and AJAX part i'm struggling with.
$(document).ready(function(){
var sections = $('a[id^=link_]'); // Link that passes parameter to external page
var content = $('div[id^=content_]'); // Where external div is loaded to
sections.click(function(){
//load selected section
switch(this.id){
case "div01":
content.load("external.php?param=1 #section_div01");
break;
case "div02":
content.load("external.php?param=2 #section_div02");
break;
}
});
The problem I am having is getting JQuery to pass the dynamically generated parameters to the external page and then retrieve the new div.
I can currently only do this with static links (As above).

I'm not sure if you've solved this already, but I'm surprised no one's mentioned to use the ajax() function.
This would allow you to define the request type as GET:
function loadContent(id) {
$.ajax({
type: "GET",
url: "external.php",
dataType: 'html',
data: {param: id},
success: function(html){
$("#container").html(html);
},
error: function(){
},
complete: function(){
}
});
}
Just call this function instead of using load. Obviously you'll have to tinker with the code (mainly what goes in the success function) a little, but this should give you a good starting point.

You can use the optional data argument to pass parameters to the GET request. Read the documentation. This is far better than building the URL yourself. You can of course add dynamic generated data to the parameters list.

function loadDiv(evt)
{
// these params will be accessible in php-script as $_POST['varname'];
var params = {name:'myDiv', var1:123, var2:'qwer'};
$.post('http://host/divscript.php', params, onLoadDiv);
}
function onLoadDiv(data)
{
$('#myContainer').html(data);
}
$(document).ready(function() {
$('#divButton').click(loadDiv);
});
In this example server-side script should return inner content of your div. Sure you can return XML-serialized data or JS to eval etc... it depends on task. The example is simplified, so extend it to fit your needs.

This tutorial on loading AJAX content is good:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Especially the part explaining how to read the results with Firebug.

Use this :
function GetDiv(id) {
$.ajax({
type: "GET",
url: "external.php"
dataType: 'html',
data:id,
success: function(html){
$("#container").append(html);
},
});
}

var params = {
param: 1,
otherParam: 2
};
content.load("external.php #section_div01", params);
will load "external.php?param=1&otherParam=2"

Related

Can I dynamically load a portion of a table first?

I've recently changed my searching page to a searchable datatable page due to my employer's request for easier data management. The problem is that it is taking too long to load.
I'm wondering it there is a way to only load like a portion of the table and finish loading the page first. Then finish off loading the rest of the table after that, e.g. while the user actually attempt to search for the data.
This was requested because the user might want to navigate to other parts of the page instead of using the datatable.
Extra info : The page is in .php and the data is loaded using php do-while loop. Maybe we can do a workaround using php functions?
Using the AJAX method recommended in the comments, the following is similar to how you could handle the page-load. You would need the jQuery library for the below.
Initial page
<script type="text/javascript">
// when the page is done loading,
// let's send a call to load more data
$(document).ready(function(){
myFunction();
});
// function to handle AJAX request to gather data
function myFunction(){
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
success: function(data){
// handle the data using the "data" variable
}
});
}
</script>
AJAX Page
<?php
if(isset($_GET["loadData"])){
// call query here and echo information
}
It may be recommended, to actually use a PHP function called json_encode() to echo back the information from your AJAX page in JSON form. This would allow you to transmit an array of information, instead of raw data. You would then need to update your AJAX request function similar to below.
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
dataType: "json",
success: function(data){
$("#myDivToChange").html(data);
}
});
You can read up on JSON at this highly rated question.

Rendering AJAX view in Cakephp

I have a method which will render a standard view file index.ctp or an AJAX view file index_ajax.ctp depending on the request type
Within my controller - I have the following code
public function index() {
if ($this->request->is(array('get', 'post))) {
// .... do normal stuff
} elseif ($this->request->is('ajax')) {
$this->autorender = false;
echo 'blah blah'; // this shows
$this->render('index_ajax', 'ajax'); // this does not render
exit;
}
}
The Javascript that invokes this AJAX view is as below
$('#myModal').on('show.bs.modal', function (event) {
$.ajax({
url: '/cake/myController/index',
type: 'ajax',
success: function(data) {
alert(data);
$('#link-list').html(data);
}
});
});
Now the normal index view renders just fine - no problems at all, however the AJAX view is not rendering. If I put an echo statement in the controller, that statement does get outputted to the view but the actual view file itself is not getting picked up and rendered. I am not sure what my mistake is - any help is appreciated.
Try this :
if ($this->request->is(array('get', 'post'))) {
// .... do normal stuff
} elseif ($this->request->is('ajax')) {
$this->view="index_ajax";
$this->layout="ajax";
}
After this, look in your layout ajax if you use blocks or something like this which don t show your code or something like that.
Ok - after lots of trial and error and experimenting around, I figure out the solution.
For the original problem that I posted, #mark gave the right answer and I have since then incorporated the plugin available here - essentially, we download and include the plugin mentioned in that link and in the AJAX method in our controller we put a line as below
$this->viewClass = 'Tool.Ajax'
And in your AJAX javascript include the following line that extracts content from the parsed JSON array and embeds in the HTML selector provided
$.ajax ({
url: '/myajaxurl',
type: 'ajax',
success: function(data) {
$('myDiv').html(data.content);
}
});
Vola! the AJAX view now gets rendered. I examined the plugin source code and noticed that Mark has essentially extended the Basic view class and overridden the render method to render AJAX views via a JSON array. However that caused a problem for me since I also had pagination in my AJAX view. So while the links would get rendered fine and the first page would load fine, the second and subsequent pages would load as unparsed JSON array.
To overcome this I had to do a lot of fiddling around and I finally figure out that we need to discard the default AJAX pagination specified within CakePHP manual and use the AJAX pagination provided by Mark at this link (along with the appropriate source code). Essentially, instead of using the default echo $this->Pagination->numbers() we should now use echo $this->element('Tools.pagination') and we should include a javascript that binds the generated pagination links in the following manner -
Assume that pagination links are within a div identified as 'pagination' and these links are generated dynamically by Mark's plugin
$(document).on('click', 'div.pagination a', function(evt) {
evt.preventDefault();
$('#myDiv').load($(this).attr('href'), function(data) {
var res = $.parseJSON(data);
$('#myDiv').html(content);
});
});
Essentially what is happening above is that we are binding each of the pagination links with a different event as opposed to what is automagically generated by CakePHP. So we are loading the content of hyperlink via load method but since a JSON array is returned by AJAX view, we are parsing it and setting the DIV's content accordingly.
Hope this helps someone else down the line!!

jQuery pop up - ask for variable before loading page

I need a jQuery popup to ask the user for some required data before loading the same page it's on.
The data entered will become a php variable that I'll use to query a mysql table and pre-populate some form fields.
Any advice?
Thanks!!
you can make an AJAX call to the PHP and load it to div that you want. For the ajax calls you can use jquery it really makes you job easy.
eg:
$.ajax({
url: 'getitems.php',
success: function(data) {
$('#manage_inventory').html(data);
//alert('Load was performed.');
}
});
like in the example it is calling getitems.php and getting the list and loading it into #manage_inventory. The data being returned can be XMl or other type which can be parsed and be used according to your needs.
Your solution could be as simple as using a prompt() box in javascript and then passing the information via ajax
var stuff = prompt('Gimme Stuff');
$.ajax({
url: 'dostuff.php',
data: 'stuff=' + stuff,
success: function(data) {
//process stuff
}
});

Loading mini-interfaces with ajax

I'm in the process of creating a revised version of a CMS I've made for a few sites.
In this redesigned version, there is a list on the left, showing you different sections you can manage (text, photo gallery etc.). On the right, I want to load the appropriate UI via AJAX when the user selects an item.
I started off by simply making a request to various files, and shoving the HTML in a div, like so:
var map;
$(document).ready(function() {
map = {"text":"txt_interface.php","gallery":"gallery_interface.php"};
$('#left_pane li').click(function() {
var id = $(this).attr('id');
if (map[id].length) {
// show loading stuff etc.
var url = 'ajax/'+map[id];
$.ajax({
url: url,
type: 'GET',
success: function(res) {
$('#right_content').html(res);
}
});
}
});
});
However, I then realized that certain pages would require external JS (e.g. tinyMCE). So, I tried various solutions such as passing the js references down in JSON separately and using $.getScript, but it all became horribly over-complicated.
Preferably without using frames, what is the simplest way of achieving this?
You can put your JavaScript in a block that you can pull-out in your AJAX callback function and eval it (I know Google does something similar to this to defer parsing of certain JavaScript):
$.ajax({
url: url,
type: 'GET',
success: function(res) {
var tmp = res.split("{script}"),
code = tmp[1].split("{/script}")[0];
eval(code);
$('#right_content').html(tmp[0]);
}
});
Here is a jsfiddle: http://jsfiddle.net/4HReW/
This assumes that you put {script}/{/script} in place of the regular <script>/</script> tags and that the JavaScript block comes at the end of the content pulled in via AJAX.

How to change the content of a div without reloading the webpage?

I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.

Categories