Ok I have a table that changes the displayed text once clicked on like the one displayed on http://www.w3schools.com/ajax/ajax_database.asp
I'm trying to update it based on each click.
For example.
Page Load > Load news article 1
onClick 1 > Load news article 2
onClick 2 > Load news article 3
All I want is for it to change based on each click, to a subsequent value. I have a php mysql database script that will pull the data from the database each time called.
The real question: Should I program the php to return a new table data cell with the new
oncLick="showNews($next_number)"
or should I leave that up to the AJAX, before it requests the information, just +1 it up.
I'm new to AJAX programming and not that experienced in PHP. I have searched everywhere and apologize if this is a redundant question. Just point me in the right direction.
write a php function to support to get the content by id. showNews(news ID). and then pass the newid with the ajax request. no need to change the newsid in the PHP.
I'm guessing something like this would be simplest:
var article = 0;
function showNews(){
get_article(article);
// magic
article+=1;
}
To be honest, just pick the way which seems more natural to you. Unless this is only a small part of something huge, it won't matter.
if I understood right, you want to get the next news when clicking on your button...
I suggest you to use jQuery for Ajax request...
It could be like this:
<script type="text/javascript">
$(document).ready(function(){
var result = 0;
$('#myButton').click(function(){
$.post('phpfunction.php',result,function(r){
$(document).append(r);
});
result ++;
});
});
</script>
And in PHP:
<?php
$result_id = $_POST['result'];
//SELECT * FROM WHERE id = $result_id;
?>
Related
I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)
I'm going to do my best explaining this, as I'm fumbling around a bit as it's my first time doing anything like this.
At the beginning of my page I call a function that returns 3 recipe's, I then create variables and assign each with a recipe id:
$meal = builder::buildMealPlan(1200,0,0,0,3);
$id1 = $meal[0][id];
$id2 = $meal[1][id];
$id3 = $meal[2][id];
So I now know the id's of the 3 recipe's that have been chosen by the function, I then display these 3 recipe's in 3 div's:
<div id="meal1"><h2><? print_r($meal[0]); ?></h2></div>
<div id="meal2"><h2><? print_r($meal[1]); ?></h2></div>
<div id="meal3"><h2><? print_r($meal[2]); ?></h2></div>
When any of these div's are clicked it means you don't like that recipe and want a different one, it calls a page with 4 parameters (id1,id2,id3,clicked), basically telling it the 3 recipe's that are currently displayed as well as which one was clicked, so I can find another combination of recipes with 2 of the same id's, as well as the new one:
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1", function(result){
$("#meal1").html(result);
});
});
This works great, a proper recipe is selected and the div is refreshed with the new recipe, however my problem is now, if you click any of the div's again, it refreshes with the same recipe over and over again, because my php variables ($id1, $id2, $id3) are always the same value, since the page is never reloaded.
My question: How can I set a javascript variable with the result of my onclick event? Right now the on click event replaces the div with data from:
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1
However I need to somehow update the variables that I'm sending in the above statement with new values each time a div is clicked.
If you've read this far, thanks, if I've left important/obvious things out please just let me know and I'll add it in.
EDIT: Ok, I've got it outputting JSON now:
{"mealnumber":1,"id":"69","title":"Protein Packed Meatloaf","description":"This meatloaf is packed with protein to help your muscles grow.","cookingtime":"00:25 ","preptime":"00:10 ","servings":"4.00","rating":"0.000","calories_ps":"205.00","carbohydrate_ps":"7.70","protein_ps":"20.55","fat_ps":"9.64"}
My JS code to try and show that I'm at least reading it correctly:
$(document).ready(function(){
$("#meal1").click(function(){
$.getJSON("testing-01.php?id1="+id1+"&id2="+id2+"&id3="+id3+"&clicked=1", function(data) {
$.each(data.items, function(i, item) {
console.log(item.id);
alert(item.id);
});
});
});
});
However nothing is logged or alerted when I click the div... am I missing something obvious here? I can see in the console that it's calling to the correct page, if I copy and paste the URL I get the json code I pasted above.
Im not sure i understand all you need, but i guess you need to change this 3 ID's in get method.
You could make some simple javascript object that store 3 id's, and rewrite it on success ajax... Buy you need better repsonse then just html... Try json...
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1="+SomeJavascriptObject.id1"&id2="+SomeJavascriptObject.id2"&id3="+SomeJavascriptObject.id3"&clicked=1", function(result){
SomeJavascriptObject.id1 =result.returnedID1;
SomeJavascriptObject.id2 = result.returnedID2;
SomeJavascriptObject.id3 = result.returnedID3;
$("#meal1").html(result.html);
});
Maybe this can help you.
On my website an user is able to fill in an url. When he fills in the url, he gets all the images src's from that url. I push these src's to an array in php:
array_push($goodfiles,$pic);
Now the user will be able to choose on of the pictures (with a next or prev button) and then save it to the database. The picture that's saved is based on the id of the image in the array. So $goodfiles['0'] means id = "0" and so on.
I want the swapping of the images to work with ajax, so that the pages doesn't have to refresh all the time when clicking the next or previous button. And then when I save the form, I want to know the id of the current image, so that I can save it to the database.
How do I realize this with Ajax (jquery)?
Edit:
This is how I do it right now:
$current_id = $_GET['id'];
if(empty($_GET['id']) || !empty($empty)) { $current_id = 0; }
$prev_id = $_GET['id'] - 1;
if($prev_id < 0){ $prev_id = 0;}
$next_id = $_GET['id'] + 1;
if($next_id > $_SESSION['count']-1 && $_SESSION['count'] != 'empty') { $next_id = $_SESSION['count']-1;}
This is the code for the pagination
And this is the pagination:
<div id="url_pic">
<img src="<?=$_SESSION['pictures'][$current_id]?>" class="img_load"><br>
<? if($_SESSION['count'] > 1) { ?><center><img src="img/add/left.png"> <img src="img/add/right.png"></center> <? } ?>
</div>
So right now my solution doesn't contain any javascript, but it's all php coded. And the page refreshes everytime you want to see the next picture. I want to solve this in ajax, so that you can paginate through the images without a refresh. The way I want it is like this link:
http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
But except for the text, I want to paginate through images.
You probably don't need to use AJAX for this. Simply return a html file containing a JavaScript array, which contains all those image URLs and do the other stuff using JavaScript.
Get back to StackOverflow in case you've a more precise question and hopefully some code, which we can help on ;)
Load a script at the bottom of your php page the user side of the PHP where all your HTML is, above the closing body tag thats something loosely similar to this
<script type="text/javascript">
var myArray = <?php echo json_encode($myPHParray); ?>
</script>
this way when your page loads out it renders with a dynamic javascript json object as a variable that you can work with client side, this removes the need for an AJAX request all together unless your doing stuff with the data your playing with. From first glance Im guessing not really per say. But yea, at the very least its one less transaction to be made when the page is loading.
edit just noticed someone said similar while I was typing out.. Lars.. so I guess this is a follow up to his answer :-D
What is that called and how do you do it? My page refreshes every 10 seconds using jquery querying a database.
I get new tables casually and I want to be able to update the field to display how many new tables were gathered. I want this because instead of viewing the page to see if any updates happened I can just look at the title of the page inside a tab instead of switching over every 10 seconds you know?
How can this be done? Thanks.
Also the data I am gathering is text in a small table and data is just failed admincp user credentials.
You can change the title of a HTML document using JavaScript:
var title = "This is my new title, can be anything";
document.title = title;
I don't know how you are storing the number of new fields, but you could use a function like this:
function updateTitleBar (newTables)
{
document.title = newTables;
}
... Or you can just use document.title = newTables where you define the newTables somewhere else (and change that value every time you refresh the page in jQuery).
Maybe something like this?
<body onload="runTicker()">
function runTicker(){
setTimeout("document.title = new Date();runTicker()", 5000);
}
But instead of doing document.title = new Date(), replace that with a call to a function that would make an AJAX call to your PHP script. Perhaps using jquery if you're accustomed to that already?
I am trying to pass an id value to a php script with jquery.
So, I was trying to create a link:
Superman
and when this link is clicked, I would like jquery to grab the id value and place it in the php script or php grabs the id? im not sure the best way.
I want the id value so it can be placed in a mysql query like this:
SELECT * FROM hero_db WHERE category="superman"
So, i get the id and place it in for the category as seen above.
I have trying many things, but am unfamiliar with jquery but trying to learn as much as I can.
Thank you for any help on this.
It sounds like you want to load HTML when the link is clicked. If so you need markup something like this:
Superman
<div id="superman_data">
</div>
with Javascript:
$("a.loaddata").click(function() {
$("#" + this.id + "_data").load('/loaddata.php', {id: this.id});
return false;
});
What this does is binds an event listener to all anchors with a class of "loaddata". When it's clicked on, the ID is passed to loaddata.php. That script should return HTML. It is loaded into the named div.
There are various jQuery Ajax methods. Which one you use depends on what you want to achieve.
$.post('http://PHP_SCRIPT_URL', {id: $('a.yourlik').attr('id')});