AJAX Form Post not working - php

I've tried at least 3 ways and every time I try to get a form to post using ajax, the page always reloads and nothing is submitted.
It doesn't even return a success or error - it seems that the function isn't even being called.
Here's the code, thanks in advance.
HTML:
<form id='sig_up' name='sig_up' style='min-width:170px'>
<textarea id='sig' class='custom-scroll' style='max-height:180px;'></textarea>
<br>
<input class='btn btn-primary btn-sm' type='submit' />
</form>
jQuery/AJAX:
$('#sig_up').on('submit',function(e) {
$.ajax({
url:'update_sig.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
$.smallBox({
title : "Signature Updated",
content : "Your signature has been successfully updated.",
color : "#296191",
//timeout: 8000,
icon : "fa fa-bell swing animated"
});
},
error:function(data){
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});

Well, to send it I will attach the handler of the the form to the document (although according to the docs it doesn't matter), write the preventDefault first to avoid sending the form before anything (although I tried with it at the end, and the result is exactly the same, have to review this function).
So, the other important thing I did, and I thing is the real answer, is the change of the scope inside of the form. If you used $(this) inside of the AJAX, you're referring to the AJAX jquery handler, instead to the form, I changed it to show how it changes. I also added an error console.log to check what is wrong just in case. I tried the code below and it sends the call in my localhost.
$(document).on('submit', '#sig_up', function(e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: 'update_sig.php',
data: $form.serialize(),
type: 'POST',
success:function(data){
console.log('ok');
// $.smallBox({
// title : "Signature Updated",
// content : "Your signature has been successfully updated.",
// color : "#296191",
// //timeout: 8000,
// icon : "fa fa-bell swing animated"
// });
},
error:function(data){
console.log(data);
}
});
});

Have you tried it with stopImmediatePropagation() ?
$('#sig_up').on('submit',function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
url: 'update_sig.php',
data: $(this).serialize(),
type: 'POST',
success:function(data){
console.log("Success");
},
error:function(data){
console.error("Error");
}
});
});

$('#sig_up').on('submit',function(e) {
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
var that = this;
$.ajax({
url:'update_sig.php',
data:$(that).serialize(),
type:'POST',
success:function(data){
$.smallBox({
title : "Signature Updated",
content : "Your signature has been successfully updated.",
color : "#296191",
//timeout: 8000,
icon : "fa fa-bell swing animated"
});
},
error:function(data){
}
});
});

Related

add waiting message before load remote data in bootstrap modal box

I have this code for load remote php data into bootstrap modal box:
$(function() {
$(window).bind("resize", function() {
if ($(this).width() < 400) {
$('#tabs-content').removeClass('col-xs-10').addClass('col-xs-12')
} else {
$('#tabs-content').removeClass('col-xs-12').addClass('col-xs-10')
}
}).resize();
});
$(function() {
$(document).on('click', '.push', function(e) {
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'post',
url: 'details.php', // in here you should put your query
data: {
'bookid': id,
'lang': 'fa',
'csrf_token': 'MTQ0OTQxNDQ0MUVvN2JwNXNJRHVxMDZmOXFpQm1ROFNNTk1UZ3lPMGZO'
},
success: function(r) {
// now you can show output in your modal
$('#bookdetails').modal({
backdrop: 'static',
keyboard: false
}) // put your modal id
$('.something').show().html(r);
}
});
});
});
This worked for me But I need to show loading message/image before load data.
How do add waiting message/icon?!
You just need to show image/message before Ajax call and hide it in success: function(r)
Assuming you have image which to show before modal load, image HTML e.g
<img class="progress" src="http://downgraf.com/wp-content/uploads/2014/09/01-progress.gif" style="display:none;">
and in JS, just show image with .show() function and after modal load in success: function(r) hide is with .hide() function
$(document).on('click', '.push', function(e) {
e.preventDefault();
var id = $(this).attr('id');
$(".progress").show(); // <-- Show progress image
$.ajax({
type: 'post',
url: 'details.php', // in here you should put your query
data: {
'bookid': id,
'lang': 'fa',
'csrf_token': 'MTQ0OTQxNDQ0MUVvN2JwNXNJRHVxMDZmOXFpQm1ROFNNTk1UZ3lPMGZO'
},
success: function(r) {
// now you can show output in your modal
$('#bookdetails').modal({
backdrop: 'static',
keyboard: false
}) // put your modal id
$('.something').show().html(r);
$(".progress").hide(); // <-- Hide progress image
}
});
});
Minimal example with delay and fade

jQuery ajaxStart with php code

I am reading about Ajax Events from the jQuery docs.
My jQuery code with some HTML:
<p style="display:none">Loading...</p>
<div></div>
$(document).ready(function() {
$("p")
.ajaxStart(function(){
$(this).show();
})
.ajaxStop(function(){
$(this).hide();
});
$.ajax({
url : 'http://localhost/xampp/web_development/new_study_2014/my_files/test.php',
data : {id : 123},
type : "GET",
dataType : "html",
success: function(response) {
$("div").hide().html(response).fadeIn(1500);
},
error: function(xhr, status, errorThrown) {
console.log( xhr + status + errorThrown );
},
complete: function() {
console.log( );
}
});
});
The PHP:
<?php
sleep(1);
echo "<p> his name is jack</p>";
?>
I wanted the paragraph that says Loading... to display when the ajax request starts and hides when it is finished. As described in the jQuery docs. Yet it does none of the two and displays "his name is jack" from the php page. What am I doing wrong?
The target of the ajaxStart event is the document, not a particular element, so using $(this) in the handler won't work. Change it to select the specific element.
jQuery:
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
HTML:
<p id="loading" style="display: none;">Loading...</p>

issue regarding PHP, Jquery and Ajax.

I have an issue at the moment regarding PHP, Jquery and Ajax.
I have a a div at the bottom of my page that has data in it from a database, now for every iteration of the data a new div is formed, the div has an id of 'pagestatus' and has an auto increment next to it so the id changes for each div like so: 'pagestatus0', 'pagestatus1' etc.
Now I'm not completely new to Jquery as I have used it to make pages more interactive and I've used Ajax to update a MySQL database.
I'm having trouble with the code though, I would like it go something like this:
Button is clicked in div
Button fades in (or div, which ever is easier)
A hidden div with a loading gif appears underneath
Ajax calls to the php file to make changes to the database
jquery then fades the loading gif back out and fades the button back in
I have wrote some code for it but I think I am going wrong somewhere, could someone see what I am doing wrong and let me know how to fix it.
Here is my Jquery:
$(document).ready(function(){
for(i=0;i<$('#changestatusoff').val();i++){
(function(x){
$('#changestatusoff'+x).click(function(){
$('#changestatusoff'+x).fadeOut('slow',function(){
$('#loadingstatus').fadeIn('slow',function(){
$.ajax
({
type: "POST",
url: '.php',
data: {'changestatusoff': changestatusoff},
success: function(data) {
return data;
},
error: function() {
alert('Error occured');
}
$('#loadingstatus').fadeOut('slow',function(){
$('#changestatusoff'+x).fadeIn('slow',function();
});
});
});
});
});
});
}
})(i);
});
And here is the button in the div:
<input type='button' value='Offline' id='changestatusoff".$count."' style='background: none repeat scroll 0% 0% rgb(0, 118, 188); color: rgb(255, 255, 255); border: 1px solid rgb(0, 0, 0); font-weight: bold; cursor: pointer; margin:5px;'/>
Any help is appreciated
As the others mentioned, we have no idea what you are submitting ;-)
Use a class, which means it dosent have to make a new bind for each item, it can do it all at once.
You could do something like:
$(function() {
//set loading
var $loading = $('#loadingstatus');
//on changeStatus click
$('.changeStatus').click( function(e) {
//since we dont have a form, disable default behaviour
e.preventDefault();
//set $this as the item clicked
var $this = $(this);
//fadeIn loading, fadeout the item
$this.fadeOut();
$loading.fadeIn();
//make ajax request
$.ajax
({
type: "POST",
url: 'yourPhpFile.php',
data: {'changestatusoff': $(this).val()},
success: function(data) {
//Do something with data?
$loading.fadeOut();
$this.fadeIn();
},
error: function() {
//Do nothing, and tell an error happened
alert('An error occured');
$loading.fadeOut();
$this.fadeIn();
}
});
});
});
I think you need to check data: {'changestatusoff': changestatusoff} and try changing it to data: {changestatusoff: 'changestatusoff'}
If you want to change loading gif back, then you should put the last two lines:
$('#loadingstatus').fadeOut('slow',function(){
$('#changestatusoff'+x).fadeIn('slow',function();
in completed callback, not after ajax call.
$.ajax
({
type: "POST",
url: '.php',
data: {'changestatusoff': changestatusoff},
success: function(data) {
return data;
},
error: function() {
alert('Error occured');
},
completed: function() {
$('#loadingstatus').fadeOut('slow',function(){
$.('#changestatusoff'+x).fadeIn('slow',function();
}
Try the following
$(function(){
$('#Your_Event_Source').click(function(){
$(this).fadeOut(600);
$('#loadingstatus').fadeIn(600);
$.post('you_file.php',{changestatusoff: 'yourValue'},function(data){
if(data.success == 'yes'){
alert(data.message);
$('#Your_Event_Source').fadeIn(600);
$('#loadingstatus').fadeOut(600);
}else{
alert('failed'+ data.message);
$('#Your_Event_Source').fadeIn(600);
$('#loadingstatus').fadeOut(600);
}
},'json');
});
});
I recommend to use 'success' in php:
$data = array('success'=>'yes','message' => 'your meaasage',...);
echo json_encode($data);

Why doesn't this jQuery AJAX work?

I don't understand why this form wont send.
The coding is very long and I don't think it would be good idea to post all of it here.
Link to form here
Link to Script here
I just tried loading the PHP file in browser and it wouldn't work. I will save it as a .txt file so you can view it. It will be # ......multiform/post.txt
On top of that, how would I send the entire form instead of stating all the values for the 'data' bit:
$.ajax({
type: 'POST',
url: 'post.php',
data: {subject:options.subject, name:$(this_id_prefix+'#adycustlname').val(), email:$(this_id_prefix+'#email').val(), message:$(this_id_prefix+'#zip').val()},
success: function(data){
Also ignore the success: function(data){ section, this form is going to be put in a slide panel so that is for what the slider should do after. I have a feeling it is wrong, but
the main issue is to get the form to send.
EDIT
$('#submit_seventh').click(function(){
//send information to server
$.ajax({
type: 'POST',
url: 'post.php',
data: $('#bob').serialize(),
success: function(data){
$(this_id_prefix+'#loading').css({display:'none'});
if( data == 'success') {
$(this_id_prefix+'#callback').show().append(options.recievedMsg);
if(options.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$(this_id_prefix+'#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$(this_id_prefix+'div#contactable_inner').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$(this_id_prefix+'#overlay').css({display: 'none'});
}
} else {
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
setTimeout(function(){
$(this_id_prefix+'.holder').show();
$(this_id_prefix+'#callback').hide().html('');
},2000);
}
},
error:function(){
$(this_id_prefix+'#loading').css({display:'none'});
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
}
});
alert('Data sent');
});
} else return false;
alert('Fail');
});
^^^^^ Why wont the above code work? ^^^^^
At the end of your script you have to replace
$('#submit_fourth').click(function(){
//send information to server
alert('Data sent');
});
with the correct URL to send to.

Posting a sub-form with jQuery

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Categories