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).
Related
I am trying to get the contents of a div and send that to ajax.
Here is a sample code of ajax that sends data but how can I put the html contents of a div in this post and send it to another php script via ajax?
I need to send ALL the HTML in the "sortable" ui and not just the text.
<ul id="sortable">
<li class="ui-state-default">Hello, please send me to Ajax! :)</li>
</ul>
$("button").click(function()
{
$.post("get_sorted_content.php", // Example script
{
data: $("#sortable").html(); // My NEEDED content - Does not work!
function(data)
{
alert("Data: " + data + ");
});
});
Again, This code may be missing some elements but regardless it doesn't work. It's just an example showing what I am trying to do.
I'll use the AJAX method as an example here because I think it's a little clearer about what you want to do. Let's retrieve the li contents and sent it to your PHP script.
Don't bind to the button element, that is not very specific at all and will bind to any button on the page. Instead, give it an id and bind to that.
Your main problem is that you're getting the HTML of the ul with id sortable, not the specific li element you're after.
<ul id="sortable">
<li class="ui-state-default">Hello, please send me to Ajax! :)</li>
</ul>
<button id="clickme">Click me!</button>
// bind to the button with clickme ID
$("button#clickme").click(function() {
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#sortable li').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
});
Now in your PHP script, you can access that data with $_POST['yourData']:
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
EDIT: following having seen your statement: I need to send ALL the HTML in the "sortable" ui and not just the text., if you need the entire ul contents, use what you had originally:
data: {
yourData: $('ul#sortable').html();
}
Your $.post call needs to change as follows:
$.post('get_sorted_content.png',
{ data: $("#sortable").html()},
function(data){
//data is whatever you send back from php script.
}
);
if $("#sortable").html() does not work, try to escape the HTML like:
escape($("#sortable").html());
I am trying to use ajax in wordpress.
I don't get ajax response. If I have done mistake on code, please let me know.
Here is my jquery code
// ajax submitting for the name
$("#sendemp").submit(function(e) {
e.preventDefault();
var submit_val = $("#searchbox").val();
alert('submitval is ' + submit_val);
$.ajax( {
type : "POST",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'deatils_search',
user_name : submit_val
},
success : function(data) {
alert('hhh');
$('#accordion3').html(data);
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
});
Here is my php code
function deatils_search() {
$name=$_POST['user_name'];//retrive data from post array on form submitting
$jason =$name;
echo json_encode($jason) ;
//echo '</div>';
//wp_reset_query();
die();
} // end theme_custom_handler
add_action( 'wp_ajax_deatils_search', 'deatils_search' );
add_action( 'wp_ajax_nopriv_deatils_search', 'deatils_search');
I tried to print alert('hhh'); on success message in ajax call. But it doesn't print anything.
Where I have done the mistake?
Please check bellow network tab on chrome
Don't use $ as a jQuery shortcut within WordPress javascript. WordPress is set to run jQuery in noConflict mode. Replace $ with jQuery.
When I replace the following method with click method., Every thing started to work.
$("#sendemp").click(function(e) {
I am useing modal window of native joomla codes. I am displaying a form wihchi is used to send mail from one user to another. The php,css and js codes are in tmpl file (by using JDocument) of view and js is like that;
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#sendMail").click(function(){
if(document.formvalidator.isValid(this.form)){
$j("#mailSending").css("display","inline-block");
$j.ajax({
type: \'POST\',
url: \'index.php?option=mycomponent&tmpl=component&view=members\',
data: $j("form#mailForm").serialize(),
success: function(data,xhr,status){
$j("#mailSending").css("display","none");
$j("#mailMsg").css("display","inline-block");
setTimeout(function(){window.parent.SqueezeBox.close()},1000);
alert(status);
}
});
}else{
$j("#mailMsg").text("'.JText::_('OFFER_EMPTY_FIELDS').'").css("display","inline-block").delay(1000).fadeOut("slow");
}
});
});';
I am tracing the xhr with firebug when I triger the click function to loading icon is shown and task within the controller file is executed. Php file ends like that;
$send =& $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->getMessage();
} else {
echo 'Mail sent';
}
exit();
While the php function process ends the content within the modal window is changes with Mail Sent. But I want to hide the loading .gif and show a message. But the code don't do that. Any idea ?
Code to send a form with ajax and insert its returned values into a div
jQuery(function($) {
$("form[name='srchForm']").submit(function(){
$.get($(this).action, $(this).serialize() + "&tmpl=component&limitstart=0", function(data){
$m =$('#main');
$m.html(data).delay(10);
});
return false;
});
});
It is funny I love Ricardo's use of jquery instead of this "$j(document).ready(function(){})" but the point is I figured that the button which is used to trigger the ajax is not to set a type of button it has button tag but doesn't have attribute. I think it tries both ajax and normal submit process and it conficts.
Thanks for your helps and sorry for my stupit mistake.
I am working with AJAX with prototype and PHP. It is working for me but I need some small changes. Following is my running code for AJAX request:
JS/Prototype:
function ajaxRequest(url) {
new Ajax.Request( url, {
method: 'get',
onSuccess: function( transport ) {
// get json response
var json = transport.responseText.evalJSON( true );
alert(json);
},
onFailure: function() {
alert('Error with AJAX request.');
}
});
return false;
}
HTML:
<a href='javascript:ajaxRequest("/testajax/ajaxresponse");'>Testing AJAX</a>
Question:
Now I want to change my link like this:
<a href='/testajax/ajaxresponse' class='AjaxLink'>Testing AJAX</a>
So prototype function should capture click event of class='AjaxLink' links and then get href part of clicked link and proceed. How can I change my above prototype function for such kind of links.
Thanks
If you have Prototype 1.7 then this way is available:
document.on('click', 'a.AjaxLink', ajaxRequest.curry('/testajax/ajaxresponse'));
Otherwise you'll have to rely on good old Event.observe:
$$('a.AjaxLink').invoke('observe', 'click',
ajaxRequest.curry('/testajax/ajaxresponse'));
Just re-read the question and I see you want to use the href attribute. Jan Pfiefer was very close.
document.on('click', 'a.AjaxLink', function(event, element) {
return ajaxRequest(element.href);
});
This wont work. Why do you want such a link? If a link is specified in this way any click on it will follow its href and change location of actual document. Only way to prevent such a behavior then is by adding onclick again or in $(document).ready bind onclick handler, and manualy cancel the event.
UPDATE
However to bind onclick event on all links with AjaxLink class,execute request and cancel the event:
$(document).ready(function(){
$('.AjaxLink').click(
function(e){
ajaxRequest(this.href);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
);
});
This will work:
$$('a.AjaxLink').each(function(element) {
element.observe('click', function(e) {
var element = e.element()
Event.stop(e)
alert(element.href)
});
})
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"
);
}
});
});