Exchange data between HTML page and Java servlet without page refreshing - javascript

I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.
Here is my frontend code:
<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>
Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>

You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.
You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):
function login() {
$.ajax({
type: 'POST',
url: url, //Url of login endpoint
data: DATA, //Now here you would want to send a payload i.e. your username and password data
dataType: 'json',
contentType: 'application/.json',
success: function(data) {
//HERE 'data' would represent your true or false that came back from the server.
//You can do stuff here with the response
},
error: function(jqXHR, textStatus, errorThrown) {
//IF ERROR then this code would be executed.
}
});
}
Hope this gives you a starting point!

You must use jquery AJAX.
Here is a link to the official documentation: http://api.jquery.com/jquery.ajax/
Hope it helps.

Related

AJAX error when passing a variable to a PHP file

How my page works:
The quiz php page loads and the user generates a score with a function inside quiz.js. The score is then saved in a variable score inside quiz.js
After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in sendData.php, without reloading the page.
My button looks like this:
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
And my PHP file being like this:
if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
$score = $_POST['score'];
$numQuiz = $_POST['numQuiz'];
// SQL query and stuff goes here
}
But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
You're running the JS when you click a submit button in a form.
So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response.
You then see the result of the standard form submission.
If you just want a button to trigger some JavaScript, then use a non-submit button (<button type="button"), and don't put it in a form.
Better yet:
switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form
Use preventDefault() to stop the form submission when the JS is successful
Put form controls in the form so it submits useful data when the JS isn't successful
i.e. write Unobtrusive JavaScript then provides Progressive enhancement.
Two things:
You need to tell jQuery to use the application/json content-type:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. So we can parse the JSON payload (body) ussing:
$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);

Bootstrap form get true or false if form is valid or not then ajax

Now before i ask the actual question this is a stupid rant. I swear I hate javascript and everything that is associated with it.
Now actual question.
I have a asp.net web form. I can send data to my web api controller via asp.net code and its working. I'm trying to now post the data via client side ajax using jquery, but I can't get a simple true or false if the form is valid or not. Its a bootstrap v3 form. Someone please help me get off this wild ride. I've searched countless questions but no its not working. Everything is working including post and return message, just this stupid little thing wont't
I just wish to know how to get the form validity status before i ajax. Simple.
Edit:
this button click event works.
$("#additional").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
});
Basically I want the above ajax to run ONLY when form is valid. I have 'required' tags on my form fields already.
Your Question is not clear, but if you mean there is some inputs that they shouldn't be null or empty and after valid theme call ajax you can do some thing like this:
<form class="form-horizontal"> <input type="text" required class="SubscribeText" name="email"> <input type="button" class="postmethod" value="Send"></form>
$(".postmethod").click(function() {
if ($(".SubscribeText").val().length>0) {
$.ajax({
type: "POST",
url: "/api/data",
data: $('form.form-horizontal').serialize(),
success: function(msg){
swal(msg,"Success","success");
},
error: function(){
swal("failure");
}
});
}
});
if you have some inputs, the best practice is use flag, for on click flag=true, which input fails the validation should change the flag to false then if flag is true call ajax method.

Passing JS to PHP

I am trying to pass a string stored in a variable to a mysql table via php.
Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.
I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)
How can I do it?
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.
<html>
<form>
<input type="email" id="email-field" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</html>
Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.
$('#submitButton').click(function() {
var email = $('#email-field').val();
$.ajax({
type: 'POST',
url: './yourphpfilename.php',
data: {
email: email
}
}).done(function(data) {
console.log(data) // Will send you the result that is echoed in the PHP file
})
})
As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
echo 'I have received your request.';
}
To send the data back, I use the echo command to do so here.
Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.
data: {
useremail: email
}
You would then just change the PHP code like so,
$email = $_POST['useremail'];
This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.
There are several things you need to do:
You have a form tag and you need to prevent it from submitting, like this:
$("#myformid").submit(function(event) {
//Do something
event.preventDefault();
});
If your form is no longer submitted, then you are on the right track.
You need to use $.ajax to send the request, like this:
$("#myformid").submit(function(event) {
//Here I assume that all variables have been properly initialized
$.ajax({
url: "yoururl",
method: "POST",
data: yourdata, //yourdata should contain the things you intend to send to the server
}).done(function(response) {
//callback
});
event.preventDefault();
});
You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//It is a POST request
} else {
//It is not a POST request
}

AJAX call returns results, but in a blank page

There are a couple of questions that are somewhat similar to this, but I haven't been able to get their solutions to work for me.
Basically, I am making an AJAX call that is working properly--the result is coming back through. The issue is that instead of processing the result, the result-array is printed back to the screen (and deletes everything else). Clearly, it is not handling the incoming result properly, but I'm not sure why.
This is the form being sent:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="submit">Use</button>
</form>
The PHP that is processing the AJAX:
case "removeAndApply_PromoCode":
…Get data from $_POST….
…process stuff...
$response = …..;
$finalPrice = ….;
$dataArray = array('response'=>$response, 'finalPrice'=>$finalPrice);
header('Content-type: application/json');
echo json_encode( $dataArray );
exit();
break;
Here is a sample result text, as printed on my screen during failure:
{"response":{"Col1":"13","0":"13","Col2":"PC2","1":"PC2","Col3":"1","2":"1","Col4":"45.89","3":"45.89","col5":null,"4":null,"Col6":"1","5":"1"},"finalPrice":0}
And this is the javascript function that is supposed to handle it:
$('.removeAndApply').ajaxForm({url: this.href, type:'post',
data: this.serialize,
dataType: 'json',
success: function(response){
alert("asdf");
}
});
Thanks.
The problem seems to be in HTML button type attribute. When you have a <button type="submit"> in <form> and you clicked it. The form submits, request is sent to the server, browser opening the new response in new document.
If you make some changes:
HTML:
<form class="removeAndApply" method="post" action="">
…hidden inputs...
<button type="button" id="submit-form">Use</button>
</form>
JS:
$('#submit-form').on('click', function() {
$.ajax({
type: 'post',
url: window.location.href,
data: $('.removeAndApply').serialize(),
dataType: 'json',
success: function(res) {...},
error: function(err) {...}
});
});
Everything should be fine.
This is probably better suited for a comment, but I don't have enough rep for that, so:
This is the type of behavior you'd see if you don't bind the ajax form functionality to that form... the button submits the form as normal and you just see plain json coming from the server as a response to the (non-ajax) post. Are you sure that ajaxForm() statement is being executed?

getJSON fails, JSON validates

I have a getJSON call which is inexplicably failing. The idea is, you click to submit a comment, a URL gets hit which determines if the comment is OK or has naughty words in it. The response is given in JSON form.
Here's the paired down JS that generates the call. The comment and the URL are already on the page, it grabs them and hits the URL:
FORM HTML:
<fieldset id="mg_comment_fieldset" class="inlineLabels">
<div class="ctrlHolder">
<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
</div>
<div class="form_block">
<input type="hidden" name="next" value="" />
<input id="mg_comment_url" type="hidden" name="comment_url" value="" />
<input id="mg_comment_submit" type="submit" value="Remark" />
</div>
</fieldset>
SPECIFIC JS BLOCK THAT SENDS/READS RESPONSE:
$('input#mg_comment_submit').click(function(){
var comment = $("textarea#id_comment").val();
var comment_url = $('input#mg_comment_url').val();
$.getJSON(
comment_url+"?callback=?&comment="+comment+"&next=",
function(data){
console.log(data);
alert(data);
});
});
The JSON response:
[{"errors": {"comment": ["Weve detected that your submission contains words which violate our Terms and Conditions. Please remove them and resubmit test"]}}]
It's being returned as a mimetype of application/json. It validates in JSONLint. I also tried adding a couple AJAX functions to try to catch errors, and they're both silent. I can see the request going out in Firebug, and coming back as status 200 responses, which validate in JSONLint and which I can traverse just fine in the JSON tab of the response. If I put an alert before the getJSON, it runs; it's just that nothing inside of it runs. I also find that if I change .getJSON to .get, the alerts do run, suggesting it's something with the JSON. I'm out of ideas as to what the problem could be. Using Firefox 3.0.13.
The querystring parameter "callback=?" comes into play if you are using cross-site scripting or jsonp, if you are posting the same server, you don't need to use that.
If you need or want to use that option, the server side code needs to come back with the callback function included in the json response.
Example:
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
So either make a server side change if necessary or simple remove the "callback=?" parameter from the url.
Here's more info on jsonp
Are you able to manually call your service without any errors? Have you tried using firebug and looked under XBR to see the post/response of the JSON payloads? I normally use .NET as my endpoints, and with .NET 3.5 I need to use content type "application/json; charset=utf-8".
Here is an example of a working JSON call I use in .NET with jQuery 1.3.2
$.ajax({
type: "POST",
url: "WebService1.ASMX/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
// Do your work here.
// Remember, the results for a ASMX Web Service are wrapped
// within the object "d" by default. e.g. {"d" : "Hello World"}
}
});
Have you tried it with $.ajax? You can then define both error and success callbacks and have better idea.
Can you try adding a global ajaxError function to log the error.
$.ajaxError( function(event, XMLHttpRequest, ajaxOptions, thrownError){
console.log( thrownError );
});

Categories

Resources