i have a php page that redirects (if successful) to another php page like this:
header('Location: completed.php?message=Successful operation. Data inserted for user: ' . $login->get_username() . ' . See home page for infos.');
Now in completed.php i have a div that echoes the received message:
<div id="msg">
<?php echo $_GET['message']; ?>
</div>
I'm using the 'Toastmessage-plugin' : here.. , but i'm unable to display the $_GET in to the text of Toastmessage ..
I'm using this code :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="js/jquery.toastmessage.js" type="text/javascript"></script>
<link href="styles/jquery.toastmessage.css" rel="stylesheet" type="text/css" />
...
<script type="text/javascript">
function showStickyNoticeToast() {
$().toastmessage('showToast', {
text: $('#msg').val(),
sticky: true,
position: 'bottom-left',
type: 'notice',
closeText: '',
close: function () { console.log("toast is closed ..."); }
});
}
</script>
I've searched a lot , also for DOM Events and other events but i don't know what step take... maybe when the JQ function is loaded the div 'msg' has not yet received GET data ...? so how i update his value ?
The page i've read :
this and this.
I also tried with ajax but i'm less experienced in that language..
please help... :) Thanks
EDIT #charlietfl
Ajax : i've made a lot of tries... i can't find the code anymore!
Basically i call a php file with this code (take this as pseudocode):
<script type="text/javascript>
<!--
$('#choose').change(function(event) {
$.get('messages.php', { selected: $('#msg').val() },
function(data) {
$('#update').html(data); // other div wher store data
}
);
});
</script>
....
<?php
$alfa = isset($_GET['message']) ? $_GET['message'] : 'nothing';
echo $alfa;
?>
Try to pass the message with urlencode() like:
$msg = "Successful operation etc. etc.";
header("Location: completed.php?message="+urlencode($msg));
Got it: you use $("#msg").val() but DIV tags have not a "value".
Use $("#msg").text() (for plain-text)
or $("#msg").html()
to include also some HTML you may have in your code (pretty sure you need the first option).
Use .val() only with "valued" tags like <input> (works also with <textarea>).
See also: http://api.jquery.com/val/
Your issue is likely that you are trying to call the message plugin before the ajax completes since the first 'A' in ajax stands for asynchronous.
In order to allow for the time required for the ajax to complete you would need to call your message plugin within the success callback of ajax.
Add message argument to function
function showStickyNoticeToast( message ) {
$().toastmessage('showToast', {
text: message,
sticky: true,
position: 'bottom-left',
type: 'notice',
closeText: '',
close: function () { console.log("toast is closed ..."); }
});
}
$.post( url , dataToserver, function(data){
showStickyNoticeToast( $(data).text())
$('#update').html(data);
})
Related
I'm trying to get a jQuery script to update the content of an HTML paragraph tag variously according to whether or not a PHP if statement, which checks for data in a database, evaluates to true or not:
if ($num_rows > 0) { ?> // If results are returned from database...
<script>
$(document).ready(function() {
$('p.message').text('Some data'); // ... p should read 'Some data'
});
</script>
<?php else { // otherwise
<script>
$(document).ready(function() {
$('p.message').text('No data'); // ...p should read 'No data'
});
</script>
}
The contents of are intended to change dynamically without the need for a page refresh, but do not do so. Only after the page has been refreshed is the new value shown.
Any ideas as always much appreciated.
Use AJAX to get the content from PHP. You can have the success populate the data into your HTML.
What You are trying to do can be achived through Ajax. Belwo Is a simple Example
Jquery
setInterval(function(){UpdateMessage()},10000) // Will Eecute after 10 Seconds
function UpdateMessage()
{
$.ajax({
type:"POST",
url:"Script.php",
success: function(data)
{
$(".message").text(data);
}
});//END OF Second AJAX
}
HTML
<p class='message'></p>
Script.php
if ($num_rows > 0)
echo "SOME DATA";
else
echo "No Record";
above code will refresh Your Data every after 10 Seconds Without Refresh
did you try include jquery into that php file? like
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>
I have got the following code to show a dialog box when the image is clicked. Instead of running FB.ui I want to run PHP code. It's for facebook.
<html>
<head>
<style> img#share_button { cursor: pointer; } </style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxx',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
This is the image:
<img id = "share_button" src = "img.png">
And this is the code I need to change:
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').live('click', function(e){
e.preventDefault();
FB.ui({
method: 'feed',
name: 'TabPress1',
link: 'http://www.hyperarts.com/',
picture: 'http://www.hyperarts.com/',
caption: 'I am a fan of TabPress',
description: 'TabPress -- Gotta love it!',
message: ''
});
});
});
</script>
</body>
</html>
I don't know any JS, hope you can help me!
If you don't know any javascript, perhaps it's best if you check out some beginner tutorials, like those at http://net.tutsplus.com/category/tutorials/javascript-ajax/?tag=basix , but in regard to your question...
It looks like your using jQuery. The best way to do what your describing is to use AJAX, and jQuery has nice functionality for that.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourImage")
now, to listen for when it's been clicked,
$("#TheIdOfYourImage").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
Why you don't use an href attribute with removing underlying and coloring of the link and launch your php script?
As you have jQuery already there: Send an AJAX-Request:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
$('#share_button').live('click', function(e) {
e.preventDefault();
$.ajax('/path/to/your/script.php');
});
});
//]]>
</script>
cf. the jQuery documentation for further information: http://api.jquery.com/jQuery.ajax/
Additionally I added CDATA-Tags to avoid problems with HTML-Special-Chars. These special chars would normally have to be encoded.
The FB.ui(param1,param2) method can take two parameters. You've specified the first one that dictates how the feed dialog is displayed. Param2 can be your callback function
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'http://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
In the code switch for post was published, you can then use jQuery to make an AJAX call to one of your PHP pages. See: http://api.jquery.com/jQuery.ajax/
to run a javascript function when button is clicked:
<img id = "share_button" src = "img.png" onclick = "dothis()">
here is some basic javascript:
<script type = "text/javascript">
function dothis(){
alert("Button pressed");
}
</script>
This is just some basic javascript that will make a message appear on the screen when the button is clicked
EDIT: It appears you want to use JSON. Take a look at this:
http://ditio.net/2008/07/17/php-json-and-javascript-usage/
Based on your comments, I think you want to do something like this:
$(document).ready(function(){
// on click
$('#share_button').live('click', function(e){
e.preventDefault();
// any parameters you need to pass to your php script,
// you can omit the data parameter if you don't need it
var data = { param1: "a", param2: 2 };
// start the ajax request
$.post("your/script.php", data, function() {
// when the ajax request completes, show the FB dialog
FB.ui({
method: 'feed',
name: 'TabPress1',
link: 'http://www.hyperarts.com/',
picture: 'http://www.hyperarts.com/',
caption: 'I am a fan of TabPress',
description: 'TabPress -- Gotta love it!',
message: ''
});
});
});
});
Relevant javascript references:
.live()
$.post()
FB.ui()
I have made a code --
<?php
header("Content-type: text/javascript");
require_once('../php/config.php');
$domail_theme = $_GET['theme'];
?>
<?php
if($domail_theme=='default')
{
?>
$('div.theme_content').mouseover(function () {
$(this).stop().animate({
backgroundColor : '#234'
}, 250, 'linear', function() { });
});
$('div.').mouseout(function () {
$(this).animate({
backgroundColor : '#ddd'
}, 400, 'linear', function() { });
});
<?php
}
?>
And here is the script including tag --
<script src="domail_res/scripts/java/settings_form_css.php?theme=default"></script>
The thing I want is that when I mouse over on the div element with class theme_content it's background changes according to the given one in the animate function. It is working for the input element but that script is original javascript and in this I have included php that's why I'm thinking whether the php code I used is wrong or my javascript. Also when I include this code in javascript file it works correctly. And by the I'm including the script tag in between the body tag, is it wrong? Please help me out with this one.
Thanks in advance!
Try to put it inside script. <script></script>
And also it's possible that DOM might not have been loaded. so try putting wrappint in $(document).ready(function() { /*Your code here*/})
And also put alert('hello'); to check if that code is being executed or not. It might be useful in debugging.
The most likly explanation is that 'theme" is not set to 'default' in your URL request.
This should be easy to check. Also you can "View" -> "Page Source" in your browser and look at the html your php program is actually generating. If my guess is right you won't see your mouseover function in the page.
Hi you should write like this:-
<?php
if($domail_theme=='default')
{
?>
<script>
$('div.theme_content').mouseover(function () {
$(this).stop().animate({
backgroundColor : '#234'
}, 250, 'linear', function() { });
});
$('div.').mouseout(function () {
$(this).animate({
backgroundColor : '#ddd'
}, 400, 'linear', function() { });
});
</script>
<?php
}
?>
Just need add tag between on your php if statement.
Hope can help you.
Does it work better if you add type='text/javascript' to your script tag?
<script type='text/javascript' src="domail_res/scripts/java/settings_form_css.php?theme=default"></script>
Why not just put the php logic in your main file and include the javascript as plain javascript?
<?php
if($domail_theme=='default')
{
?>
<script type='text/javascript' src="domail_res/scripts/java/settings_form_css.js"></script>
<?php
}
?>
Seems like overcomplicating things
i got this script, which i found in the web:
<script type="text/javascript">
$(document).ready(
function () {
$('a.closeEl').bind('click', toggleContent);
$('div.groupWrapper').Sortable(
{
accept: 'groupItem',
helperclass: 'sortHelper',
activeclass : 'sortableactive',
hoverclass : 'sortablehover',
handle: 'div.itemHeader',
tolerance: 'pointer',
onChange : function(ser)
{
},
onStart : function()
{
$.iAutoscroller.start(this, document.getElementsByTagName('body'));
},
onStop : function()
{
$.iAutoscroller.stop();
}
}
);
}
);
var toggleContent = function(e)
{
var targetContent = $('div.itemContent', this.parentNode.parentNode);
if (targetContent.css('display') == 'none') {
targetContent.slideDown(300);
$(this).html('[-]');
} else {
targetContent.slideUp(300);
$(this).html('[+]');
}
return false;
};
function serialize(s)
{
serial = $.SortSerialize(s);
alert(serial.hash);
};
</script>
<div class="serializer">
<a href="#" onClick="serialize(); return false;" >serialize all lists</a>
</div>
<script language="JavaScript" type="text/javascript">var client_id = 1;</script>
at the bottom of the script is the "function serialize", which is called by clicking on the link below. Can someone tell me, how can i send the variable "serial.hash" to a php-file to save it in mysql-database?
many thanks, maschek
Yes as Yacoby says $.post() or jQuery.post
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Use Ajax to send request to a PHP script which submits the data to a database. The JQuery documents contain a lot of examples. If you use a HTTP GET request, be warned there is a limit on the amount of data you can pass. This is browser dependant. I would recommend using jQuery.post as the method of sending data.
All the PHP script has to do is read the variables either from $_GET or $_POST (whichever method you use), sanitize them and submit them to the database.
Actually, it seems very simple now:
$.post("test.php",{'func':'serial'},function(data){
alert(data);
});