I have a form loaded from AJAX. On this form there is a input type button which i would like to manage like it
$("#button_id").on("click",function(){..});
but it's does not work...
My question is how to do this work?
Javascript/Jquery load form code
function openForm('commandForm')
{
$.ajax({
type: "POST",
url: "./forms/commandForm.php",
data: $('#'+frm).
dataType: "html",
beforeSend: function(msg){
$('#ResponseDiv').html('Loding....');
},
success: function(back_data){
$('#ResponseDiv').html(back_data);
}
});
}
commandForm.php
<form id="commandForm" action="postCommand.php" method="post" >
.....
....
<button type="Button" id="postButton" />
</form>
Jquery on postButton onclick
$(document).ready(function () {
$('#postButton').on("click", function (e) {
/*....*/
}); //This don't work
}
PS: I don't want submit the form directly! Just make my own checkform running in my javascript function...out of here. So i want only that the button react on the Onclick ...so to do an alert for example or any javacript function else
Solved my problem with jquery event delagation
More infos here.
Event binding on dynamically created elements?
Now i understood.
This will help you-
$(document).ready(function () {
$("#id").click(function (e) {
//.........
}); //This will work
}
Related
I am making an Ajax call to a PHP file that checks a condition and runs a query a MySQL query if the conditions are met.
The query updates a table in my DB with a new value. This all works great. I would like to know how to show the new value in the current page without having to manually reload. Code is Below.
The variable I am updating is $trialExpiry
HTML/PHP
<h4 class="sbText mt-10">Trial End Date: <?php echo date("d/m/Y",
strtotime($trialExpiry)); ?></h4>
<form id='promocode'>
<input type='text' class='sbInput' placeholder='Promo Code' name='promocode'>
<input type='hidden' name='userid' value='<?php echo $userID; ?>'>
<button class='btn sbSubmit'>Submit</button>
</form>
JQUERY
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function () {
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
}
});
});
});
</script>
Thanks so much.
You don't want to do the live updating with PHP variables, since those are only refreshed when the page is reloaded. Instead, you want to update an element's value via AJAX. As far as I can tell, you want to update the expiration date. If you don't, just let me know and I can change the code to whatever it's supposed to do.
Here's the "control flow" of this functionality:
(Entry point) User clicks 'Submit', jQuery event handler fires
jQuery AJAX function is called and sends the promo code to a PHP script
In the PHP script, the database is updated with the promo code.
The PHP script returns the new expiry date (I'll assume that it's in the d/m/Y format you wanted)
The callback in the jQuery AJAX function receives the data from the script.
The callback's function body updates the "Expiry" element on the page with the value from the PHP call.
Here's how to put that into HTML / JavaScript:
<h4 class="sbText mt-10" id="expiry_label">
Trial End Date: <?php echo date("d/m/Y",
strtotime($trialExpiry)); // The initial value can be displayed as normal. ?>
</h4>
<form id='promocode'>
<input type='text' class='sbInput' placeholder='Promo Code' name='promocode'>
<input type='hidden' name='userid' value='<?php echo $userID; ?>'>
<button class='btn sbSubmit'>Submit</button>
</form>
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function (result) {
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
document.getElementById("expiry_label").innerHTML = "Trial End Date: " + result;
}
});
});
});
</script>
As you can see, I only added an "id" attribute to the element, a parameter to the "success" property of the AJAX call, and a line of code to update the element.
Hope I helped!
You need to add a callback -- IE
<script>
$(function () {
$('#promocode').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function (data) { //<---- CALLBACK
alert(data); // data contains the return from the ajax call
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
});
}
});
});
});
</script>
Only change the success function like below
success: function (data) { //<---- CALLBACK
$('input["name='userid' "]').val(data); // data contains the return from the ajax call
$("button.btn").css({
'transition-duration': '1000ms',
'opacity': '0.5'
New to Jquery, even newer to Jquery Ajax calls - here is my problem:
I have a small form - email address submit - that fires to a PHP file which inserts the email into a table.
I want to do the following:
Handle the form submission through Ajax so there is no refresh
After successfully writing to the table I want to change the submit button's text to "Success!" for 3 seconds and then back to
"Sign Up" with fadeIn and fadeOut effects.
Here is my code for the form:
<form action="" id="registerform" name="registerform" method="post" >
<input type="text" id="email" name="email" value="Email Address" onClick="empty()" onBlur="determine()" />
<button id="join" type="submit" name="join" onClick="validate()">Sign Up</button>
</form>
Here is my terrible attempt at handling the POST request through Jquery:
$('form').on('submit', function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Can anyone comment on how to make the Ajax request work (doesn't seem to be)?
Thanks in advance!
Update
Alright, the following block of Jquery adds the data to the table, however, my button text does not change:
$('form').on('submit', function(e) {
$.post('register.php', $("#registerform").serialize(), function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Any ideas now?
Here is an example of one of my ajax calls
details = "sendEmail=true&" + $("form").serialise();
$.ajax({
url: "yourphppage.php",
type: "post",
data: details,
success: function (data, textStatus, jqXHR) {
if (data == "false") {
console.log("There is a problem on the server, please try again later");
} else {
//Do something with what is returned
}
}
})
And on the server side
if (isset($_POST['sendEmail'])) {
//Do something with the data
}
Of course this is only an example, and you may need to alter this to suit your needs :)
One thing to note is what if (data == "false") does. Well on the server side i can echo "false" to tell the ajax call it was not successful.
You're not actually sending any data to the server. You need to use the 'data' parameter of $.post to send your data.
$('form').on('submit', function(e) {
$.post('register.php', $(this).serialize(), function() {
$('#join').html('Success!');
});
//disable default action
e.preventDefault();
});
Not sure, but does the POST request send anything at all? Try adding the data in the POST request.
$('form#registerform').submit(function() {
var email = $(this).find('input[name=email]').val();
$.post('register.php', {email: email}, function() {
$('#join').html('Success!');
});
return false;
});
Where you're pushing your form data to server in ajax call? change code to this.
var data = {$("#email").val()};
$('form').submit(data ,function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
I'm still working on my multi-stage form (http://jsfiddle.net/xSkgH/93/) and have incorporated the following solution to assist in ajax submit:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$("#task5_booking").submit(function() {
$.post('resources/process2.php', function(data) {
$("#result").html(data);
});
});
return false;
});
});
</script>
It fades out the last step well but when it comes to loading up the content ot process2.php which is simply an array of all the form fields:
<?php
print_r($_POST);
?>
Nothing seems to happen at all. The div remains blank. Would really appreciate any help guys. Thanks in advance.
if you call a resource via ajax you should also pass the serialized form along the call. So assuming $("#task5_booking") is your form element
$("#task5_booking").submit(function(evt) {
evt.preventDefault();
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
$("#result").html(data);
});
});
When you submit the form
stop the default event (submit) otherwise the form submission stops immediately the subsequent code and the ajax call never starts - this is done using preventDefault() method;
make a post call, passing the form serialized with serialize() method (see http://api.jquery.com/serialize/).
Please also note that as pointed out by Jack your form in the fiddle has camperapplicationForm id and not task5_booking
I think you should remove your submit function:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$.post('resources/process2.php', function(data) {
$("#result").html(data);
});
return false;
});
});
</script>
$(document).ready(function() {
$("#postData").click(function(e) {
e.preventDefault();
$("#last-step").hide(600);
$("#task5_booking").submit(function() {
$.post('resources/process2.php', $(this).serialize(), function(data) {
$("#result").html(data);
});
});
});
});
i want to submit all form's infomation with an onclick event function (i don't want to use a conventional submit ). How can i use the post or ajax method?
here is my code
$("#login_form").bind("click", function() {
var qtyVal = document.getElementsByName('id[]').length;
$.ajax({
type : "post",
cache : false,
url : "abcd.php?ref=xyz",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
You should not use from this keyword here. You click on a button to send the form data,so this will return you the button element. You should not use from 'click' event for your form too. You can do like the following code:
function send(){
$.ajax({
type : "post",
cache : false,
url : "abcd.php?ref=xyz",
data : $('#frm').serializeArray(),
success: function(data) {
alert(data);
}
});
return false;}
<form id="frm"><input type="button" id="submit" onclick="send()" /></form>
Are you looking for .submit() ?
If login_form is really a form (i.e. <form id="login_form">), you can do:
$("#login_form").submit();
to submit your form the conventional way without AJAX call.
I am using cakephp and jquery with the form (file-field with submit button) to upload picture.
All I need to do is to do AJAX image upload form. I don't want to refresh the page. So I bind event.preventDefault on submit the form. But I am not sure that the $_FILE['y'] is stopped by the event.preventDefault.
I wonder if the form is submitted ,and I bind event.preventDefault on submit the form.
Do the superglobal,such as $_REQUEST['x'] , $_FILE['y'] ,$_POST['x'] ,$_GET['x'] still there?
if not there , how to do this?
thankyou.
<script type="text/javascript">
$(document).ready(function() {
var getAjax=function(event){
$.ajax({
'url':'<?php echo $this->webroot;?>vehiclePictures/addImageAjax/',
'data': {'x': 33,'y':44},
'dataType': 'json',
'type': 'GET',
'success': function(data) {
if (data.length) {
$.each(data, function(index, term) {
alert(term[1]);
});
}
}
})
event.preventDefault();
};
$('#imageUploadForm').submit(getAjax);
});
</script>
If you're using a button to submit the form, I'd just add return false to the button and have it run the ajax-call instead. Not sure if this is what you were wondering tho?
Like this:
<form method="post" action="someFile.php">
//Form here
<input type="submit" id="buttonToPostForm" />
</form>
function ajaxCall() {
$.ajax({
//Ajax data goes here
});
}
$("#buttonToPostForm").click(function() {
ajaxCall();
return false;
});
And fill in so the data from the form is sent like in you original code.
Hope I understood the question correctly, if not I apologize:)