my most trusted programmers and thank for all the help!
I grab rss-feed by jquery-ajax using php curl. It's loading very nicely directly on the page. However, I would like to translate the text, that is now html, title within h2 and text within p, wrapped by a div-container.
Google's api-script for translation doesn't seem to run after the content was put into the div. Really nothing happens. I tried both putting the script in the ajax-url-file and the file that the content is displayed on.
I used .live(), but no result.
Any idea?
Thanks!
--
In one of the methods I create a table i mysql and put in title, link and text. After that I echo the table.
$query3 = mysql_query("SELECT * FROM temp_rss_$id") or die("$error_msg");
while ($row3 = mysql_fetch_array($query3)) {
$title = htmlentities($row3['title']);
$text = htmlentities($row3['text']);
$link = $row3['link'];
echo "
$titel
$text
";
}
The title is within in a h2 and an anchor, and the text is within a p.
Using simple jquery, this method without ajax, to grab this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file);
});
Works like a charm. Then there's the google-api-script:
function initialize() {
var text = document.getElementById('media').innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en", function(result) {
var translated = document.getElementById("media");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
It doesn't load the google-script. What can be done? Of course it does work if I put the text directly on the page, without loading another file. Using ajax and append(result) instead of .load doesn't make a difference. Any idea?
Thanks!
You can call that function after the .load() runs, as it's callback, like this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file, initialize);
});
This will call the initialize function once the .load() has completed and the new content in the #media element is there and ready to translate.
Related
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
What I want to achieve
I have some works I want to show. So, I have thumbnails of these. When a visitor clicks on a thumbnail, I want a div (called slickbox) to open and show the title, the description and a slider about the work clicked.
What I've already done and how
I get my work's datas from a database. Here is the little part of my listing of works:
index.php
<?php
$retour_messages = mysql_query('SELECT 2K13_works.*, 2K13_categories.nom AS nomCAT FROM 2K13_works, 2K13_categories WHERE 2K13_works.cat_id = 2K13_categories.cat_id ORDER BY 2K13_works.record_date DESC') or die(mysql_error());//requete sql pour récupérer les works de la page
?>
<ul id = "creations" class = "step">
<?php
while($donnees_messages=mysql_fetch_assoc($retour_messages)){
echo '<li class = "step '.$donnees_messages['nomCAT'].'" id="'.$donnees_messages['work_id'].'">
<div class = "item"><img src = "'.$donnees_messages['thumbLink'].'" alt = "'.$donnees_messages['titre'].'" title = "" width = "226" height = "147"/>
<div class = "caption">
<h3>'.$donnees_messages['titre'].'</h3>
<p>'.html_entity_decode($donnees_messages['resume'],ENT_QUOTES,'UTF-8').'</p>
<p id = "desc" class = "hidden">'.html_entity_decode($donnees_messages['description'],ENT_QUOTES,'UTF-8').'</p>
<!--<p id = "idw" class = "hidden">'.$donnees_messages['work_id'].'</p>-->
</div>
</div>
</li>';
}
?>
</ul>
As you can see, I have a ul tag containing a li tagfor each work. Each li tag takes the id of the work in database, and each li contains h3 tag and p tag containing the texts I want to show in a slickbox (for the images, I'll see later).
Now, my JavaScript code for the slickbox, appearing and disappearing:
front_functions.js
//_____________SLICKBOX__________________________________
$('#slickbox').hide();
$("#creations li").click(function(e) {
// shows the slickbox on clicking the noted link
$titre = $(e.target).children("h3").text();
$bla = $(e.target).children("#hidden").text();
$("#description").children("h1").text($titre) ;
$("#description").children("p").text($bla);
$('#slickbox').slideDown();
e.preventDefault();
$(e.target).empty();
//return false;
});
This code is not working, because my slickbox is loaded before the works. So that's why I need Ajax and a asynchronous way of sending and executing requests.
I read this sample code here: which is quite helpful.
But, I have a problem: I'm using jQuery and I would like to use $.ajax(). And I just don't really understand how to do this.
Do I have to set an XHMLHTTPRequest object? Where can I write the Ajax call? Can I call a function, instead of an URL?
Like doing (I don't know):
$(#creations li).click(function(e){
$.ajax(){
function : "displayContent(id,desc,title)",
}
}
function displayContent(id,desc,title){
$(#slickBox).children("h1").innerHTML(title);
$(#slickBox).children("p").innerHTML(desc);
$(#slickBox).show();
}
I don't even know if I should use JSON (but, well, because my data is already stored, and I just want to display them, I think I don't need Json).
Please give me your informed opinion and your senior advice.
when you send a request for server (with ajax) this is like that you are submitting a form in a page .
so every thing that you can do with php when a form submitted , you can do that with ajax too .
e.g if you want to call a function in php with ajax , just send a param to php like this :
$.ajax({
type:'POST',
data:{
param:'Hey_php_call_this_function'
},
success:function(data){
alert('hey jquery , php said : ' + data);
}
});
and in server side :
if(isset($_POST['param']) && $_POST['param'] == 'Hey_php_call_this_function'){
echo call_a_function(); /// "output to callback success function" = data
}
hope that helpful .
I have a a script that on click do a ajax call connect to the database get imagename and set the image name inside an < -img - > with the right path also it adds a hidden checkbox after it and then echo it.
i then take the ajax message returned and put it as div's HTML. my question is will i be able to preform more action on the inserted content..
The main goal is to be able to click on the image as if it were a checkbox(this part is already sorted for me) however no matter what i try i cant have a .click function works..
Here is the code.
This is the PHP part that echos the images.
if($_POST['updateIgallery'] == 'ajax'){
global $wpdb;
$table_name= $wpdb->prefix . "table_T";
$imagecounter = 1;
$toecho = '';
$currentselected = $wpdb->get_row("query");
preg_match_all('/\/(.+?\..+?)\//',$currentselected ['image_gal'],$preresualts); // images are stored with /image/.
foreach ($preresualts[1] as $imagename){
$toecho .= '
<img rel="no" id="JustantestID" class="JustaTestClass" src="'.site_url().'/wp-content/plugins/wp-ecommerce-extender/images/uploads/'.$imagename.'">
<input name="DoorIMGtoDeleteIDcheck'.$imagecounter.'" style="display:none;" name="DoorIMGtoDelete['.$imagecounter.']" value="/'.$imagename.'/" type="checkbox">
';
$imagecounter++;
}
echo $toecho;
}
This is the ajax part that send and receive and insert the HTML to the div:
$.ajax({
type: "POST",
url: "/wp-content/plugins/wp-ecommerce-extender/DB_Functions.php",
data: { updateIgallery: "ajax", CurrentDoorIDnum: $('#dooridforgallery').val()}
}).success(function(insertID) {
$("#ImgGalleryID").html(insertID);
});
This so far works what i am having trouble with is the following:
$("#JustantestID").click(function() {
//DoorImageGallery($(this).attr('id')); // the function i will use if the alert actually works
alert("kahdaskjdj");
return true;
});
I hope the question and the code is understandable.
Thanks in advanced.
When you replace element's html, all the elements inside it are removed and gone. That means the event handlers attached to them are removed as well.
You could try attaching an event handler to a higher level element that is static and permanent on your page. Without more info I am going to use document:
$(document).on( "click", "#yaniv", function() {
alert("kahdaskjdj");
});
$('img.JustaTestClass').bind('click', function() {
var checkbox = $(this).siblings('input[type=checkbox]');
if (!checkbox.is(':checked')) checkbox.attr('checked', true);
else checkbox.attr('checked', false);
});
Since the elements are dynamically inserted into the DOM with ajax, you have to delegate events to a parent element that actually exists when binding the click handler, which in this case looks to be #ImgGalleryID
$('#ImgGalleryID').on('click', '#yaniv', function() {
DoorImageGallery(this.id);
alert("kahdaskjdj");
});
I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}