It seems this question has been answered in the past, however, I'm either 1) having a hard time grasping the solutions or 2) not implementing them correctly.
I have a PHP function, that when run, will return results of a database query. Results look similar to this:
Koenji
I can echo this into a page just fine. What I'd like to do is give an end user the option to refresh the link (which can be done by refreshing the page and echoing a new random string returned by the php function) without having to refresh the whole page. I've tried a few different methods, but it seems the function that returns the element is only run when the page reloads - so my URL never changes.
Here is my latest attempt. I figured the url I'm grabbing from the database was only getting set when the paged loaded. I thought setting a function to initialize the url variable would help - no good. It still only works once on page load.
$(document).ready(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
$('#clicky').click(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
function updateVariable() {
url = '<?php echo dannyChoo();?>';
random = 'Random DannyChoo.com article: ';
};
You can see it live at www.dannychoofan.com.
Any help is appreciated =0)
It looks like your looking for an ajax style call.
You should put the contents of the dannyChoo() function into a new file called articleLinkGenerator.php at the same level as your index.php file. This file should have the contents of the dannyChoo() function so that it automatically executes and echos the html you are expecting for the link like
<?php
function dannyChoo(){
// generate random link code
echo $random_link_html // Like Koenji
}
dannyChoo();
Then in your index.php (main web site) update your functions using ajax(http://api.jquery.com/jQuery.get/) to look like:
$(document).ready(function() {
updateVariable();
});
$('#clicky').click(function() {
updateVariable();
});
function updateVariable() {
$.get('articleLinkGenerator.php',function(data){
$('#dannychoolink').html(data);
});
};
It's because PHP runs before the page loads, and JavaScript runs after the page loads, so your variable never changes without another page load.
Related
My goal: I have a form that is in parts, 1-4, when the user clicks on the "Next" button I would like the content to animate out then part 2 slides, and so on until the form is complete. The tricky part is I would am trying to use a different php page in a different subfolder to insert as the other 3 parts. This would also change the URL subfolder the user sees.
The working example is actually WordPress. When you click through the multi-part form you will see the content and the URL act as I have described.
I did a bit of digging and it seems like they used React.js on the content but I couldn't really find any documentation on how to do this with React.js so it made me think that maybe it was custom Ajax/jQuery or what.
My Trees of Folders -
Main
Subfolder-1
index.php
Subfolder-2
index.php
And so on. The only thing I could think of would to use jQuery:
$(document).ready(function() {
$('#form-container').on('click', '.insert', function() {
var directory = $(this).attr('name');
$('#form-container').load('../' + directory);
return false;
});
});
I add the class of "insert" on the "Next" button and give it a name="Subfolder-2" $('#form-container').load('../Subfolder-2);' will actually load the content into the div without the page refreshing BUT it does not change the subfolder in the URL.
Am I on the wrong track? Maybe I am just not searching for the right thing?
Ok, so I ended up figuring out how to get the content to act like I wanted with the information John S. provided me. After doing some research and a few hours of trial and error I came up with the JavaScript below:
var data = 'start',
url = '../' + data + '/';
history.pushState(data, null, url);
Above I set the variables and immediately run a history.pushState on page load to capture the first div that is loaded into the content div. This is important because it is the only way I could load the content that happens on initial load back into the page when hitting the browsers back button.
$('body').on('click', '.insert', function(e) {
data = $(this).attr('data-name'),
url = '../' + data + '/';
history.pushState(data, null, url);
request_content(data);
return false;
});
Then I add a click listener to the button with the class .insert reset the variables so instead of grabbing the page that initially loaded it grabs the page that will be loaded, then use history.pushState again to change the url that is determined by the variables.
The request_content function is a simple .load function. So when the button is clicked the variables are set, the url changes and the new content get loaded into the page while the old content disappears.
The final piece to the puzzle which took me the longest to figure out is actually the popstate function. I am still not 100% sure why it works but after hours of messing with it and finally getting it to work I am not going to question it.
window.addEventListener('popstate', function(e){
var data = e.state;
if(data === null) {
} else {
request_content(data);
}
});
This popstate function is what allows the content to come back when hitting the browsers back or forward navigation.
CSSTricks < this article at CSSTricks helped a TON when learning this method.
Thanks again to John S. for pointing me in the right direction!
for the life of me I cannot get my PHP file to be called using the ajax function. Here is my relevant HTML:
$(document).ready( function(){
$("#generate").click(function(){
alert("Been clicked");
$.ajax({
url: "filterScriptForMe.php",
success: function(data){
alert("response");
}
});
});
});
Here is my PHP file, which I can run by calling separately, and will print to the error log/echo/create the necessary image no problem when run on it's own:
error_log("script has been called");
$hello = imagecreatefrompng("./images/stock.png");
$hello = imagecreatefrompng("./images/stock.png");
imagealphablending($hello,false);
imagesavealpha($hello,true);
$x=imagecolorallocatealpha($hello,0,0,0,127);
$color = imagecolorat($hello,350,500);
for($y=0;$y<512;$y++)
for($z=0;$z<597;$z++)
{
if($color!=imagecolorat($hello,$y,$z))
{
imagesetpixel($hello,$y,$z,$x);
}
}
imagepng($hello,"done.png");
echo "done";
I am beginning to wonder if there is a problem on my server at this point. When run it will print the first alert saying "been clicked" but it does not seem to be running the php script as I get no output to my log files when clicking the button from the html file, as opposed to visiting the php directly in the broswer. Both the html and php are in the same directory, and I have double checked the names to make sure they are correct.
I know other jQuery functions are working on the page as well, as I've been successful in getting some jQueryUI elements to display and respond to manipulation using jQuery alone. Added to that the first alert seems to be firing, so I'm fairly sure the library/code is in there. I've tried going through with firebug, but it's a little beyond me when it starts getting deep into the library and I lose track of what's being done and why.
Any help that you can provide would be much appreciated, at least to get the PHP file called from the html page. Thanks!
I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});
Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).
Okay, i have a job to do before tomorrow morning..
i'm working on some jquery.
Where i load some external file data..
What i really want to know, is how am i going to load some data when i $.post / or $.get some data through jquery
Send request into jquery hey
and the same time change the url browser to ex. mywebsite.com/prices/ without making the refresh on the page
is it possible, and how to do ?
// edit (not working)
<li> <span>prices</span></li>
jquery: $('a.prices').click(function(e) {
e.preventDefault();
$.view.show('prices');
});`
but can see that some of the others samples are not that easy to make it work..
You can do it like this:
hey
$('a.priceLink').click(function(e) {
e.preventDefault();
$.view.load('prices');
});
When the user click the link, the normal URL will be shown on the browser line, but won't get visited (because of preventDefault) and $.view.load('prices'); will thus load in that content without refreshing the page.
EDIT: #William - please try this:
<li><span>prices</span></li>
$('a.prices').click(function(e) {
e.preventDefault();
$.view.show('prices');
});
You can use a jQuery plugin called URL Utils - there's also a great screencast that shows you how to use it.
As far as I know, you can only change the url for the anchor part (www.url.com/#anchor), and nothing else (without a browser refresh). Perhaps you can use SWFAddress for your purposes?
i found the solution!!
http://nix.lv/history/demo.html
took me about 10min to install, and it just work perfectly..(i did some mod )
solution:
<li><span>prices</span></li>
jquery(download the plugin at the link above):
$.history.init(pageload);
// PageLoad function
function pageload(hash) {
// hash doesn't contain the first # character.
if(hash) {
$.view.show(hash); // load pages
} else {
// start page
$.view.show(load_from_start);
}
}
try it.. :)