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) {
Related
I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>
I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.
I tried to just send some information to a php file using Jquery Ajax. I wanted to send some info to the php file every time a click is made.
<script>
$(document).ready(function() {
$('#checkbox').click(function() {
$.ajax({type : "POST",
url : "test.php",
data : "ffs=somedata&ffs2=somedata2",
succes : function() {
alert("something");
}
});
});
});
</script>
<body>
<input type = "checkbox" name = "checkbox" id = "checkbox">
</body>
The php file looks like this:
<?php
echo $_POST['ffs'];
?>
Now, I see the POST going, (using firebug). I get no errors, but nothing happens in the php file. Also success is never reached, so no alert is triggered. What should I do in the php file so that I can trigger success and also see the sent info?
Typo, change
succes : function() {
to
success : function() {
And to retrieve the response from the PHP use
success : function(data) {
alert(data);
}
For more info see this
Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});