$.ajax POST is not posting - php

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

Related

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();
}
});

Call ajax after success

I made an ajax request to get the name of each button I click...
Then I want to put everything in that url into "#Container".(url define a page that has some codes)
It works for me at the first time...but for the other times I have to reload the page to show me the details of each button and it doesn't show me details of other buttons that clicked after first desired button..
$(function () {
$('button').click(function () {
var data= $(this).val();
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function (data) {
$('#container').html(data);
}
});
});
});
What should I do?
Is there something preventing of running the ajax for next times ?
Try with $(document).on('click', instead of $('button').click like below
$(function () {
$(document).on('click','button',function () {
var data= $(this).val();
alert(data);
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);}
});
});
});
You will need to re-bind ajax event because of its re-rendering DOM after an ajax request completes. All those elements under #container are not virtual part of DOM and your click event only works for pre-existed elements.
Try this
Wrap ajax event in a separate function
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
clickEvent(); //note this function attachment I added below
}
});
}
You can wrap your click event into a function
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
Now js looks like
<script>
$(function(){
clickEvent();
});
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
}
});
}
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
</script>
Also I see you are passing ajax data as $('button').val() which is not correct. Use a input type text if you want to send a data to server.

POST form on button click using jquery ajax

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);
});
});

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

Form validation with jQuery and php

I have a form which I'm validating using jQuery and php. So basically if the php echoes "input must be filled" the jQuery should put a red border around that input, but the thing works only after submitting the form two times.
I explain: if I submit with input unfilled the php file echoes "input must be filled", but only if I press again the submit button - the input goes red.
$("form#maj_email").submit(function(){
var _data = $(this).serialize()
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
})
})
It looks like the form is being submitted via the form instead of your ajax call. You need to prevent this behavior for this to work:
$("form#maj_email").submit(function(e){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
});
e.preventDefault();
return false;
})

Categories