Ajax POST always returns error - javascript

I'm trying to submit a form via ajax POST to a servlet, process the parameters and then send a response. It always winds up giving me an error.
Form html :
<form id="login" >
<div class="form-group">
<label for="username"> Username : </label>
<input id="username" name="username" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="password"> Password : </label>
<input id="password" type="password" name="password" class="form-control" placeholder="*******">
</div>
<button id="loginBtn" onclick="posaljiLogParametre()" value="Submit" class="btn btn-primary" type="submit"> Uloguj se </button>
</form>
Ajax post :
$.ajax({
type: "POST",
url: "LogInServlet",
dataType: 'text',
data: $("#login").serialize(),
success: function (data) {
$loginParagraf.css("display","block");
alert("DA");
},
error: function(data, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
alert(data.message);
}
});
Servlet :
String username = request.getParameter("username");
String pass = request.getParameter("password");
JSONObject jsonReply = new JSONObject();
System.out.println(username);
System.out.println(pass);
response.setStatus(200);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
jsonReply.put("success",true);
jsonReply.put("message", "Please work this time");
System.out.println(jsonReply.toString());
out.print(jsonReply);
The system prints work just fine, and the username and password are printed out in the console.

From what I can tell I have recreated your setup using an index.jsp page which includes the form and ajax call, and a servlet with a doPost method that includes your code. The code appears to work as expected. I get a successful response with the JSON message.
My first thought was changing dataType: 'text' to 'json', but it appears to work either way.
I had to wrap a try/catch (JSONException) around your jsonReply.put statements to appease the compiler.
One thing that might be causing trouble is that your form includes a submit button which will fire the onclick event and submit the form. I changed it to type="button" so that only the onclick event would fire.

Related

Why can I not run javascript (Js2Py) in Python (Streamlit)?

I am using Streamlit to build a simple app. In this app I made a simple form using FormSubmit to let people contact me. But I don't want them to leave the website when they click on Send button, so I am trying to send the form using AJAX.
To integrate JS in Python I am using Js2Py, but I can't solve this.
This is the form:
contact_form = """
<form id="myForm">
<input type="hidden" name="_captcha" value="false">
<input type="text" name="name" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your name" required>
<input type="email" name="email" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your email" required>
<textarea name="message" style="font-family:'Alegreya, serif';
font-size:20px;" placeholder="Your message here" required></textarea>
<input type="hidden" name="_template" value="table">
<button type="submit" value="Submit" id="sendButton" class="block">Send</button>
</form>
"""
so I made a javascript variable, to check when Send button is clicked:
check_submit = '''<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#sendButton").click(function(e) {
e.preventDefault();
var form = $('myForm'[0]);
var data = new FormData(form);
$.ajax({
method: "POST",
url: "https://formsubmit.co/my-email",
dataType: 'json',
data: data,
success: (data) => console.log(data),
error: (err) => console.log(err)
});
});
});
</script>
'''
then:
st.markdown(contact_form, unsafe_allow_html=True)
So I am passing the javascript variable into the function eval_js() from Js2Py:
js2py.eval_js(check_submit)
I got my form up, and an error message below the form:
JsException: SyntaxError: Line 1: Unexpected token <
and when I fill the form and clicking the Send button, nothing happens.
This means according to me that I misunderstood how to use JS2Py in Python!!!
Any help/suggestion to show me where I did wrong, is very appreciated

post html form results to api as json

I want to submit a form and have the values sent to the api in json format and save the response in a variable. When i try this using the below code i get an 'Internal Server Error' message.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$('#myForm').ajaxForm({
url : 'myurl.com',
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
});
</script>
</head>
<body>
<form class="myForm" method="POST" action="myurl.com">
<div class="form-group row">
<label for="example-text-input" class="col-2 col-form-label">Season</label>
<input class="form-control" type="text" id="season">
</div>
<div class="form-group row">
<label for="example-number-input" class="col-2 col-form-label">Students</label>
<input class="form-control" type="number" id="num_students">
</div>
<div class="form-group row">
<label for="example-number-input" class="col-2 col-form-label">teachers</label>
<input class="form-control" type="number" value="42" id="num_teachers">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>
The parameters the api takes are 'season', 'num_teachers', 'num_students'. Once it has all the parameters it will send a result response back. How can i send my form results to the api and get back the response?
I don't know why you using a jQuery plugin to send form in Ajax, totally useless.
$('#myForm').on('submit', function() { // Fired listener when submit button is clicked.
$.ajax({
url: 'myurl.com',
dataType : 'json', // Try text also, maybe the api donn't send result in json. Text always work.
data: $('#myForm').serialize(); // The form to send.
success : function (response) {// Get response on successful sever connection.
console.log(response); // or alert
}, error: function (err) { // Get error on failed connection to server.
console.log(err); // or alert
}
}
});
Replace your function by that one. Remove action attribute on your html form tag. Now you handle errors and response from server. That means if the server returns an error, it will be displayed in your console and you will be able to know the problem. Other thing, do you really need this old version of jQuery, cause now we are at version 3.3.1.

AJAX HTTP post request is triggered 3 times

In my webapp, the Ajax request is executed 3 times, and I have no idea why this is happening.
Can someone please help here?
My Javascript:
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function(e) { //
e.preventDefault();
// on form submission ...
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(data) {
var res = data.AVG;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p);
},
error: function(error) {
console.log(error)
}
});
}); });
And my HTML is:
<form role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="text" class="input-medium" id="perfid" name="perfid" placeholder="Enter a Perf ID" required style="height:30px;">
<input type="text" class="input-medium" id="hostname" name="hostname" placeholder="Enter a HostName" style="height:30px;">
<input type="text" class="input-medium" id="iteration" name="iteration" placeholder="Enter a Iteration" required style="height:30px;">
<button type="submit" class="btn btn-default" style="height:30px;">Get Data</button>
</div>
</form>
I have written the code for only one AJAX POST request,
EDIT:
This is the console output:
Please make sure you have included the js file only once,
and add a return false at the end of the submit event callback
look at the selector
$('form').on('submit', function(e) {
if the page has 3 forms, the above selector will execute 3 times
Try to add id to the form like this. sorry about my bad english

How to submit form using Ajax in MVC

I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that
As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.
Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.
Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.
use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.
Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`

onclick AJAX POST request(getting for some reason GET)

Good day.
I trying to send AJAX POST request when button is pushed.
this is the form and button button:
<form class="form-horizontal" >
<fieldset>
<!-- Form Name -->
<legend>Welcome!</legend>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Username">Username</label>
<div class="controls">
<input id="Username" name="username" type="text" placeholder="Username" class="input-xlarge" >
......
......
<input type="submit" value="Register" id="register_button" name="register_button" class="btn btn-primary" >
I use bootstrap(if this is important.)
In my java script file(that included in html above) i have following:
$("#register_button").click(function() {
var register_request = $.ajax({
url: "/register",
type: "POST",
data: {
'action' : 'register',
.....
....
}
/*
statusCode : {
200: function(response){
...
},
403: function(response){
...
}
}
*/
});
register_request.done(function (response, textStatus, jqXHR){
...
});
register_request.fail(function (jqXHR, textStatus, errorThrown){
...
});
return ;
});
When i push submit button and my chrome Dev tools opened, i can see there only GET request.
Can someone explain why, and how i can make it POST request.
Many thanks!
You need to return false in your click function. Otherwise, the form (which defaults to GET) will still process.

Categories