How to submit an AJAX form with a <a href> link? - javascript

I have the following form:
<form id='confirm_reset' action='login/forgotPassword_action' method='post'>
<input type='hidden' name='user_email' value='user_email'>
Submit
</form>
<div id="alert_box_register"></div>
I am trying to submit this with Ajax to return JSON in the alert box:
$("#confirm_reset").on("submit", function(event) {
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url, postData, function(data) {
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});
This script returns no result (as if the link did not function). Where am I going wrong?

Not sure if this code is still a problem for you or not...?
A quick note about out your progress messages ("Resetting password..."): this code will probably run so fast that this message will just barely flash on the screen for the user. I don't know how your stuff is set up but you may never see this on the screen.
<!-- The following line was missing .php from the action -->
<!--form id='confirm_reset' action='login/forgotPassword_action' method='post'-->
<form id='confirm_reset' action='login/forgotPassword_action.php' method='post'>
<input name="txtbox" type="text" value="hello world"/>
<input type='hidden' name='user_email' value='user_email'>
<!-- submit_confirm_reset() is a function I made in the javascript tages-->
Submit
</form>
<div id="alert_box_register"></div>
<script>
function submit_confirm_reset() {
$("#confirm_reset").submit();
}
$("#confirm_reset").on("submit", function(event)
{
console.log('("#confirm_reset").on("submit", function(event)');
//disable default click operation
event.preventDefault();
var action_url = $(this).attr("action");
// you were using alert_box_register like it was a function
// but it doesn't exist in the code you posted in your question
// but a DOM element has this name so I assume you meant that
$("#alert_box_register").html("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url, postData, function(data) {
console.log(data);
// if this response is already json, you don't need to parse it
var obj = $.parseJSON(data);
$("#alert_box_register").html(obj.message);
});
});
</script>

Related

How to make a popup form AJAX in leaflet and execute function on submit

What i'm basically trying to do,after clicking on each polygon a popup form appears where the user will input some values,press submit and after the php script and function runs ,it will supposedly show some markers on the map.I'm trying to make this form work as AJAX and execute the function within.
I already ajax successfully a html form before but it seems it needs some work to function properly within leaflet.
The form im trying to AJAX
var htmlformGuest = `
<h2>Search for parking slots</h2>
<form id="parkform" action="/findPark.php" method="post" >
Enter the polygon id:<br>
<input type="number" name="id_P" value="">
<br>
Max radius:<br>
<input type="number" name="Radius" min="50" max="500" value="" placeholder="50">
<br><b>
<input type="Submit" value="Submit">
<input id="form-polygon-id" type="hidden" name="PolygonID">
<input type="reset">
</form>
`;
The function i want to include when submitting the form ( which im not sure it works since i need to first ajax the form!)
function putMultipleMarkers(jArrayId, jArrayLat, jArrayLng) {
for (var i = 0; i < jArrayLat.length; i++) {
var multipleMarker = new L.marker(jArrayLat[i], jArrayLng[i])
.bindPopup(jArrayId[i])
.addTo(geojson);
}
}
What worked for me in a non-leaflet form previously was this code withing the function
$("#parkform").submit(function (e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: "findPark.php",
data: form.serialize(),
success: alert('Marker Map'),
})
});
Any help appreciated!
It's not really clean, but you can do $('body').html(data) on success:
$("#parkform").submit(function(e) {
e.preventDefault();
var dataForm = $(this).serialize();
var url = form.attr('action');
$.post(
url,
dataForm,
function(data) { // on success
$('body').html(data);
}
);
});
Because the data is the code response of your request, then it's the same page with POST array values.

How to submit a form and get some text in return using Ajax

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) {
...
}
})

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

load form using ajax then again submit using ajax

I have a page where I'm displaying some information. You can select a option and the page will then display a form by loading the form using ajax response:
$("body").on("change", "#patient_id", function(event){
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$('.prescription_content').html(response);
return true;
});
});
This works fine. But this view is a form. I want to then submit the included form with Ajax as well. But I can't seem to do it. I think it is because if I set up a button handler for the form it doesn't work as the form isn't present when the main page and JQuery script is loaded.
So to be clear, I'm loading this div onto my main page using JQuery and Ajax load. I then want to simply submit this form with Ajax also.
<div class="prescription_content">
<div class="title">Submit News</div>
<form role="form" id="ref_form" name="ref_form_p">
<div class="form-group">
<label for="pat_ref_hosp">Hospital to Refer:</label>
<input type="text" class="form-control" id="pat_ref_hosp" name="pat_ref_hosp" value="<?php if(!empty($result->reffer_hospital)){ echo $result->reffer_hospital; }?>">
</div>
<input type="hidden" class="form-control" id="pres_note" name="pres_note" value="<?php echo $result->priscription_id ;?>">
<button type="button" id="<?php echo $result->priscription_id ;?>" class="btn btn-success reffering_status">Refer Now</button>
</form>
</div>
TIA
Then I submitted form again using ajax through below button click event:
$("body").on("click", ".reffering_status", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp,
};
console.log(curr_data);
)};
Here is log displaying
Object {action: "reffering_status", dataType: "json", prescription_id: "1", pat_ref_hosp: ""}
pat_ref_hosp is empty
I don't know how to display ajax in jsfiddle
https://jsfiddle.net/3ggq3Ldm/
Yes the way you are doing it will not work because the contents of the DIV you are loading-in is not loaded into the DOM when your initial
$("body").on("click", ".reffering_status", function(event){});
call is made.
If I am understanding you correctly, this is the behaviour you want to achieve:
$("#patient_id").on("change", function(event) {
var prescription_id = $(this).val();
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var curr_data = {
action: 'refferedcall',
prescription_id: prescription_id,
dataType: 'json'
};
$.post(hmgt.ajax, curr_data, function(response) {
$(".prescription_content").html(response);
$(".reffering_status").on("click", function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var prescription_id = $("#pres_note").val();
var pat_ref_hosp = $("#pat_ref_hosp").val();
var curr_data = {
action: 'reffering_status',
dataType: 'json',
prescription_id: prescription_id,
pat_ref_hosp : pat_ref_hosp
};
console.log(curr_data);
)};
return true;
});
});
You simply need to run the code that attaches your click listener AFTER the DOM has already been updated with the new information.
Please let me know if this code does what you were intending it to.

jQuery.post() has a side-effect of changing my URL parameters

I have a page with multiple forms. When the users fill in one of the forms, I want to send it to a server. However, I need the browser to keep displaying the original page, so that the users can submit other forms, if they wish to. Hence I cannot use the "action" attribute in the form and a "submit" type of button.
After consulting the jQuery.post docs, I arrived to the following solution:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button" onclick="submitForm();"> Submit </button>
</form>
<script>
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
</script>
</body>
</html>
The above code does what I want it to do, but it has a very peculiar and disruptive side-effect of modifying my URL to include the parameters I'm posting.
So when I fill in my name and email, I'm "redirected" to myself, but with the name and email parameters appearing in the URL:
http://localhost:8080/Prototype/TestPost.html?name=Lev&email=Storytime%40gmail.com
Now, I definitely do not want "name=Lev&email=Storytime%40gmail.com" to be a part of my URL. These parameters are also not intended for TestPost.html but rather to SaveForm.jsp, so it's all very wrong.
I also want to mention that SaveForm.jsp works as expected. It receives the parameters, saves them to the database and returns a success response.
What am I missing?
Thanks.
EDIT
Thanks, everybody. I could not avoid the refresh using the "return false" statement, so I had to use jQuery's "on click" option. I also don't understand how using ajax explicitly would make any difference, since jQuery's documentation seems to say that the post is just a syntactic sugar for Ajax.
The complete code which worked for me was:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
If you don't especify the method attribute on the form it will be GET by default, that's why you get the URL params. Also, because you aren't not stopping the default action, your form is being submitted (the reloading effect), so I recommend you the following code to help you:
<script>
$(function() { //executes js code after html has been loaded
$("#button").on("click", function(e) {
e.preventDefault(); //avoids to reload the page
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
});
</script>
And remove the onclick at the button to have a cleaner HTML:
<button id="button"> Submit </button>
If you do not want to use jQuery's on click and still stick to the submit function you can just add return false; in the end to prevent the form from submitting.
Like below
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
});
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
Hope this helps.
I guess, you are not submitting the form by ajax.
Add return false;, to that it does not redirect and submit via ajax.
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData, function() {})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
return false;
}

Categories