i use a ajax refresh like this:
<script language="JavaScript">
$(document).ready(function() {
var refreshId = setInterval(function() {
$("#refresh_technik").load('refresh/technik.php');
}, 1000);
});
</script>
I have a dashboard, in my Dashboard i include the top_navigation.php and the div "refresh_id" is within the top_navigation.php.
The refresh/technik.php looks like:
$db_3s = new Database("3s");
$anzahl_stoerungen = $db_3s->executeQuery("SELECT * FROM 3s_stoerungen WHERE status = 'open' ");
$stoerungen_gesamt_aktuell = $anzahl_stoerungen->getRowCount();
echo $stoerungen_gesamt_aktuell;
In my top_navigation.php i can see on the right top the value from $stoerungen_gesamt_aktuell. It works fine.
But now i will do some other php stuff with the $stoerungen_gesamt_aktuell on the dashboard.php. But it's not possible! The $stoerungen_gesamt_aktuell is empty! It's also not possible to use the variable within the top_navigation.php.
Greetings
Dennis
It sounds like you are trying to use the value of $stoerungen_gesamt_aktuell after it is loaded via your ajax request, other locations of the page, not just the "#refresh_technik" div. You cannot continue to use a PHP variable, that you loaded through ajax, on the dashboard.php page, as if it were part of the page itself. However, you can load the value into a JavaScript variable, and then use javacript to reuse it on the page. I recommend that instead of using the .load() function of jQuery, you actually do a full ajax request with $.get(). Then store the result of that value in a javascript variable, then, use the javascript variable elsewhere on the page, after it is loaded. Something like this looks about right:
function reuse_my_value(val) {
$('#refresh_technik').text(val);
$('#some-other-location').text(val);
// do stuff with val variable
}
// shortcut for $(document).ready(function() {
$(function() {
$.get('refresh/technik.php', function(r) {
reuse_my_value(r);
}, 'text');
});
Hopefully this will get you what you need. Let me know if I misunderstood the question.
thanks for your help. You understand it right. But i think i made a mistake with your code or i misunderstood it.
Now i take your code and combine it with mine, i think there is my mistake, or?
My main problem was, i try to write a little ajax, that inform the user about a new malfunction. Another user write a new malfunction into the database.
I found a code and it works for me:
var old_count = <?php echo $_SESSION["anzahl_technische_stoerungen"] ?>;
setInterval(function(){
$.ajax({
type : "POST",
url : "refresh/technik.php",
success : function(data){
if (data > old_count) {
$.notification(
{
title: "Error notification",
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s.",
error: true,
showTime: true,
border: true
}
);
old_count = data;
}
}
});
},1000);
My basic idea was:
1) The user log in to the system, a session will be start with the actual number of malfunctions.
2) The update function checks all new malfunctions and if there is a new one, the div will be reload and on the mainsite a php script compare the to variables.
3) The session variable will be unset every 5 minutes and make a new variable.
It was not possible to use the variable from the ajax request to comapre it with the session variable.
BUT NOW!!!!
I found the code above. It works for me and it solves my main problem.
But the Session variable (var old_count) only renew when the user reload the page. I think there will help your script.
The old_count renew all 5 minutes, and the refresh/technik.php renew all minute.
Related
I included a php form into my html code and changed it from index.html to index.php. The contact form is working well and sending everything. After submitting the user gets the message "Thank you. The message has been sent.". However, when the page is refreshed it jumps up to the header and the user has to scroll down again to see the message.
I know why this happens. A couple of days ago I had included this code:
$(document).ready(function(){
$(this).scrollTop(0);
});
I did so because when somebody visited my website he was directed to the contact form first and the page did not load at the header first. However, now, when somebody is submitting a message the page scrolls again to the top. Do you know any way to avoid this? It would be nice if the user would see the header first when visiting the website but should be redirected to the form section when submitting a message.
Thank you for your help.
Use a cookie:
https://www.w3schools.com/js/js_cookies.asp
$(document).ready(function(){
if(!getCookie(cname)){
$(this).scrollTop(0);
}
});
$( "#formID" ).submit(function( event ) {
setCookie(cname, cvalue, exdays)
});
Essentially you have two possible states. The first possible state is when you want to scroll to the top, the other is when you do not want to scroll to the top. Let's assume that you know what the condition is to be tested. In that case your code would look like:
<?php
if ($condition) {
?>
//your scrolling JS code
<?php
}
?>
Now, how could we determine $condition? an idea is to store some value in the $_SESSION of the user, which will be a logical value which will determine whether we need to scroll or not. You should check whether the value exists in $_SESSION and if not, default it to true or false (depending on your actual need).
When using jQuery, return false is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
Ref
Wrap that particular JS code block with a PHP if condition that checks whether the form has not been submitted. E.g.
<?php if (!$formSubmitted) { ?>
[JS code here]
<?php } ?>
Try this
$('form').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: "your_page.php",
data: $('form').serialize(),
success: function(response) { /*what to do on response*/ },
});
});
Here i prevent default submit with reloading and send ajax post
I have a label called price, and this label automatically updates its value every two seconds from the server. Also I have a button or link, which increases this price in database when I do click. The problem is how save the data without redirect to the same page.
My code:
<?php
echo $this->html->link('Increase price', array('controller' => 'example', 'action' => 'increase_price', $param1), array ('id' => 'btPrice'));
?>
And in ExampleController the code is
function increase_price($param1)
{
$this->autoRender = false; //Don't want a view
$example = $this->Example->findById($param1);
$example ['Example ']['price'] = $example ['Example ']['price'] + 1;
$this->Example->save($example );
}
The price is increased but cakePhp is asking me for a view, and if I do autoRender=false then my page will be blank and I want to stay on the same page.
I don't know if this is a CakePhp question or if is Jquery question. In both cases, I appreciate your help
if you don't wanna reload the page to do this, you need to use Ajax..since you've already got unique id for this, what you need to do is use Jquery Ajax to handle this.
first download jquery lib and put it into your app/webroot/js folder and load it
http://jquery.com/download/ download Jquery lib here
then you can do:
<script>
$( document ).ready(function() {
//do sth when click on #btPrice
$('#btPrice').click(function(){
$.ajax({
type:"POST",
//the function u wanna call
url:"<?php echo $this->webroot;?>example/increase_price/",
/* data you wanna pass, as your $param1 is serverSide variable,
you need to first assign to js variable then you can pass:
var param1 = '<?php echo $param1;?>';*/
data:{increase_price:param1},
success:function(data)
{
//update your div
}
});
});
});
</script>
Also you have to modify your increase_price function
As we are passing increse_price as parameter in ajax call and method is post, in your function, you have to use $_POST['increase_price'] to catch it then assign to another variable
eg: $param1 = $_POST['increase_price']; then you can use it..
Should do the trick for you
The normal flow is that when you click on a link, the browser requests a new page from the server and then renders the contents.
If you want to change something in the DOM from the client's side you need Javascript.
With the use of Javascript you can skip the complete page reload because you can request the exact information you need and then update the DOM with it. This is known as AJAX.
While you can do AJAX with plain Javascript it is usually much easier to use a Javascript framework like jQuery to make things easier.
I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
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 :).
I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});