Load the page content using jQuery? - php

Using jQuery load html forms dynamically using append function. Here the following code load the page content dynamically based on number times of values on while loop.
Here I have a struggle on load the content with different values.its working with single value of 0 or 1 on var load_with_value=0; but not on both simultaneously i.e. increment the load_with_value++ for again load the page content of HTML forms.
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() //url for loading page
{
var n = $('.item').length + 1; //load the html page content
var i = 1; //iteration for number of times load the content
var count = 2; //check the condition
var load_with_value = 0; //load the page content with different values for display different values on html form
while(i<count) { //loop starts
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});

First of all let's do some proper code formatting and get rid of the incorrect comments:
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() {
var n = $('.item').length + 1;
var i = 1;
var count = 2;
var load_with_value = 0;
while(i<count) {
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});
Now let's take it apart:
If you want to use a temporary element to store the loaded data you need to assign it to a variable, so instead of
$("<DIV>").load("<?php echo $url; ?>", function() {
do
var tempObject = $("<div/>").load("<?php echo $url; ?>", function() {
Afterwards you can append the temporary element to an existing one with $('#someExistingElement').append(tempObject).
If you want to load the content into an existing element you should use it's ID, class or other selector to do this - not $("<div>").. If you want to load it to all div elements (please don't) then it should be $("div").
Next var n = $('.item').length + 1; makes no sense. It is never used in the code.
While cycle in this case is unnecessary. Don't use while cycles if you don't have to. You can use:
for(var i=0; i<count; i++){
//code
}
What is var load_with_value = 0; used for? I can only see you incrementing it with load_with_value++; but you don't use it anywhere..
Finally if you want to load different content based on the incremented variable it should be done outside of the .load function.. For example
$(document).ready(function(){
for(var i=0; i<5; i++){
$('#container-' + i).load('/somecontent-' + i + '.html');
}
});
This loads the content /somecontent-0.html to /somecontent-4.html into container elements with IDs container-0 to container-4 respectively.

Related

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

jQuery can't update elements generated by PHP, even with on.('click'

I have the following code, which works fine:
for (var i = 0; i < <?php echo count($set); ?>; i ++){
$('#inc' + i).on('click', function(){
$('#scratchbox').val('test');
});
}
But what I need is this, which isn't working (the only difference is that '#scratchbox' has changed to '#set' + i):
for (var i = 0; i < <?php echo count($set); ?>; i ++){
$('#inc' + i).on('click', function(){
$('#set' + i).val('test');
});
}
Both the #inc divs and #set textboxes are generated by PHP in the same place and at the same time (technically, in this order: #set1, #inc1, #set2, #inc2, etc.). Also, further down I have this, which is able to retrieve the values contained in the #set textboxes just fine when the event handler is a static #submit div:
$('#submit').click(function(){
for (var i = 0; i < <?php echo count($set); ?>; i ++){
sets[i] = $('#set' + i).val();
}
});
What should I change and why?
Why dont add class names to your elements so you can do something like:
$(document).on('click', '.click_element', function() {
var ID = $(this).attr('id');
$('#set' + ID).val('test');
});
and have for loop separate that creates those click elements with the IDs.
Note that this solution is much faster in terms of execution than having to bind click events within a loop.
By the time your click event handler runs, the value if i is set to its maximum value. Create an IIFE in your loop to save the value of i for each iteration of your for loop.
For example:
for (var i = 0; i < <?php echo count($set); ?>; i ++){
(function (inner_i) {
$('#inc' + inner_i).on('click', function(){
$('#set' + inner_i).val('test');
});
})(i);
}
Here's a good read on using an IIFE (Immediately-Invoked-Function-Expression): http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Creating dynamic div content with jquery

I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON.
My problem is that I can't get the JSON data to display when clicking the links.
Here's the script I'm using:
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
for(var i=0; i<data.length;i++) {
$("#changetext"+data[i].id).click(function() {
$("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
});
}
}
});
This is the div element that has to change:
<div class='rightside' id='rightside'>Test</div>
The links are constructed this way:
echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";
I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.
Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
$.each(data, function(i, d) {
$("#changetext" + d.id).on('click', function() {
var h1 = $('<h1 />', {text : d.title}),
p = $('<p />', {text : d.content});
$("#rightside").html(h1.add(p));
});
});
}
});
The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.

Unable to navigate Dynamically created pages in DOM

After so many trials, I have finally managed to create pages dynamically using PHP, JSON and AJAX and load them into DOM. But the problem now is I'm unable to call/navigate those pages dynamically, but manually i.e gallery.html#page1 ...etc.
I seek guidance rather than burdening you, as I'm here to learn.
**PHP - photos.php **
$photos = array();
$i=0;
while ($row = mysqli_fetch_array($query)){
$img = $row["fn"];
$photos[] = $img;
$i++;
}
$count = count($photos);
echo json_encode(array('status' => 'success', 'count' => $count, 'items' => $photos));
JSON array
{
"status":"success",
"count":3,
"items":
[
"img1.jpg",
"img2.jpg",
"img3.jpg"
]
}
I use the below method to fetch and store ID of the desired gallery,
<input type="hidden" value="<?php echo $id; ?>" id="displayid" />
and then I call it back to use it in AJAX.
var ID = $('#displayid').val();
AJAX and JQM
$.ajax({
Type: "GET",
url: 'photos.php',
data: { display: ID }, // = $('#displayid').val();
dataType: "json",
contentType: "application/json",
success: function(data) {
var count = data.count;
var number = 0;
$.each(data.items, function(i,item) {
var newPage = $("<div data-role=page data-url=page" + number + "><div data-role=header><h1>Photo " + number + "</h1></div><div data-role=content><img src=" + item + " /></div></div");
newPage.appendTo( $.mobile.pageContainer );
number++;
if (number == count) { $.mobile.changePage( newPage ); }; // it goes to last page
I got this code from here thanks Gajotres to dynamically navigate between pages. It's within the same code.
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
}); // next button
}); // each loop
} // success
}); //ajax
I found your problem.
This part of code can't be used here like this:
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
});
This is the problem. First remove pagebeforeshow event binding, it can't be used here like that. Rest of the code is not going to do anything because currently there are any next page (next page is going to be generated during then next loop iteration), so remove this whole block.
Now, after the each block ends and all pages are generated (that is the main thing, all pages should exist at this point), add this code:
$('[data-role="page"]').each(function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$(this).find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'a'}).addClass('ui-btn-right').html('Next').button());
}
});
This is what will happen. Each loop will loop through every available page (we have them all by now) and in case it is not the last one it will add next button.
Here's a live example: http://jsfiddle.net/Gajotres/Xjkvq/
Ok in this example pages are already there, but point is the same. They need to exist (no matter if you add them dynamically or if they are preexisting) before you can add next buttons.
I hope this helps.

Select All Text Areas And Add into one Textarea

Hello im currently writing my own javascript/PHP css editor and i have it explode the file into tags and its all echoed out into separate text areas from a loop, i was wondering if its possible to scan the page with javascript and get all the content from all the text areas and add them into one variable or one text-area, thanks in advance.
Try this:
function getTextAreasText() {
var all = document.getElementsByTagName("textarea");
var values = "";
for(var i=0; i<all.length; i++) {
values += all[i].value;
}
return values;
}
.
.
.
.
var allTexts = getTextAreasText();
Yes,
If you are familiar with jquery, this is really simple. You would do something like:
var compiled_content = '';
$.('.name_of_class_to_extract').each(function() {
compiled_content += $(this).html();
});
This would give you all HTML content from the specified class ('name_of_class_to_extract') in the variable compiled_content. You could then insert this content into another element like:
$('.class_to_inseert').html(compiled_content);
var a = "";
$("textarea").each(function(){
a += $(this).text();
$(this).prepend("<h1>" + "someValue" + "</h1>") //prepend some markup before each textarea
});
a //concatenated data
Yes possible. Edit following lines for yourself
// jquery code
$(function(){
$.ajax({
url : 'get_content_via.php',
type : 'GET',
data : 'maybe_use_filename',
success:function(data){
var splittedData = data.split("your_seperator"); // like explode
for( var i = 0 ; i < splittedData.lenght ; i++){
$('#targetInput').append(splittedData[i]);
}
}
});
});

Categories