AJAX jquery Form Post not working - javascript

I am trying to post a form using ajax.
Right now, the code I have is
$("#sub").click(function() {
var tag = $("#tagbar").val();
var opinion = $("#op").val();
alert($("#expressform").serialize());
$.post("dbfunctions.php", $("#expressform").serialize());
});
This works, but it takes a long time to post and add to the database (thats what dbfunctions does) compared to how long it took before, when I was using a form action and refreshing the page. Why is this?
Also, if I remove the alert, the script stops working completely. I can't figure out anyway in which this makes sense.
Thanks

Make sure you cancel the default action of the button by returning false from the click handler:
$("#sub").click(function() {
$.post("dbfunctions.php", $("#expressform").serialize());
return false;
});
Also instead of subscribing for submit button clicks, it's better to subscribe to the submit event of the corresponding form directly:
$("#expressform").submit(function() {
$.post(this.action, $(this).serialize());
return false;
});
This way you are no longer hardcoding any urls in your javascript files. You are simply unobtrusively AJAXifying your form.

You can use below function for submit the data
through Ajax form Submit
$('#form1').ajaxForm({
success:function(response){
$('#save_data').html(response);
});
$('#btnSubmit').click(function() {
$('#form1').submit();
});

Related

Submitting a value of input without form

I'm creating a website game and currently I am struggling with something I will name "dialogue".
Initially I tried to approach this by creating a form element, but clicking enter or submitting it ended up with page refresh, which ruins everything.
So I used inpute type text without form that looks like this:
You are
<input type="text" id="dead">
<input type="submit" onclick="dead()">
and dead function looking currently like this, later it's gonna check for certain value, and if the value is true it's gonna run another code:
var talk = document.getElementById("dead").value;
function dead() {
alert(talk);
}
And I don't know how to save input from a form so it would be detected by JS and then used as variable in boolean check. How can I solve this problem? If there is a way to use a form tag without refreshing the page that could also work.
You can handle the submit event of your form like this:
document.getElementById('yourFormId').onsubmit = function(e) {
// your code goes here...
e.preventDefault(); // this will prevent the default operation of your form within this event
return false;
}
Or create a function:
function handleForm(e) {
// your code goes here...
e.preventDefault();
return false;
}
And add this to your form tag:
<form onsubmit="return handleForm(this);">
To be able sending some value without refresh the page you can use Asynchronous JavaScript + XML (AJAX) and if you're working with pure Javascript without some frameworks you can see a good documentation about Ajax.
But of course I suggest to use some frameworks like Jquery to make your works more easier

Can I/how do I use an OnClick with an if statement in?

I am trying to create a button that when pressed deletes a database entry, when I click it I want a message to say "are you sure you want to delete this" and then if I click cancel the message goes away and nothing happens, if I click okay the deletion runs -- but also it reloads the page, I think this will require a jquery(this is what I would like it to be in ) if statement that basically says if ok is clicked then run the default and also refresh the page after the code has run.
so far I have
<button name="del" type="submit" value="1" onclick="return confirm('Are you sure you want to delete this?') "> delete</button>
Please tell me if I am going the wrong way with this and if I am not, please help me out with how to write the if, (I have infact searched for this and the information is not complete enough for me to understand, I am a PHP developer, never used any Javascript before in my life but would like to start)
EDIT: if this is a caching issue how do I solve it?
The confirmation you have is fine.
However, you're basically performing 2 requests when you press "Ok".
I'd do this one of 2 ways:
1.
Postback to the same page and use PHP to handle the $_POST data before generating the data for the page. Pseudo code:
if($_POST['userid']!= null)
deleteUser($_POST['userid']);
getUsers();
2.
Use Javascript to fire an Ajax request to another page which does the deletion of your user. Then on the "Complete" event, get JS to reload the page that you're currently on.
I think option 2 would be best. It will give you some more exposure to JavaScript too.
$.ajax({
url: "deleteuser.php?userid=1",
}).done(function() {
location.reload();
});
Or the equivilant for $.post
You don't even need to reload the page. You can use Javascript to remove the row containing the user you just deleted.
This of course uses jQuery, but jQuery is just a wrapper for Javascript
I believe your issue is more of a caching issue and reloading the page after a form submission is not efficient since you are performing an unneeded roundtrip to the server, however if that's what you want here's one way of doing it:
PS: Remove the onclick attribute on your submit button.
document.addEventListener('DOMContentLoaded', function () {
initDeletionPage(document.getElementById('the-id-of-the-form-to-target'));
});
function initDeletionPage(deletionForm) {
refreshPageIfNeeded();
deletionForm.addEventListener('submit', onSubmit);
function refreshPageIfNeeded() {
if (sessionStorage.getItem('pageRefreshNeeded')) {
sessionStorage.removeItem('pageRefreshNeeded');
location.reload();
}
}
function onSubmit(e) {
if (!confirmDeletion()) e.preventDefault();
else indicatePageRefreshNeededAfterSubmission();
}
function confirmDeletion() {
return confirm('Are you sure you want to delete this?');
}
function indicatePageRefreshNeededAfterSubmission() {
sessionStorage.setItem('pageRefreshNeeded', true);
}
}
Sorry but I asked for a more Jquery way
Ok...
$(function () {
initDeletionPage('#the-id-of-the-form-to-target');
});
function initDeletionPage(deletionForm) {
refreshPageIfNeeded();
$(deletionForm).submit(onSubmit);
function refreshPageIfNeeded() {
if (sessionStorage.getItem('pageRefreshNeeded')) {
sessionStorage.removeItem('pageRefreshNeeded');
location.reload();
}
}
function onSubmit(e) {
if (!confirmDeletion()) e.preventDefault();
else indicatePageRefreshNeededAfterSubmission();
}
function confirmDeletion() {
return confirm('Are you sure you want to delete this?');
}
function indicatePageRefreshNeededAfterSubmission() {
sessionStorage.setItem('pageRefreshNeeded', true);
}
}

Breaking out of a jquery function

I have a page with 22 different forms that use ajax to send json to my server-side code. I have one form that needs to be submitted via a normal post, i'm attempting to break out of the function and let it process normally. It appears to work fine, the form is submitted it behaves as normal, afterwords if you submit another form the page refreshes, this can be duplicated every time.
$("form").submit(function(e) {
if( $('input[name="ticketpost"]').val() === "true" ) {
return;
}
e.preventDefault();
...
ajax/json stuff
My other function to trigger the submit of the special form is as follows:
$(".TicketPost").click(function() {
$("#ticketpost").submit();
});
I thank you ahead of time for your help.
Try adding e.preventDefault also in TicketPost click function
$(".TicketPost").click(function(e) {
e.preventDefault();
$("#ticketpost").submit();
});

jQuery hide form on submit?

I have a form setup where a user can register, and on submittal, a PHP script runs which validates the user, and once that is done, it echoes a messagebox which jQuery quickly hides and then fades in over the course of 1 second. What I now want to do is to be able to hide that form on submittal, and I thought this might do it:
$(document).ready(function() {
$('div.mainsuccess,div.mainerror').hide(0).fadeIn(1000);
$('form.register').submit(function() {
$(this).hide(1000);
});
});
Where div.mainsuccess is the success message, and form.register is the form (with a class of register). Now the first line works, which tells me the script is being called, but the form is not being hidden at all. I'm doing something stupid here, but I cannot figure out what?
I've tried to look through the jQuery API documentation for submit(), but I cannot understand what is being said. Thanks.
I think the reason it may not work is because the form is submitting it's data and waiting for page to refresh... which means, it will stop all of it's javascript stuff coz it's pointless ... I could be wrong but hey, your hide would take 1 second to hide but your page could reload quicker.
$(document).ready(function() {
$('div.mainsuccess,div.mainerror').hide(0).fadeIn(1000);
$('form.register').submit(function(e) {
e.preventDefault();// will stop the form being submited...
$(this).hide(1000);
// do ajax here...
return false;
});
});
Updated
here is a list of tutorials
http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.sitepoint.com/ajax-jquery/
Videos ....
http://www.youtube.com/watch?v=0CMTQtnZ0G0
Try this:
$("form").submit(function(e){
e.preventDefault();
$(this).hide(1000);
});
You'd want to incorporate an ajax call (I'm taking post) to call the php instead of reloading the page
$('form.register').submit(function(e) {
e.preventDefault();
url = $(this).attr('action');
$.post(url,$(this).serialize(), function(data) {
alert('success');
// data will return source code of the URL so you can grab that data and put it somewhere on the script like so.
$('#result').html($(data).find('form'));//form can be replaced with anything
// #result is the id of an element you wish to return the info to
});
$(this).hide(1000);
});
And you'd be done.
More info here
Well, seems that the form refreshes after submission, so it is still there.
I suggest using something like jQuery form: http://jquery.malsup.com/form/
Read up on it and you will find how to use it, and when it is submitted, it won't refresh, and using hide() you will be able to hide it.
N.B you will need jQuery referenced in your code to use jQuery form.
Enjoy.

Could the current page not be affected when submitting a form from it?

I want to submit a form inside a page, but don't want the page to do any refresh. I just want to submit some data to the server. How can I make it?
Use AJAX for this. Cross-browser support for AJAX is a pain, and I'm not willing to demo it without a framework, but here's a jQuery example:
$("#myform").submit(function (e) {
e.preventDefault();
$.post(
url,
$(this).serialize(),
function () { /* What to do when the data is successfully posted */ }
);
});
You can just use an ajax post() to submit (POST/GET) the data to a page where the server uses this data. Also add e.preventDefault(); to stop refreshing the page from the forms action

Categories

Resources