I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Related
I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});
How to turn off reload of page after sending AJAX to PHP? The page reloads every time when I press submit. Is it possible to send some picture without form?
<script>
$(document).ready(function (e){
$("#uploadForm").on('submit', (function(e){
e.preventDefault();
$.ajax({
url: "/class/pdo/add_new_field.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
$('#uploadForm').submit(function () {
return false;
});
});
</script>
<form id="uploadForm" method="POST">
<div style="margin-left: 75px;">
<div class="save_divs">picture<input type="file"></div>
<div class="save_divs">name:</div>
<div class="save_divs">date</div>
<div class="save_divs">short_info</div>
<div class="save_divs">long info<input type="submit"></div>
</div>
</form>
Do i need slash (/) in $.ajax url?
too many event handlers. Remove the second one unless sendContactForm(); is important. If it is, update your question with it.
syntax error in the event handler, remove the ( from before (funtion in the submit and one of the ) from the }));
If class is the top folder in your hierarchy you can use the /class, if it is under the form location, then no. Use "class/..."
like this
<script>
$(function(){
$("#uploadForm").on('submit',function(e){
e.preventDefault();
$.ajax({
url: "/class/pdo/add_new_field.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}); // also a ) too many here
});
</script>
Ok, First problem is : -
You have submit binded twice once with on, once with submit(), use only one.
Now the error is coming due to the second binding,
There is some error in sendContactForm(), due to which it never gets to the line return false and default page is submitted and is reloaded, check for console errors, also, to prevent confusion in future, you could probably use e.preventDefault(); at the start of the function to stop further propogation. (thanks #rory)
$('#uploadForm').submit(function (e) {
e.preventDefault();
sendContactForm();
return false;
});
i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.
I am trying to trigger a post request when a user clicks the submit button for a comment. Right now clicking the submit button triggers nothing, I even tried to console.log($(this)) I got no output. The first code below is the jQuery event code and ajax code. The block of code below that is the html button. thanks for the help.
$('#submitComment').on('click', '#content', function() {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = { comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2}
}
}).done(function(response) {
console.log(response);
});
});
the button I am trying to target with jQuery event
<div class="container">
<div id="content">
//the code between comments is in a Handelbar template
<input name="createComment">
<button type="submit" id="submitComment">Create Comment</button>
//end of handelbar template
</div>
</div>
You need to bind the delegated handler to an ancestor(#content) of the target element(submitComment)
$('#content').on('click', '#submitComment', function () {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = {
comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2
}
}
}).done(function (response) {
console.log(response);
});
});
Good day, fellow programmers.
There's this index.php that does an Ajax call to login.php and appends the DOM elements and some javascript from inside this into the body of the index. This login.php consists out of a a single div that contains a form and a submit button, which fadeIn() as soon as it is all appended.
However: the submit button is unresponsive!
I did find, after a while, that this does not happen when you directly access login.php via URL (.../.../login.php) instead. This means it's the fact that the index appends the whole, which makes them unresponsive.
(Also: in light of this, I've added a $(document).ready(function(){ ... }); around the entire script in the login.php, but that did not seem to help at all. Instead it caused all functions to return errors...)
I'm out of ideas. Perhaps some of you might have had any experience with these matters?
As always, thank you for the time!
Here's the (simplified) code:
index.php
$('#logInButton').click(function(){
loadContent('/login/login.php', 'body');
});
loadContent();
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
}
});
}
}
login.php (deleted some styling. If you want some specific info, just ask!)
<style>
// some styling
</style>
<div id="loginBlack">
<div class="login" style="z-index:9999;">
<form id="myform1" name="myform1">
<div>
<img src="images/inputEmail.png" />
<div id="emailOverlay">
<input id="email" type="text"/>
</div>
</div>
<input id="iets" name="iets" type="submit"/>
</form>
</div>
</div>
<script type="text/javascript">
// $(document).ready(function(){ // <-- been trying this out.
$('#loginBlack').fadeIn(t)
// some functions pertaining to logging in and registering
// });
</script>
Use jquery on() instead of click()
$('body').on('click', '#logInButton' ,function(){
loadContent('/login/login.php', 'body');
});
That should make the elements behave properly
Note: you can also replace body selector with something nearer to the click button ( its nearest parent )
EDIT::
With this you can have the styling in your normal css file. Put it outside of the login.php
And your js goes into into the success handlers. So just leave the php with the actual html
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
}
});
}
}