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
Related
I am using ajax to receive data from php server. The data is received in json format. To display this data I am creating dynamic divs with unique ids. I have appended the dynamic divs in an already structured html.
Now while spitting out the data using ("#"+dynamicid).html("data"), I am unable to get the desired output.
Here's the code:
$.ajax({
url: "loader.php",
dataType: "json",
success: function(data) {
var i = "kmapN"+data.id;
$('<div class="kmapName">').append($('<div id="'+ i +'">'))
.append($('</div></div>'))
.appendTo('.new_content');
$("#"+i).html(data.kname);
}
});
Here's the json output from the server:
{"id":2,"kname":"This is the title!"}
Edit1:
If I don't use the dynamic id, I am getting the result. The problem is therefore in generating and accessing the dynamic id.
Edit2:
The idea here is to prevent javascript and html injection attacksby using ("#" + id).html("output") function of jquery.
Try this one
$('.kmapName').append('--Output you want to be rendered ---');
your dataType must be defined.
create your dynamic div and append the variable to the main div
.ajax({
url: "loader.php",
dataType:'json',
success: function(data) {
var i = "kmapN"+data.id;
var new_div ='<div class="kmapName"><div id="'+ i +'">'+ data.kname +'</div></div>';
$(".new_content").append(new_div);
}
});
I have put together an ajax powered chat/social network with jquery, PHP - but am having problems with the javascript.
I have a js file in the main page which loads the php in a div container, the js file is underneath the div. But only one function for posting a msg seems to work but the others do not.
I have tried including the js file with the dynamically loaded php at the end of the ajax load the functions work fine but am getting mutiple entries of the same message/comment.
I am pretty sure its not the PHP as it seems to work fine with no ajax involvment. Is there a way to solve this?
this is the function that works fine:
$("#newmsgsend").click(function(){
var username = $("#loggedin").html();
var userid = $("#loggedin").attr("uid");
var message = $("#newmsgcontent").val();
if(message == "" || message == "Enter Message..."){
return false;
}
var datastring = 'username=' + username + '&message=' + message + '&uid=' + userid;
//alert(datastring);
$.ajax({
type: "POST",
url: "uploadmsgimage.php",
data: datastring,
success: function(data){
document.newmessage.newmsgcontent.value="";
//need to clear browse value too
$('.msgimage').hide('slow');
$('#addmsgimage').show('slow');
$(".usermsg").html(data);
$("#control").replaceWith('<input type="file" name="file"/>');
$(".msgimage").remove();
}
});
});
And this is one of them that does not work:
//like btn
$(".like").click(function(){
var postid = $(this).attr("pid");
var datastring = 'likeid=' + postid;
$.ajax({
type: "POST",
url: "addlike.php",
data: datastring,
success: function(data){
$(".usermsg").html(data);
}
});
});
From your post, I'm guessing that each message has a "Like" button, but you have 1 main submit button. When messages load dynamically, you have to assign the .like to each one when they come in, otherwise it will only be assigned to the existing messages.
The problem, from what I gather (and this is a guess) would probably be fixed using live so jQuery will automatically assign the click function to all messages including dynamically loaded messages; so instead of:
$(".like").click(function(){
Try this:
$(".like").live('click', function(){
If that doesn't solve the problem, then I'm probably not understanding what it is.
I have a simple load more style script that works fine on the index page, where only one parameter is sent via ajax
$(function() {//When the Dom is ready
$('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
var last_msg_id = $(this).attr("id");//Get the id of this hyperlink this id indicate the row id in the database
if(last_msg_id!='end'){//if the hyperlink id is not equal to "end"
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: "lastmsg="+ last_msg_id,
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
With this HTML/PHP
<div id="more">
<a id="<?php echo $msg_id; ?>" class="load_more" href="#">more</a>
</div>
However, I want to add another php variable so that it can also work with particular categories, I have no problems writing the HTML and PHP but I am new to Jquery and struggling to edit the script to include the additional parameter if it is set. This is the HTML that I am thinking of using, just struggling with editing the JQuery
<div id="more"class="<?php echo $cat_id;?>">
<a id="<?php echo $msg_id;?>" class="load_more2" href="#">more</a>
</div>
As always any help is much appreciated!
You can set
data = {onevar:'oneval', twovar:'twoval'}
And both key/value pairs will be sent.
See Jquery ajax docs
If you look under the data section, you can see that you can pass a query string like you are, an array, or an object. If you were to use the same method you already are using then your data value would be like "lastmsg="+ last_msg_id + "&otherthing=" + otherthing,
You can pass multiple URL params in the data portion of your ajax call.
data: "lastmsg="+ last_msg_id +"&otherparam="+ other_param
On the PHP side, you'd just process these as you already are.
You can use this code:
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: {var1: "value1", var2: "value2"},
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
Try It:
data: JSON.stringify({ lastmsg: last_msg_id, secondparam: second_param_value});
You can add more parameters separating them by comma (,).
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!
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.