I have been trying to practice jquery using the .get() function but it's not working. Here is my code:
<html>
<head>
<title>Testing Site</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php", function(data){
$('body')
.append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
</script>
</head>
<body>
<span id="hello">Hello World!</span>
<input type="button" id="id" value="Click Here"></input>
</body>
</html>
I basically modified the .get() example on the jquery api site. But when I click the button nothing happens! (There must be something wrong because the background color isn't changing either...) I have the correct path names and I copyed the correct php file:
<?php echo json_encode(array("name"=>"John","time"=>"2pm"));
?>
I also tried implementing an example on http://www.chazzuka.com/ajaxify-your-web-pages-using-jquery-88/ which used the .get() which didn't work. On firefox nothing happened and on Google Chrome it only worked part way...
I'm not sure if anyone cares to try to implement that code, but that code made me wonder about this .get() function: how does it work? In that example it is supposed to retrieve info from a plain html file. I assumed that it would only work for something like a php file which made the server send back info when you make the call "echo..."
Since your code is in the head of your page, it will execute prior to the DOM being created. You need to make your code wait until the DOM is ready. You can do this by wrapping your code in document.ready as so:
$(function(){
// code goes here
});
The problem is that the script is not even getting called because the binding happens before the page is fully loaded.
You'll need to wrap your code in a
$(document).ready(function() {
// your code
});
block.
Check out the jQuery website for more on .ready
You're not waiting for DOM ready. When your code runs, $("#id") does not return anything, since that div hasn't been loaded yet.
Wrap your code in $(document).ready(function(){}):
$(document).ready(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time )
.css('background-color', 'red');
}, "json");
});
});
You need to put the click event binding in the document ready event of jQuery.
With the current code, when you are trying to bind the click event to #id element, #id is not yet available in DOM hence jQuery cannot find the element.
Try this:
$(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
Your script is executing before the element exists.
Move the <script> to the end of the <body>.
Wrap your code in $(function(){ }) because element should be available to jQuery for it to attach the event handler. This will execute the code when DOM is ready.
$(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
Javascript is executed as it is come to in the document. You want to use jQuery's ready function to have your script wait for the DOM to be ready.
$(document).ready(function(){
// Code to execute
});
Or use the shortcut (functions exactly the same as above).
$(function(){
// Code to execute
});
You need to put the eventhandler in $(document).ready(function() {}); and use backgroundColor instead of background-color. In Javascript CSS keys do not have "-" in it, instead they're written together and the second word thick - like backgroundColor or textShadow ;)
$(document).ready(function() {
$("#id").click(function(){
$('#hello').css('backgroundColor', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('backgroundColor', 'red');
}, "json");
});
});
should work (untested)
Is the #id-element embedded in the site, or post-loaded with Ajax? If so, you have to use the following code:
$(document).ready(function() {
$("#id").live({
click: function(){
$('#hello').css('backgroundColor', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('backgroundColor', 'red');
},
"json"
);
}
});
});
Related
Dear Coders!
The purpose of my code:
Get URL of files listed in specific folder, then assign them to an Array in javascript.
How I'm imagining it:
JavaScript function in test.php uses $.post() method to send a value to getURL.php file. After this, getURL.php uses this value to get specific file URLs in a specific folder. I'm getting the result(s) in the $.post() methods function(data) parameter. After this, the resulted value of the "data" is (/would be used) in JavaScript.
The problem:
Inside the $.post() methods function: function(data,status) I'm satisfied with the result of the returned value of the data parameter; the PROBLEM is that I can't assign it's value outside this function:function (data,status)`.
TEST.php
<script src="jquery-1.9.1.js">
</script>
<script type="text/javascript">
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
alert (imgPath);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
</script>
getURL.php
<?php
if(isset($_POST["x"])){
$queryGlob='img/'.$_POST["x"].'/batch/*.jpg';
foreach (glob($queryGlob) as $filename) {
$imgFiles=json_encode($filename);
$imgFiles=str_replace('\/','/',$imgFiles);
echo $imgFiles;
}
//$data = str_replace('\\/', '/', json_encode(glob('img/'.$_POST["x"].'/batch/*.jpg')));
}
else{
$imgFiles="FAIL";
echo $imgFiles;
}
?>
Note: for testing I'm using Google Chrome.
So that's all I guess, hope someone can give me a solution and possible explanation.
The post call is asynchronous, so in your code here:
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
...the alert occurs before the post call has completed, and so shows the old value of imgPath. What you want to do is pass a function into getTargetUrl that it will call when the post completes, and put the subsequent code in there.
Something like this:
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
callback();
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function() {
alert(imgPath);
});
});
And you can do away with the global variable entirely by doing what post does and passing the data back as an argument:
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
callback(data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function(path) {
alert(path);
});
});
No, AJAX is asynchronous meaning that the $.post method will return immediately. If you want to use the results of an AJAX call, the only safe place to do so is inside the success callback. Do not attempt to assign the result to global variables.
So you should put the alert inside the success callback.
As explained by others the reason for this behavior is the asynchronous nature of ajax requests.
My solution will to return the ajax promise request from getTargetUrl and use it to register callback methods
function getTargetUrl(szolg){
return $.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
alert (data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a).done(function(data){
alert('from callback' + data);
});
});
With this javascript I'm printing list of records:
<script type="text/javascript">
$(document).ready(function(){
function hide(){
$('#friend_list').fadeIn(100);
$('#friend_list').load("friend_list.php");
};
setInterval( hide,100 );
});
</script>
in friend_list.php I'm getting all the records relevant for user and returning it like this:
echo "<div class='friend' id='friend'>" . $a["username"] . "<input type='hidden' value='$id'/>" . "</div>";
And I'm using this simple script to make overlay:
<script type="text/javascript">
$(document).ready(function(){
function overlayerOn(){
$('#overlayer').fadeIn(800);
}
function overlayerOff(){
$('#overlayer').fadeOut(800);
};
$('#board').click(function(e){e.stopPropagation();});
$('.friend').click(function(e){
e.preventDefault();
overlayerOn();
var $br = $('#board');
$br.css('display', 'block');
});
$('#overlayer').click(function(e){
overlayerOff();});
});
</script>
Overlay is working as long as I trigger it with some other id or class than the one used from friend_list.php. But that is the one I need. Any idea why overlay is not working when triggered by class .friend?
Thank you...
Use (live is deprecated)
$('.friend').live('click', function(e){
// your code
});
If you are using latest version of jquery then use
$('body').on('click', 'div.friend' , function(e){
// your code
});
It's happening because you are loading content dynamically using
$('#friend_list').load("friend_list.php");
so click is not working because those contents were not in the DOM when it was loaded.
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()
so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);
I am attempting to get a link to fire JQuery's .click() function so that I can call another script behind the scenes. All of the JQuery is generated dynamically by PHP.
The code looks correct, but the .click is not firing.
This is the code that generates the jquery:
$jscript = "$(\"".$server ."Restart\").click(function()
{
$.get(\"modules/test.php\", {command: \"RESTART\", server: \"$server\"},
function(data){
alert(\"Data Sent: \" + data);
}
);
});
";
This is the code as it looks after generation (with just an alert right now because I can't get it to do anything):
$("critRestart").click(function()
{
$.get("modules/test.php", {command: "RESTART", server: "crit"},
function(data){
alert("Data Sent: " + data);
}
);
});
This is the link that is clicked on that should be firing that event:
<div id="critRestart">RESTART</div>
Can anyone help?
You need a # in an #id selector, like this:
$("#critRestart").click(function() {
Without the #, it's looking for a <critRestart> element (an element selector).