I have an HTML file that, when you click a button, Ajax loads a PHP file and the PHP file then echoes some text back to the HTML file.
The problem is that if I click the button a second time (or third, or fourth, etc), the next echoes overwrite the previous echo.
For example, if I click the button the first time, it would echo text here. If I click it a second time, it overwrites the previous echo and, again, would show text here instead of showing it on a new line.
Here's the HTML/Ajax:
<html>
<body>
<div id="show-more-results"></div>
<center><a class="btn show-more">Show more comments</a></center>
<script type="text/javascript">
var videoid = <?php echo $video_id; ?>;
$(document).ready(function() {
$(".show-more").click(function() {
num_comments += 10;
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {video_id: videoid, num: num_comments},
success: function(data) {
$("#show-more-results").html(data);
}
});
});
});
</script>
</body>
</html>
PHP:
<?php
$videoid = $_POST['video_id'];
$num_comments = $_POST['num'];
echo $videoid;
?>
How can I make it so that the next echoes from the PHP file don't overwrite the previous echoes?
Instead of using the .html() function, which will overwrite the contents of the element every time, use .append() to add to it instead:
$("#show-more-results").append(data);
It's not PHP's echo that is overwriting your value, but your use of jQuerys html() function. It sets the HTML data for the element #show-more-results to a new value. (effectively overwriting the previous value)
To get the desired result, just concatenate the previous value with the new value:
$("#show-more-results").html(
$("#show-more-results").html() + '<br />' + data
);
Or even shorter:
$("#show-more-results").append('<br />' + data);
Something like
$( "#show-more-results" ).append( "<p>" + data + "</p>" );
Wrapping the data in <p> tags will keep it neat, but you may want some other container.
Every request is a separate script exectuion, it is like new page load.
You don't say, that HTML from previous page overwrites HTML from current page, do you?
If you want to preserve "history", you need to either accumulate reponses in your javascript code, or put in some persistent storage (Memcache, DB, etc) and return whole data.
You should append the result instead of replacing it.
//This
$("#show-more-results").html(data);
should be
$("#show-more-results").append(data);
In the success function, use document.createElement and createTextNode and appendChild to keep adding elements to the document.
Related
I have a query that gets the latest 10 rows in a table and loops 10 times to echo HTML that includes some of the information taken from the table, to something similar like below (pseudo code):
query = <GET 10 LATEST ROWS FROM TABLE>
$name = <ONE VALUE FROM TABLE>;
$name2 = <ANOTHER VALUE FROM TABLE>;
echo '<div class="style1">' . $name . '</div> <img src="image.png" /> <div class="style2">' . $name2 . '</div>';
What I'm having trouble with is that, if a user clicks the image, I need to run some Ajax to show another piece of HTML based on the variable $name.
The problem is that, since I'm echoing 10 rows from the table, how can I get the value of that one variable when the image is clicked?
Please help!
give each div an id based on the value of $name. and you use $name for your ajax call to get to next step.
Wrap the grouping you need.
PHP:
<div class="style-container">
<div class="style1"><?=$name;?></div>
<img src="image.png">
<div class="style2"><?$=name2;?></div>
</div>
Then you can use JS to loop through by container and get the name, no matter what the values inside may be, with or without quotes and other special characters.
JS:
$('.style-container').each( function( i, el ) {
var $el = $(el),
name = $el.find( '.style1' ).text();
$el.find( 'img' ).on( 'click', function() {
$.ajax({
url : 'whatever.php',
data : { name : name }
});
});
});
Note I would only do this if using the markup is your only option. You may want to echo out a json_encode of data inside a JS tag. Then you can iterate and use a templating engine like mustache to print out the markup. Then you could use AJAX to open a URL based on the data rather than the markup.
My php page has at the top of the page before any jquery a php variable called $pause.
The value assigned to this is read from a database.
What I'm trying to do using jquery is show a div, then delay for the $pause value then hide the div.
This shows and hides the div, how do I add the delay ?
$("#div1").show();
$("#div1").hide();
Thanks
If you can parse php inside of your js, you can echo it:
var pause = <?php echo $pause; ?>
If not, attach the value to an element such as a hidden input so that you can access the value with jquery.
Then you could do:
$('#div1').show().delay(pause).hide(0);
Note: You need to pass the duration to hide() in order for delay() to work:
When a duration, a plain object, or a "complete" function is provided, .hide() becomes an animation method
Here's a fiddle
add $pause to a HTML Element...for example body:
<body data-pause="<?=$pause?>" >
</body>
and js:
$("#div1").show();
setTimeout(function () {
$("#div1").hide();
}, parseInt($('body').attr('data-pause'), 10));
If you would like to keep your javascript Inline write this at the end of your html before
<script>
$("#div1").show(0).delay(<?php echo $pause; ?>).hide(0);
</script>
if you don't want to keep your code inline you can add an attribute to your element and use that:
For example:
<div id="div1" delaytime="<?php echo $pause; ?>">Hello World</div>
And finally use the javascript below:
$("#div1").show(0).delay(jQuery(this).attr('data-pause')).hide(0);
I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/
Got two questions:
How can i intgrate a php script to a html document that:
should do his work at the documents startup and return a integer, which can be handled by javascript?
should do his work after a link is clicked and uses the links id?
lets create a example project:
1. php-name: start.php
2. php-name: click.php
html-code:
<!doctype html>
<html>
<head>
<title>test</title>
<script type="text/javascript">
$(document).ready(function(){
});
</head>
<body>
<p><a class="links" id="l1" href="http://www.google.com/">Boerse</a></p>
<p><a class="links" id="l2" href="http://www.google.ch/">My Gully</a></p>
</body>
</html>
1. With javascript you could use jquery to perform a POST HTTP Request that simply posts something like 'BeenSent' with data = 1. Then php checks to see if that isset. If it is then send back the variable to jquery as the function at the end of the ajax() method.
Here's an example
$.ajax({
url: "getInt.php",
type: "POST",
data: {BeenSent: 1},
cache: false,
successCondition: function(result) {
alert("getInt.php echo'd this out on it's file when I sent the request. The content it echo'd back was: " + result);
}
});
2.
For the links you could simply perform a GET HTTP Request, or you could simply define the element's id within the link... like so...
<p><a class="links" id="l1" href="http://www.example.com/?elementid=l1">Hey! I'm a link!</a></p>
Hope this helped! :)
For your first question: An ajax call is probably the nicest way to do it, but you could also do a kind of ugly solution. Have the php-function echo out the value to a hidden element, then fetch the value inside that element from your document.ready function in javascript.
function GetInteger() {
return 10;
}
echo '<span style="display:none" id="test">' . GetInteger() . '</span>';
$(document).ready(function(){
var theValue = $("#test").html();
}
For the second question I would create onclick events that made ajax calls with the wanted value as a parameter, alternatively add the id as a get parameter to the querystring.
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");
});