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.
Related
A PHP page opened in my browser.
I have an HTML file with a jQuery AJAX call in it. When I post the data using AJAX, the HTML page disappear and the PHP file open instead.
I want to see the HTML result in the PHP page that I initially opened instead of opening a new HTML page.
What I have to do in my phpfile?
Thanks for help.
My HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$.post( "result.php",{ name : $('#text').val() },
function( data ) {
$('#bigdiv').html(data);
// alert(data);
});
}); //event handler
}); //document.ready
</script>
And my PHP code:
<?php
$name="";
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
}
echo "name = $name";
?>
I'm going to go ahead and assume that your button is tied to a form, so that it submits the form, and thus reloading the page, when you press it. Try adding this to your JavaScript:
$("#button").click(function(e) {
e.preventDefault();
//rest of your code...
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 using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};
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 a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.