I am using a jquery carousel to display some images in a dynamically populated list. When the page is first opened it looks great but once the ajax replaces the contents of the div containing carousel content all of the formatting etc is lost.
I understand that this is because the ajax content is newly created and didn't exist when the carousel script did it job but I'm not sure how I can get it to apply the formatting to the new content?
This is the ajax call displaying the newly created data
$(function(){
var audit_id = $('#auditID').val();
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: '../ajax/upload_standard_ajax.php?audit_id='+audit_id,
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|JPG)$/.test(ext))){
status.text('Only jpg files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(response){
status.text('');
//if(response==="success"){
$.ajax({
url: 'ajax/create_audit_standard_carosel.php',
type:'POST',
data: 'audit_id='+audit_id,
success: function(response){
$('#selected_standards').html(response);
}, // End of success function of ajax form
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
}); // End of ajax call
}
});
});
The html used to trigger the ajax call
<a href="#" class="upload_stuff ipad_hide">
<div id="upload">
<span class="upload_btn"> </span>
</div>
</a>
<span id="status" ></span>
The ajax response
$output .='<ul id="standards_list" class="touchcarousel-container">';
while($row = mysqli_fetch_assoc($result)){
$output .='<li class="touchcarousel-item">';
$output .='<img src="'.$row['imageLocation'].'" width="200" >';
$output .='</li>';
}
$output .='</ul>';
I've tried it just having it all on one line and I've also tried leaving the ul intact on the original page and just outputing the li element. I've also tried using json and just echo for the resonse
I can apply the formatting by refreshing the screen but it kind of defeats the object of using ajax
My reputation is too low so I can't comment, but first, what do you mean by formatting? Do you mean CSS styles? It would help if you showed the markup for the element that is represented by #selected_standards.
If you mean "CSS formatting", I suspect that when you do:
$("#selected_standards").html(response);
you are overwriting the contents of #selected_standards and thus losing the CSS formatting.
Grab the current value of the classes assigned to #selected_standards (or its children, depends on your document structure) and then re-attach those classes to the elements that had them before.
You can do something like
var previousClasses = $("#selected_standards").attr("class");
// your existing code to insert HTML
$("#selected_standards").attr("class", previousClasses);
Related
how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
On my page I have a list of users. Each user has a profile page on an external site (not the same domain name). To save my client updating their profile details in 2 places, I am using PHP simple HTML Dom Parser. This gets the content of the users external profile page and returns it on my site.
What I am trying to do is load the users profile information into a div on my site only when the users name is clicked.
Each user looks like this:
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="http://placehold.it/500x500" />
</div>
To get the contents of the external page I use this code:
$html = file_get_html('http://www.spotlight.com/5094-1276-6177');
echo $html->find('div.credits', 0);
Obviously this works at the minute as it is hard coded. However I need to make it dynamic so that the external profile info for each user is loaded when the relevant user is clicked.
Update from answer below:
I added this script to the top of the user list:
<script>
jQuery(function ($) {
$(".actor_container").load(function () {
return "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url");
});
});
</script>
then in my.php
<?php
$html = file_get_html($_GET["url"]);
echo $html->find('div.credits', 0);
Currently, when I click on a user, nothing happens
UPDATE
OK I've moved to using AJAX to access my.php. Here is what I have so far:
<script>
jQuery(document).ready(function ($) {
$('.nial_actor').on("click", function (e) {
e.preventDefault();
$.ajax({
url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url"),
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
// append all data
$('#all_data').append(data);
}
});
}); //on
}); // ready
</script>
However this returns the following error:
GET http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=undefined 500 (Internal Server Error)
So for some reason the url in data-url is not adding to the end of my ajax url. Have I missed something obvious?
Something like this works?
$(function () {
$(".actor_container").load(function () {
return "my.php?url=" + $(this).data("url");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="...actor profile img..." />
</div>
And in the PHP file, you can add url as your GET param:
$html = file_get_html($_GET["url"]);
Note that there are lots of vulnerabilities in this methods. Keep this just as a guidance.
If I click on a link, it's supposed to load data from the database that corresponds to that link and display the data into a div, but when I click, nothing happens. Based on my original question which had so many comments, I decided to start fresh: Using a href onclick to update div without reloading page?
My code:
the page that displays the links and data:
<a href="#" class="query-link" data-id="1" >text</a><br>
<a href="#" class="query-link" data-id="2" >text 2</a>
javascript file:
jQuery(document).ready(function() {
jQuery('a.query-link').on('click', function(e){
//Prevent the link from working as an anchor tag
e.preventDefault();
//Declare 'this' outside of AJAX because of asynchronous nature of call
that = jQuery(this);
//Make AJAX call to the PHP file/database query
jQuery.ajax({
url:'http://dirtypoliticsph.com/chart-submission/templatecode.php',
type:'POST',
data:{id:jQuery(this).data('id')},
success:function(data){
jQuery('#myStyle').append(data);
}
});
});
});
templatecode.php (the file that calls the database):
if(isset($_GET['id']))
{
$results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE ID=".$_GET['id']);
if( $results->num_rows > 0 )
{
$row = mysqli_fetch_array($results,MYSQLI_ASSOC);
//Instead of just echoing out the ID, you need to build the result/data that you want in the div right here. The success function of the AJAX call will append whatever you echo out here
echo $row['id'];
}
}
Try:
data:{id:jQuery(this).attr('data-id')},
You need to fetch the 'data-id' attribute of the element:
<a href="#" class="query-link" data-id="1" >text</a><br>
You said that you want to load data from database that corresponds to that link, but I don't see any selectors referring to the anchor tag as the response from the server. Add the following after your jQuery('#myStyle').append(data); :
jQuery('.query-link').append(data);
and use $_POST in your templatecode . By the way since those anchors use the same class name, so both of them will be affected.
I want to apply a plugin on a certain table that is being generated dynamically through a php script. This is the plugin : CLICK
Now from what i read in the comments i should You first need some form of server side component, say a PHP script, which generates the html table from the data in the database. Then pass the URL of this PHP script into a jQuery ajax call. In the "success" callback, set the innerHTML of some holding div to the response of the ajax call, then select this newly created DOM table element and put it into the plugin.
Hope that makes sense!
Here's what i got so far.
HTML
<div class="testin">
<script>
testin();
</script>
</div>
JS
function testin(){
var load = $.get('functions.php',{gameNo:"1",function:"testin"});
$(".testin").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".testin").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".testin").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
php
if($_GET['function']=="testin")
{
echo '<table class="template" style="display:none"><thead><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr></thead><tbody></tbody></table>';
$gamenumber = $_GET['gameNo'];
echo'<table border="1" class="actualTable"><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr>';
$sql = mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gamenumber' ORDER BY round_name")
or die(mysql_error());
$i=1;
while($row = mysql_fetch_array($sql))
{
$tempSnumber = getcurrentshot($row['round_id'],$row['player_id']);
echo'<tr>';
echo'<td>'.$gamenumber.'</td>';
echo'<td>'.$row['round_name'].'</td>';
echo'<td>'.$row['player_id'].'</td>';
echo'<td>'.$row['target_name'].'</td>';
echo'<td>'.$tempSnumber.'</td>';
echo'<td>'.$row['round_score'].'</td>';
echo'<td>'.$i.'</td>';
echo'</tr>';
$i++;
}
echo'</table>';
}
The function fills the div just fine. I also create the template table in the php script.
Now my problem is how to invoke the plugin and what should i pass ass objects?
Invocation is like $(oldTableElement).rankingTableUpdate(newTableElement) but i'm confused due to the fact that it's being generated dynamically.
I'm new to JS so any help would be appreciated.
First off, I would put your javascript outside the div with class "testin".
Below you JS function you can add the jquery call like in the code below.
See this link for more info: http://api.jquery.com/on/
$(document).ready(function(){
$("table tr").on( "click", function() {
//your custom code goes here.
});
});
What this does is make sure then any element that matches the "table tr" will get an click handler, no matter when it gets created.
I've created a bookmark page that retrieves links from a database and displays it. I'm able to log in, add new links & delete them. However, when I delete an entry it displays delete.php instead of loading the page onto itself (the query does work).
I've most likely over-complicated my code at this point and am probably overlooking something simple, as I've used a lot of JavaScript for other elements of the page.
The entries are added dynamically so this part of the HTML is being appended:
<h2>
[x]
</h2>
<a href="'+url+'" target="iFrame" class="linkURL">
<div class="bookmark">
<h3 style="float: left;">'+title+'</h3>
<br />
<p>'+desc+'</p>
</div>
</a>
JavaScript:
// DELETE FUNCTION
$("h2 a").click(function() {
return false;
var action = $(this).attr('href');
var form_data = {
URL: $("#linkURL").attr('href'),
is_ajax: 1
}; // form_data
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success') {
alert('Successful delete!');
} else { // if
alert('Delete failed.');
} // else
} // function(response)
}); // ajax
return false;
}); // h2
The page is located here: http://samaradionne.com/links6/ if it is easier to view the whole thing.
You are using both an anchor tag a and a click event. You are getting the actual delete.php page because when you click on the anchor tag it works just like any regular link. You have no where in your code something that says "hey, don't actually follow this link like normal".
To not follow the link, you need
[x]
Furthermore, you attached your jQuery click event to the h2, which is not bad in of itself, just confusing as the intent is to actually click the link. In that case, you need:
$("h2 a").click(function(){});
Lastly, to bring this all together, you could do the following:
$("h2 a").click(function(){
// your normal logic
return false; // don't follow link
});
And then you don't have to have the onclick inside the anchor tag.
Since my links were dynamically generated, my .h2 a click was attaching itself to something that wasn't there yet. I added an event trigger to my append function that calls to my delete function.
Problem solved.