Can one jQuery call load multiple HTML containers? - php

I was wondering if there's a way to allow jQuery loading multiple HTML containers with just one call. For example:
.
<div id='one'></div>
<div id='two'></div>
.
.
<script type="text/javascript">
jQuery("#one").load("somephpmodule.php", "",
function(responseText, textStatus, XMLHttpRequest) {
if(textStatus == 'error') {
jQuery('#one').html('There was an error making the AJAX request');
}});
</script>
.
In the code above, only div "one" will be loaded from the somephpmodule.php output. How to load also div "two" with one call? Or simply do I need to issue multiple calls?

I'd do it like this:
loadUserModules.php handles all of the users modules and returns an array where keys are div IDs (one, two, three etc) and values are the HTML blocks you'll be adding to the page.
This will make one big call to load all your modules.
<script type="text/javascript">
$.getJSON('loadUserModuels.php', function(data) {
$.each(data, function(index, value) {
$("#" + index).html(value);
});
});
</script>

Place both s in one new empty or another tag of your choice with id and load to it.

Personally, I would use the jquery.ajax function to return json with both bits of information, then at clientside, I would get the script to place the appropriate data from the json in to appropriate div tags.
Using this method, you could have many div tags, and a single request would return all the data in json form, which could easily be placed appropriately at clientside.

You don't need to issue multiple calls, you just need to format your request and response differently.
Example, useing json.
$.ajax( {
url: url,
dataType: 'json',
data: data,
success: function( response ) {
$("#one").html( response.one );
$("#two").html( response.two );
}
} );

function loadModules() {
$('#section div[class="module"]').each(function() {
var ajaxModule = $(this);
$.ajax({
url: 'modules/' + $(ajaxModule).attr('modulePage'),
cache: false,
type: 'post',
async:true,
success: function(data){
if(data)
$(ajaxModule).html(data);
else
$(ajaxModule).html('The page that you requested was not found.');
}
});
});
}
You can use a function like this. I wrote it for load modules via ajax. You can set your modules like this;
<div class="module" modulePage="MODULETEST.PHP"></div>
And call this function on;
$(document).ready(function() {...});
It will gonna load all modules.
Btw, don't forget async:true statement on ajax. If not, when you load 3 or more modules at the same time, your page gonna freeze.
Normally async:true statement is default setted but if you assigned async:false on ajaxSetup function like me, you don't have to forget it.
good luck!

Related

.each() makes the page Freeze

The idea is to fetch the content from an external PHP file on Page load using jQuery .each() function. The problem is the page freezes or keeps on loading and never ends. What would be the issue?
PHP Page
<div class='caller-div-holder'>
<div class='calling-div' id='calling-div-1'></div>
<div class='calling-div' id='calling-div-2'></div>
<div class='calling-div' id='calling-div-3'></div>
</div>
In the .js file
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
$('#calling-div-'+fetch_id).html(data);
}
}); // Ajax
}); // Each function
Note:
Instead of $.ajax() on using document.write I found that the function is called for 3 times correctly with the variable fetch_id getting the data properly.
The external PHP page is checked with sample data just changing the POST to GET and passing the data through GET method. It works.
Edit 1:
Adding async:"false", reduces the problem intensity. But still the page is considerably slow.
The following will solve the issue by adding all the html at once, this will be faster than the other method...it will still lock the DOM at the end when it adds the html variable to the html of the parent element.
var html = '';
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
html += "<div class='calling-div' id='calling-div-" + fetch_id + "'>" + data + "</div>"
}
}); // Ajax
}); // Each function
$('.caller-div-holder').html(html);
Special Note I highly recommend using the following to solve this problem:
jQuery append() for multiple elements after for loop without flattening to HTML
http://jsperf.com/fn-append-apply

jQuery Ajax return html AND json data

I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();

Pushing data to a html list for search using ajax, jquery and php, codeigniter

First I want to show you guys what I am trying to do.
I am trying to create a search functionality in my application using AJAX, jquery and php
and as for the framework I am using Codeigniter, but it's not necessary to be CI, this could be similar to all(well I suppose).
I have this piece of code to observe a focus and blur event.
$("#searchbox").on({
keyup : debounce(function(){
MSI.Interface.search();
},350,false),
blur : function(){
$("#search_results").hide();
}
});
I have not finished it yet that is why the blur event has only .hide() . I can't think of what other else to include, maybe reset the html of the #search_results to make it blank, but I don't know if that is reasonable.
1st question: What do you think is a more reasonable solution for that?
As you can see in the previous code, i have the debounce function, just to prevent per character request on the server, I wonder if that is correct.
Then I have this search function
search : function() {
var keyword = $("#searchbox").val();
if (keyword == '') {
} else {
$.ajax({
url : MSI.variables.base_url + 'search',
type: 'POST',
data: {
keyword : keyword
},
dataType : 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
$("#search_results").show().prepend("<p>"+value+"</p>");
});
});
}
});
}
}
With that code, the script will be able to add contents to the #search_results div.
2nd Question: What do you think is a better solution for this?

Sending a value from a dropdown box to PHP via jQuery

I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});​
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});​
the ones you should always set are url,success and data if needed, please read The Documentation for more information.

JQuery to PHP function and back Ajaxed

i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.

Categories