POST form on button click using jquery ajax - php

i'm trying to load form via ajax and submit form then write response to "#pagediv".
Here is my working code
$(function() {
$.ajax({
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
type: "GET",
data: { <?php echo $ajxparam; ?> },
dataType: "html",
cache: false
}).done(function( msg ) {
$("#pagediv").html(msg);
$("#savebtn").click(function(event){ event.preventDefault(); $("#testform").submit(); });
}).fail(function() {
$("#pagediv").html( "Request Failed. Please Try Again Later." );
});
});
modified code in form submit part(refer below); its not working, did i missed anything?
$(function() {
$.ajax({
url: "<?php echo $_SERVER['PHP_SELF']; ?>",
type: "GET",
data: { <?php echo $ajxparam; ?> },
dataType: "html",
cache: false
}).done(function( msg ) {
$("#pagediv").html(msg);
$("#savebtn").click(function(event){
event.preventDefault();
$("#testform").submit(function(evt) {
evt.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, $(this).serialize() );
posting.done(function( dte ) {
$("#successdiv").html(dte);
});
});
});
}).fail(function() {
$("#pagediv").html( "Request Failed. Please Try Again Later." );
});
});
Note:- Form POST URL is different from ajax load main page.

Inside your click event handler you're adding a submit event handler and not actually submitting the form. Since you're uploading the data via ajax on a button click just call the ajax in the button click callback.
$("#savebtn").click(function(event){
event.preventDefault();
var $form = $("#testform"),
url = $form.attr( 'action' );
var posting = $.post( url, $form.serialize() );
posting.done(function( dte ) {
$("#successdiv").html(dte);
});
});

Related

Wordpress ajax request not working properly

I am new to wordpress, i make a ajax request on click button and it print the data, but ajax is not giving me any response. Please help me to find out the error.
Here is my code
add_action("wp_ajax_delivery_options", "delivery_options");
add_action("wp_ajax_nopriv_delivery_options", "delivery_options");
function delivery_options()
{
echo json_encode(array('type' => 'success'));
wp_die();
}
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/js/custom.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
Ajax
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});
})(jQuery);
Any solution appreciated!
you have to pass "callback function name" in data: { action: 'delivery_options', delivery_option: data },
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { action: 'delivery_options', delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});})(jQuery);

confirm delete with ajax

How can we confirm the deletion of an array element result of an ajax call?
I have an array :
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({
data: data
});
}
});
In my recursive.php I have this code:
$arr = array(
'text' => '<img src="img/pdf.png">'.$sub_data["n_doc"].'
'
);
In this <a href, I need to confirm before deleting.
in delete.php i have:
$sql = mysqli_query($conn, ' DELETE FROM saisie WHERE code = "'.$doc.'" ') or die (mysqli_error());
Make another ajax call in the success function:
$(document).ready(function(){
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$(document).on('click', '.btn_supp', function(){
if(confirm("do you want to delete this file?")){
$.ajax({
url: "delete.php",
method:"POST",
dataType: "json",
success: function(data)
{
alert("deleted");
});
}
});
}
});
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});`
The easiest method of accomplishing displaying a confirmation when AJAX adds to the DOM, would be to bind a delegated event listener in your view's DOMReady function.
Since jQuery binds event handlers during the DOMReady state, it will not bind additional elements in the ajax.success function, unless the response includes javascript and the dataType is 'script' or you parse the data variable from the success function and an event is manually added.
This assumes an element with an id="treeview", already exists.
<script type="text/javascript">
jQuery(function($) {
$(document).on('click', 'a[href^="delete.php"]', function(e) {
return window.confirm('Are you sure you want to delete this file?');
});
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data) {
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});
});
</script>
<div id="treeview"></div>
This works by telling jQuery to monitor all of the clicks inside of the #treeview element, for a triggering element of <a href="delete.php">. Specifically href^="delete.php" means an <a> element, with an href that begins with delete.php. If one is found, the callback function is executed and the confirmation dialog is displayed.
If you add a class attribute to your recursive.php anchor element, you can replace a[href^="delete.php"] with a.classname.
Example https://jsfiddle.net/ub1hw9tn/
$arr = array(
'text' => '<img src="img/pdf.png"><a class="delete" href="delete.php?doc='.$sub_data["code"].'" target="_blank">'.$sub_data["n_doc"].'</a>'
);
Then in your javascript
$(document).on('click', 'a.delete', function(e) {
if (!window.confirm('Are you sure you want to delete this file?')) {
e.preventDefault();
}
});

jQuery Ajax [object Object] error

I have a form with most types of inputs like checkboxes, selectors, file uploads and others. I want to post the form without page to refresh and here is my code:
$(document).ready(function() {
jQuery.noConflict();
var form = $('#form1111');
var submit = $('#submit1111');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '../ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(),
beforeSend: function(){
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data) {
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e) {
alert(e);
}
});
});
});
But I get an [object Object] in an alert after pressing the submit button. Any suggestions will be appreciated.

$.ajax POST is not posting

This is exactly what the title describes, when I hit submit, and use php file to echo the result its empty.
$( "form#fileupload" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( 'form#fileupload' ).serialize();
$.ajax({
url: 'create_adgroup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#footer").html(returndata);
}
});
return false;
});
and the php is as such:
ECHO "PRINT POST: ".print_r($_POST);
echo "le titre: ".$_POST['title'];
any suggestions please the alert returns the serialized string and it has all the data and title is one of them.
Try with this, usually i did the ajax POST with this kind of code:
$( "form#fileupload" ).on( "submit", function( event ) {
$.post('create_adgroup.php', $('form#fileupload').serialize(), function(data) {
$('#footer').html(data);
});
event.preventDefault();
return false;
});
For uploading file using ajax I prefer using jquery.form.js plugin.
Reference

post page through ajax

hi i want to submit the page through following code but i can't get post data on ajax.php
please tell me where i am wrong
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
data:{items:item},
onComplete: function(res)
{
////Code
}
to keep it simple and fast you can use open source jquery.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
check links below
- http://api.jquery.com/category/ajax/
http://api.jquery.com/jQuery.post/
example
<script>
$(document).ready(function() {
$('#checkbox').click(function() {
$.ajax({type : "POST",
url : "test.php",
data : "ffs=somedata&ffs2=somedata2",
success : function() {
alert("something");
}
});
});
});
</script>
<body>
<input type = "checkbox" name = "checkbox" id = "checkbox">
</body>
Mention the framework you are using, assuming you are using prototype, try below code
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
parameters:{items:item},
onComplete: function(res)
{
////Code
}
});

Categories