I am developing a RESTFul web service project which has a POJO as below:
#XmlRootElement
public class Input {
//variable declarations
public Input(){
//default constructor
}
//constructor no 1
public Input(String LR, double ECH,double CSH,String APP) {
this.LR = LR;
this.ECH = ECH;
this.CSH = CSH;
this.APP = APP;
}
//constructor no 2
public Input(String LR, double ECH,double CSH,String APP,...) {
this.LR = LR;
this.ECH = ECH;
this.CSH = CSH;
this.APP = APP;
//constructor of all other parameters including these
}
//getters and setters method below.
}
My ajax is getting called on this button:
<button type="submit" onClick='functionname();' class="btn btn-primary" ><span class="glyphicon glyphicon-lock"></span>Function</button>
The Controller class I have is as follows:
#Path("/input")
public class InputResponse {
InputService inputservice = new InputService();
#PUT
#Path("/approve")
#Produces(MediaType.APPLICATION_JSON)
public void approveInputRecord(Input obj) throws Exception{
String LR = obj.getLR();
double CSH = obj.getCSH();
double ECH = obj.getECH();
String APP = obj.getAPP();
Input input = new Input(LR,CSH,ECH,APP);
input = inputservice.approveTransaction(input);
}
}
The Service Class for the same is as below:
public class InputService {
CallableStatement stmt;
Statement commitStmt;
public InputService(){
//database connection
}
public Input approveTransaction(Input input) throws SQLException {
commitStmt = dcc.con.createStatement();
stmt=dcc.con.prepareCall("BEGIN APPROVRTRANSACTION(?,?,?,?); END;");
stmt.setString(1, input.getLR());
stmt.setDouble(2, input.getECH());
stmt.setDouble(3, input.getCSH());
stmt.setString(4, input.getAPP());
stmt.execute();
commitStmt.executeQuery("COMMIT");
return input;
}
}
Inside my JAVA Script my ajax call to above is:
var obj = {
LogReference : logreference,
EuroclearHoldings:euroclearholdings,
ClearstreamHoldings:clearstreamholdings,
Approver : loginXPID
}
var jsonobj = JSON.stringify(obj);
$.ajax({
url:'./webapi/input/approve',
type: 'PUT',
data:jsonobj,
cache:false,
contentType: 'application/json',
dataType:'json',
success:function(data)
{
alert('success');
},
error:function(xhr,textstatus,errorthrown){
alert(xhr.responseText);
alert(textstatus);
alert(errorthrown);
}
},'json');
Having this as my code my application is working fine on Google Chrome but sometimes works and sometimes not on Internet Explorer 11. This is the strange behavior. And the other thing which I am unable to get is even if it works on Chrome the ajax call always getting the alerts in error. Can anybody please explain why is it so? And how do I solve it? Any help much appreciated.
Update
Here is the output on network --> Response tab on chrome when error is thrown. But despite that I still get the output.
Many Thanks
As I can see your Button type="submit". If it is inside the form tag then call the ajax request in action of the file. As I can see from above comments this might be the issue. As you are submitting something this changes to a POST request and not GET request so its giving the error method not allowed. And looking at the solution just change the Button type='button' or call the ajax on the action of form tag. It should work.
Related
I have implemented Paytm payment system and everything is working fine with a web intent on top of my intent, money is deducted from customer's acc and its getting added on my account but after the transaction gets complete it gets stuck on a white page saying 'Redirect to app' which i believe i should write the code to redirect back to my app but i don't know how to do that because i couldn't find a onTransactionSucess() event or anything similar to that i also tried onTransactionResponse but still no response. I checked all the paytm documentation and tried contacting paytm support but couldn't find a way.
Hope you have added 'CALLBACK_URL' which is requied to verify the checksum.
As mentioned in paytm documentation
CALLBACK_URL - Security parameter to avoid tampering. Generated using
server side checksum utility provided by Paytm. Merchant has to ensure
that this always gets generated on server. Utilities to generate
checksumhash is available here .
Hope this should do the magic.
I hope you have added this variable to your code -
PaytmPGService service;
If you are using it than you can get all the payment related methods like this :
service.startPaymentTransaction(this, true,
true, new PaytmPaymentTransactionCallback() {
#Override
public void onTransactionResponse(Bundle inResponse) {
System.out.println("===== onTransactionResponse " + inResponse.toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.equals(inResponse.getString("STATUS"), "TXN_SUCCESS")) {
// Payment Success
} else if (!inResponse.getBoolean("STATUS")) {
// Payment Failed
}
}
}
#Override
public void networkNotAvailable() {
// network error
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// AuthenticationFailed
}
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// UI Error
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {
// Web page loading error
}
#Override
public void onBackPressedCancelTransaction() {
// on cancelling transaction
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
// maybe same as onBackPressedCancelTransaction()
}
});
I hope this will help you.
Change default callbackurl to suppose, 'http://yourdomain (ip address if checking on localhost)/pgResponse.php';.
Add following code to pgResponse.php
<?php
session_start();
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";
$paramList = $_POST;
$return_array= $_POST;
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);//generate new checksum
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your applicationÃs MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
$return_array["IS_CHECKSUM_VALID"] = $isValidChecksum ? "Y" : "N";
unset($return_array["CHECKSUMHASH"]);
$mid = $_POST['MID'];
$orderid = $_POST['ORDERID'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://securegw-stage.paytm.in/order/status?JsonData={"MID":"'.$mid.'","ORDERID":"'.$orderid.'","CHECKSUMHASH":"'.$checkSum.'"}',
CURLOPT_USERAGENT => 'Make Request'
));
$resp = curl_exec($curl);
$status= json_decode($resp)->STATUS;
//do something in your database
$encoded_json = htmlentities(json_encode($return_array));
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-I">
<title>Paytm</title>
<script type="text/javascript">
function response(){
return document.getElementById('response').value;
}
</script>
</head>
<body>
Redirecting back to the app.....</br>
<form name="frm" method="post">
<input type="hidden" id="response" name="responseField" value='<?php echo $encoded_json?>'>
</form>
</body>
</html>
In android studio:
public void onTransactionResponse(Bundle inResponse) {
Log.d("Create Response", inResponse.toString());
String response = inResponse.getString("RESPMSG");
if (response.equals("Txn Successful.")) {
Toast.makeText(Bag.this,"Payment done",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Bag.this,response,Toast.LENGTH_LONG).show();
}
}
I have two problems:
I have no idea how to call a java class function in a html page using angularJS.
I need my button to be disabled after it is used.
My address is this: http://localhost:8080/CreditCardWEB/rest/cc/init
I have this in my class:
CardBean.java
#GET
#Path("/init")
public void init() {
Student s = new Student(1, "Pera", "Peric");
em.persist(s);
s = new Student(2, "Pera2", "Peric2");
em.persist(s);
s = new Student(3, "Pera3", "Peric3");
em.persist(s);
}
In my indexStud.html page, I have a button:
<button ng-click="initStud()">Init Student</button>
In my controllers.js I have the problem, but I have no idea how to do it:
$scope.initStud = function() {
//call the function from Cardbean.java
//disable the button after he is used
}
Ok i found the answer to question number 1....and here is it
$scope.initStud = function() {
$http.post('http://localhost:8080/CreditCardWEB/rest/cc/init').success(
function(data) {
});
}
thats needed in the controllers.js file
and the #GET in the 1st line in the Cardbean.java file has to be changed to #POST
I'm trying to do a thing in php that I've learnt in Java.
When a user logs in a website a Controller page saves in a private $userLogged var user infos and redirects him in index.php. Now, if he clicks on "profile" I would like that Controller page had in $userLogged his infos still. How I can do it? I've done this:
controller.php
class ECommerce
{
private $checker;
private $errorManager;
private $userLogged;
[...]
function userLogIn($data) {
$user = new User();
$this->userLogged = $user->getByEmail($data["email"]);
if($this->userLogged) {
if($this->userLogged->checkPassword($data["password"])) {
$_SESSION["ec_code"] = $this->userLogged->getCode();
$_SESSION["ec_name"] = $this->userLogged->getName();
$_SESSION["ec_surname"] = $this->userLogged->getSurname();
$_SESSION["ec_email"] = $this->userLogged->getEmail();
$this->redirect("e-commerce/index.php", null);
}
else {
$data["error_message"] = $this->errorManager->getErrorUserLogIn();
$this->redirect("e-commerce/accedi.php?err=1", $data);
}
}
else {
$data["error_message"] = $this->errorManager->getErrorUserLogIn();
$this->redirect("e-commerce/accedi.php?err=1", $data);
}
}
function seeUserProfile() {
$data["try"] = $this->userLogged->getName();
$this->redirect("e-commerce/profilo_utente.php", $data);
}
user_profile.php
<?php
session_start();
session_regenerate_id();
echo $_SESSION["data"]["try"];
what's wrong?
Thank you before!
Uh this is the error message I receive:
Fatal error: Call to a member function getName() on a non-object in /home/mhd-01/HOST_NAME/htdocs/e-commerce/controller/ECommerce.php on line 110
In user_profile.php you need to include the ECommerce class like Liquidchrome mentioned like so:
require('Controller.php');
and then you'll need to create an instance of your ECommerce Class
if you want to pass the same data to user_profile.php page you'll need to instantiate the user_profileclass and pass the instance of the ECommerce class you were using to it.
I'm trying to update an HTML5 table in real-time with some data from the database. Here is my code:
HTML page:
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("[some address]/api/sse");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("placeholder").innerHTML=table;
};
}
else {
[erro message]
}
</script>
And my Java Restful service:
#Path("/sse")
public class SSEResource {
#Context
private UriInfo context;
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() throws Exception {
SomeObject o = new SomeObject();
final String myString = o.someQuery().getEntity().toString();
return "data: " + myString + "\n\n";
}
}
This someQuery() method queries from database and returns what I want to put on my table. Everythings looks great. But I want to know if it's right or wrong, because if I put some log on someQuery() method, I see that every 3 seconds the query is executed. This may cause heavy duty, right? Is this normal or is my code wrong?
I'm trying to show in my App different errors when a user is already logged in and when the user wrote their username/password wrong. I have tried many ways but none of them is working. I don't know what else to try or if it's even possible. I don't know if I'm close to the solution either.
What I'm trying to do is:
Set the errorMessage in the request;
Set the SC_INTERNAL_SERVER_ERROR in the response so the AJAX function enters in ** and the HTML in the paramether is the one in the JSP with the specific Message.
Action
public class LogUser extends Action {
#Override
public void execute() throws Exception {
...
String pageToGo = this.tryLogUser(username, password);
request.getRequestDispatcher(pageToGo).forward(request, response);
}
private String tryLogUser(String username, String password) throws Exception {
String pageToGo = "page/userHome";
...
if(canLog) {
...
try {
...
Server.getInstance().logIn(user); // Throws an Exception if the User is already logged in.
...
} catch (ServerException e) {
this.setErrorMessage("That user is already logged in.");
pageToGo = "page/error.jsp";
}
} else {
this.setErrorMessage("User and/or Password are incorrect.");
pageToGo = "page/error.jsp";
}
return pageToGo;
}
private void setErrorMessage(String message) {
request.setAttribute("errorMessage", message);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
JSP
<div class="alert alert-danger"> ${ requestScope.errorMessage } </div>
AJAX
function showUserHome() {
$.post( "${ sessionScope.ServletUrl }", $( "form#logForm" ).serialize() )
.done(function( html ) {
$( "div#toolbar" ).load("page/userToolbar.jsp");
$( "div#content" ).html( html );
})
.fail(function( html ) {
$( "#result" ).html( html );
});
}
Edit:
While trying to Debug it from the browser, it gets in the $.post and after that step, it jumps to the end of the function, skipping .done and .fail and the page remains the same. I'm not getting any error in the RAD Console or the Browser Console other than the SC_INTERNAL_SERVER_ERROR that I setted on the Action.
Calling setErrorPage method won't change your pageToGo local variable and thus always the same view is used. Change it to something like:
pageToGo = setErrorPage("That user is already logged in.");
(or even consider rename it to getErrorPage)