don't see Json data result in JSP - javascript

In my .JSP file i have :
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="submit" onclick="submitform()">
</form>
<p id="result"></p>
</body>
and my Javascript function is:
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
};
Also I created a new class User.java with some data, then in my Jsoncontent.java , in method POST I set my variables and created a request for json like this:
String jsonData = request.getParameter("per");
System.out.println(jsonData);
Gson gson = new Gson();
User data = gson.fromJson(jsonData, User.class);
System.out.println("Fetching json object");
String name = data.getName();
String address = data.getAddress();
System.out.println("User Name: "+ name );
System.out.println("User Address: "+ address );
User user = new User();
user.setName(name);
user.setAddress(address);
String jsonObj = gson.toJson(user);
System.out.println(jsonObj);
out.print(jsonObj);
So,all works without errors or warnings but I don't see the result when I click on submit button. I don't know why.

You note in the comments to the other answer that i still have a white browser page yet without name and address which indicates that the browser is navigating away from the page you are currently viewing and, therefore, you are not making an Ajax request - or more likely you are making an Ajax request but are also making a standard HTTP Post request due to the fact that you have not disabled the default submit event.
You therefore need to disable the default submit action.
https://api.jquery.com/event.preventdefault/
https://www.w3schools.com/jquery/event_preventdefault.asp
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" id="submit" type="submit">
</form>
<p id="result"></p>
</body>
$('#submit').click(function(e){
e.preventDefault(); //prevent standard post
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
})

You missed the point: you have $ajax but should be $.ajax
Also you can submit form instead of json, like:
function submitform(){
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: $("#form").serialize(),
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
And in the servlet get the parameters "name" and "address":
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
...
String name = request.getParameter("name");
String address = request.getParameter("address");
...
}
CHANGES IN ANSWER
Sorry, I only paid attention to the conclusion of the alert message. Alan Hay is right in his remark, you can use it or change the type to a button.
Anyway, here is the working code
Servlet.java
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(urlPatterns = "/jsonserverlet")
public class Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String jsonData = request.getParameter("per");
out.print(jsonData);
}
}
index.jsp
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.js"
type="text/javascript"></script>
</head>
<body>
<form id="form">
<input type="text" name="name" id="name"><br><br>
<input type="text" name="address" id="address"><br><br>
<input value="Submit" type="button" onclick="submitform()">
</form>
<p id="result"></p>
</body>
<script>
function submitform(){
var userName = $('#name').val();
var userAdd = $('#address').val();
var myVar = JSON.stringify({name: userName, address:userAdd});
$.ajax({
url: 'jsonserverlet',
type: 'POST',
data: 'per=' + myVar,
dataType: 'json',
success:function(data){
var json= JSON.stringify(data);
alert(json + " " + data.name + " " + data.address);
$("#result").html(data.name + " " + data.address);
}
});
}
</script>
</html>

Related

Sending two forms after button click and run php in background

I have created this site and integrated with payfast, it works well. but now i want to execute another php script on place order button which gets details into the db
here is my code quite long.... I no nothing about Ajax or javascript!! Please help
<form id="form1" action="payment.php" method="POST">
some stuff...
</form>
<?php
$htmlForm = '<form action="https://'.$pfHost.'/eng/process" method="post" id="form2">';
$htmlForm .= '<input type="submit" id="submit" name="submit" class="btn btn-primary btn-lg btn-flat" value="PLace Order" onclick="submitForms()"></form>';
?>
<?php
echo"
".$htmlForm."
</div>";
}
else{
echo '...';
}
?>
<script>
submitForms = function() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>
$(function() {
$(".submit").click(function() {
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
I tried the ajax i found but, it never worked. Check at the end of my code!
What i need is payment.php will execute in the background while it directs user to payfast
I want to submit only the first one via AJAX.
Your attempt doesn't make much sense because it doesn't appear to target the first form (which you say you want) and may not prevent the default postback behaviour.
As I understand it, you want that whichever form the user clicks on to submit, the code will actually then submit the first form via AJAX, and then the second one via standard postback.
This should do the job:
HTML:
<form id="form1" class="doubleForm" action="payment.php" method="post">
<input type="submit" id="submit1" name="submit" class="btn btn-primary btn-lg btn-flat" value="Submit">
</form>
<form id="form2" class="doubleForm" action="https://example.com/eng/process" method="post">';
<input type="submit" id="submit2" name="submit" class="btn btn-primary btn-lg btn-flat" value="Place Order">
</form>
JavaScript:
//handle submission of both forms
$(".doubleForm").submit(function(event) {
event.preventDefault(); //stop standard postback
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//submit first form via AJAX
var request = $.ajax({
type: "POST",
url: "payment.php",
data: dataString
});
request.done(function(response) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
//now the first form is submitted and server has responded, we can trigger "normal" (non-AJAX) submission of second form
document.querySelector("#form2").submit();
});
}
});
So this actually worked well using .serialize(). Thanks #ADyson for the headsup just had to tweak it a little bit, though i'm not experienced in js
<script type="text/javascript">
$(function(){
$("#submit2").click(function(){
var dataString = $("#form1").serialize();
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(data)
{
alert('Success!');
$("#form1")[0].reset();
}
});
});
});
</script>

The response received in AJAX call is shown in another HTML page

I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>

How to get text field value from html and pass it to REST GET service and display the response in dynamic HTML table

I have created a Spring-boot REST service and It's working as expected and returned JSON array as response.
End Point:
https://localhost:8081/displayProduct?productId=1234
Output(Example):
{
"dataSet":[
{
"productName": "mobile",
"product_OS":"Android"
},
{
"productName": "Laptop",
"product_OS":"Linux"
}
]
}
Code:
#ApiOperation(responseContainer = "request", response = HadoopCALDTO.class, value = "shows_component")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#RequestMapping(value = "/displayProduct", produces = MediaType.APPLICATION_JSON, method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> getETLResponse(#RequestParam("productId") String productId)
throws Exception {
Map<String, String> data = new HashMap<String, String>();
Map<String, String> dataError = new HashMap<String, String>();
String response = Utils.sendGET(ConfigReader.getProperty("getBaseURL")
+ productId);
data = Utils.getHttpUrl(response, productId);
System.out.println(data.size());
if (Utils.getDataError().size() > 0) {
Utils.getDataError().clear();
}
for (Map.Entry<String, String> getValue : data.entrySet()) {
String tempUrl = Utils.replaceUrl(getValue.getKey());
System.out.println(tempUrl);
String tempresponse = Utils.sendGET(tempUrl);
Utils.getErrorData(tempresponse);
}
System.out.println(dataError.size());
String finalResponse = Utils.buildJSONSkelton(Utils.getDataError());
System.out.println(finalResponse);
return new ResponseEntity<String>(finalResponse,HttpStatus.OK);
}
The above code works perfectly fine. I tested the End point in postman which returned 200 Ok response and proper response body as expected.
The above code I have a JSON that I stored in "finalResponse" string variable and showing it as response body (Sample output mentioned above).
I'm getting the productId is the input from user and getting the result and publishing the data. And I just want to do this from Responsive HTML page. Like I just need a text box where the user needs to enter the product id and click submit button. And the value is pass into the REST client and displaying the JSON array result as table view in HTML page.
Really I don't have any idea how to kick start this. I'm very new to web application development, and not sure how to achieve this. Googled about Spring MVC and some library called xmlhttprequest javascript. But not sure how to get the value from text field and pass it to REST client and wait for respose (It takes close to 20 seconds to fetch all the productID from hadoop) JSON array and display the result as dynamic HTML table as like below.
S.No || Product_Name || Product_OS
1 || Mobile || Android
2 || Laptop || Linux
Please can someone help me on this.
Updates:
I just tried the below steps to hit the REST client and get the response as dynamic html table
<html>
<head>
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value;
var dataString = 'calId=' + name ;
if (name == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
url: 'http://localhost:8081/api/displayProduct?',
data: dataString
dataType: 'json',
success: function(data) {
for (var i=0; i<data.length; i++) {
var row = $('<tr><td>' + data[i].productName+ '</td><td>' +
data[i].product_os + '</td> </tr>');
$('#myTable').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
</script>
</head>
<body>
<form id="form" name="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>
</body>
</html>
<table id="myTable">
<tr>
<th>Zipcode</th>
<th>City</th>
<th>County</th>
</tr>
</table>
Observed below Error message:
MyTest_sta.html:39 Uncaught ReferenceError: myFunction is not defined
at HTMLInputElement.onclick (MyTest_sta.html:39)
Please find below code snippet, here I am rendering ajax response into a table, you can probably make this ajax call attach to any event/ form submit
HTML:
<form id="form" name="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>
<table id="myTable">
<tr>
<th>Zipcode</th>
<th>City</th>
<th>County</th>
</tr>
</table>
JS:
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dataString = 'name1=' + name + '&email1=' + email;
if (name == '' || email == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
url: 'https://localhost:8081/displayProduct?productId=1234',
data: dataString
dataType: 'json',
success: function(data) {
for (var i=0; i<data.length; i++) {
var row = $('<tr><td>' + data[i].zipcode+ '</td><td>' +
data[i].city + '</td>
<td>' + data[i].county + '</td></tr>');
$('#myTable').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}

Why I cannot Login the using c# and mysql in ASP.net

I am beginner in developing a website using ASP.Net
Please Help me. so that i can pursue my career. Thanks in Advance
I am creating a login script using c# and I want to call it in javascript.
But it after I Logged in, The Login page will only refreshing.
And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll
So here is my code :
HTML
<form>
<div class="form-group">
<input type="text" class="form-control material" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control material" id="password" placeholder="Password">
</div>
<button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>
</form>
JAVASCRIPT:
$(document).ready(function () {
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
AuthenticateUser(username, password)
});
});
function AuthenticateUser(username, password) {
var value = "{'email':'" + username
+ "','pass':'" + password
+ "'}";
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: value,
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
C#:
[WebMethod]
public string loadEmployeeAccount(string email, string pass)
{
List<Auth> mylist = new List<Auth>();
using (MySqlConnection connection = new MySqlConnection(connectionString()))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = #email AND password = #pass", connection);
cmd.Parameters.Add("#email", MySqlDbType.VarChar).Value = email;
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = pass;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int user = 0;
if (dr["userType"].ToString() == "")
user = 1;
else
user = Convert.ToInt32(dr["userType"].ToString());
mylist.Add(new Auth
{
user_id = dr["user_id"].ToString(),
username = dr["username"].ToString()
});
}
dr.Close();
connection.Close();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsn = jss.Serialize(mylist);
return jsn;
}
And here is the image on the console.
Can someone help me with this?? any help will much be appreciated. Thanks
Okay, in order to achieve your functionality follow these steps:
In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:
data: {"json": JSON.stringify(value)}
Then decorate your class with:
[System.Web.Script.Services.ScriptService]
to allow POST requests via AJAX to your WebMethod.
And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:
[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"];
string password=jsondata["pass"]
//Your code here
}
it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod
function AuthenticateUser(username, password) {
var value = {'email':username,
'pass':password};
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: JSON.stringify(value),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.
First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.
type: ‘GET’
Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:
data: {
email: username,
pass: password
}
also, delete the dataType: ‘JSON’

The jQuery AJAX and PHP not fetching data values

I am trying to fetch the values of the data variable passed with jQuery AJAX to a php page. How to solve it?
Below is the HTML page code:
<input id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>
On the button click this jQuery AJAX calls a php page:
$.ajax({
type: "POST",
url: "jquery-ajax-hello.php",
contentType: "application/json; charset=utf-8",
data: '{"name":"' + $("#name").val() + '"}',
success: function (result, status, xhr) {
$("#message").html(result);
},
error: function (xhr, status, error) {
$("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
The PHP Page code is:
<?php
$name = $_POST['name'];
echo "Hello ".$name.", How are you ?";
?>
In the php page I am not able to fetch the data varaible 'name' value?
Please help?
Your data should be an object, what you're passing is a string, so it should be
data: {
name: $("#name").val()
},
JQuery Ajax
Form data
<input type="text" id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>
Jquery section
$(function() {
$("#submit").click(function() {
var name = $('#name').val();
$.ajax({
url : 'success.php',
method: 'POST',
data : {name:name},
success : function(res) {
$('#message').append(res);
}
});
});
});
success.php
<?php
$name = $_POST['name'];
echo "Hello Mr ".$name ;
?>
change data property to
data: {name: $("#name").val() }
and it would work fine
change data to:
data: { name: $("#name").val() }
because data must be an object having key : value pair in it
In your case:
data: '{"name":"' + $("#name").val() + '"}'
{} is wrapped with single quotes. Remove them.

Categories

Resources