I have a form from which I want latitude and longitude and I want want load this without submit button.
<form method="post" id="myform" action="" >
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
</form>
I tried
document.getElementById("myForm").submit();
But it causes infinite loop and I want it on the same page so I am not giving action.
I add this function but still not working.
function send_data(lat, lon) {
document.getElementById('place_lon').innerHTML = lat + ' : ' + lon;
// $("input[name='lattitude']").val(lat);
// $("input[name='longitude']").val(lon);
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
$j.ajax({
url: window.location.href,
type: 'POST',
data: $j(this).serialize(),
dataType: 'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$("input[name='latitude']").val(lat);
$("input[name='longitude']").val(lon);
// $j('#lattitude').val(lat);
// $j('#longitude').val(lon);
//submit the form (to the form's action attribute)
document.forms['#myform'].submit();
}
}
What happens is that as soon as form is loaded it submits itself, then loads again and submits etc.
Try using AJAX request to send data to the server.
$.ajax({
type: "POST",
url: window.location.href,
data: $('#myForm').serialize()
});
Related
I have a form calling submitting as follow
<form action="" method="post" id="member_form" onsubmit="return json_add('member','<?php echo ($admin->getnew_id()); ?>','0','slider_form');">
The problem I have is to get the $new_id before submitting the form from another function class.
this is not working
It keep running the funtion getnew_id() and generate the ID before it is saved
I need the process as follow.
Form Open
User complete form
onsubmit it need to do follow.
a. get new id = $new_d
b. then do
return json_add('member','','0','slider_form');">
I tried the following but dont work
$("form").submit(function(){
$.ajax({
url:"lastid.php",
type:'POST',
success:function(response) {
var $new_id = $.trim(response);
return json_add('member-add',$new_id,'0','slider_form');
alert("Submitted");
}
});
The problem seems to be in the third step.
What you should do is prevent the form from submitting and handle it in ajax.
you need onsubmit="return false" to prevent the form from submitting
Next, handle the submission in ajax
$("form#member_form").submit(function(){
$.ajax({
url: "lastid.php",
type: "POST",
data: { // this is where your form's datas are
"json": json_add('member-add',$new_id,'0','slider_form'),
"key": $("form#member_form").serialize()
},
success: function(response) {
var $new_id = $.trim(response);
alert("Submitted");
// alerting here makes more sense
}
// return json_add('member-add',$new_id,'0','slider_form');
// returning here do nothing!
});
You can read more about using ajax in jQuery here
This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})
I have a jsp page which displays the details of a student .Based on the student selection from the dropdown box on change event will be fired and retrieve the min and max marks for the student.
<form name="listBean">
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialMarks"/>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalMarks"/>
<input type="submit" value="submit" id="submit" />
MinMarks:<c:out value="${Item.minMarks}"/></c:if>
MaxMarks:<c:out value="${Item.maxMarks}"/></c:if>
</c:forEach>
</form>
After retrieval ,updated data will be stored into the bean.Server request is handled using jquery.ajax() method
function onChange() {
jQuery('form').each(function() {
jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
});
location.reload();
});
}
Once the server response is successful , i will be reloading the page so that the page will be refreshed with the bean data set during the ajax call.
But it is not displaying the data?What i am doing wrong ?
Or is there any better solution to achieve this?
Any suggestions are welcome .
Thanks
It looks like you are reloading the page immediately after sending the AJAX request, potentially before the server has received and processed it.
You could store your ajax requests in an array and only reload the page when all requests have completed using jquery's when().
function onChange() {
var requests = [];
jQuery('form').each(function() {
requests.push(jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
}));
});
jQuery.when.apply(jQuery, requests).then(location.reload, errHandler);
}
function errHandler (err) {
// handle any errors
}
I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.
as title states I'm struggling with making delayed post submission so ajax call can complete.
So far I've this, any ideas why it wouldn't work?
//Jquery
jQuery(document).ready(function($) {
$("#save").on("click", function(e){
//Prevent submission of post data before ajax success in function reverse_geocoding
e.preventDefault();
//ajax
reverse_geocoding(lat_onclick,lng_onclick,true);
}
});
function reverse_geocoding(latitude,longitude,submit) {
//get country/city/state using lat and long data
jQuery.ajax({
url: "<?php bloginfo('template_url'); ?>/reverse-geocoding.php",
type: "GET",
data: "latitude=" + latitude + "&longitude=" + longitude,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
},
complete: function() {
if (submit) {
$("#add_to_map").submit();
}
}
});
}
});
//End Jquery
html part:
<form method="post" name="update_profile_maps" id="add_to_map" action="">
//some inputs here.
</form>
Rather than using a <submit> tag, use a normal <button> (which is not of type submit; note that type submit is the default). When the button is clicked, fire your ajax and then submit the form using JavaScript if the ajax completes successfully.