PHP let value fixed in a controller page - java

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.

Related

Ajax call working on Google Chrome but not on IE 11

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.

Understanding Server-sent Events

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?

Play2 Framework Better solution

So I am doing an edit profile feature with Play! Framework (2.2.0);
I have this code
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
localUser.firstName = formData.field("firstName").value();
localUser.lastName = formData.field("lastName").value();
localUser.locale = formData.field("locale").value();
localUser.gender = formData.field("gender").value();
localUser.country = formData.field("country").value();
localUser.save();
}
return redirect("/profile/edit");
}
It works. But I want to know is there a better way of doing this ?
I have tried this things:
1)
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User localUser = formData.get();
localUser.save();
}
return redirect("/profile/edit");
}
but this says that variable localUser is already defined.
2) also, I tried this
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User updatedUser = formData.get();
updatedUser.save();
}
return redirect("/profile/edit");
}
but this code is creating a new user in the database.
I am new to Play so I am waiting for any advice. Thanks and sorry for my english
Does your user have a unique id? If so, you could try the following:
updatedUser.setId(localUser.getId())
updatedUser.save()
Saw this example here:
How to update an existing object in playframework 2.0.2? aka CRUD in 1.2.x
... along the lines of what #mantithetical was saying. Better to have an update method in your User class:
public static Result update(Long id) {
Form<User> userForm = form(User.class).bindFromRequest();
if(userForm.hasErrors()) {
return badRequest(editForm.render(id, userForm));
}
userForm.get().update(id);
...
Just a matter of providing the unique id (note that also, we're relying on the id, rather than the entire user, when handling bad requests). You can do that by adding a parameter to your controller in the routes file:
POST /update/:id controllers.doEditProfile(id: Long)
Then when you direct to your controller method, you have to pass that unique id in.

how to call sub mxml values into main mxml in flex?

Actually in my Flex sample applicaion have Main mxml called Demo.mxml..
in the main mxml file have login button when we click login button Login.mxml file called
protected function button2_clickHandler(event:MouseEvent):void
{
PopUpManager.createPopUp(this,Login);
}
In Login.mxml file doing some authetication useing java..
public var userService:UserService = new UserService();
[Bindable] public var userVO:UserVO = new UserVO();
protected function loginUser(event:MouseEvent):void
{
var rpcAuthenticateUser:AsyncToken = userService.authenticateUser(userid_id.text, password_id.text);
rpcAuthenticateUser.addResponder(new mx.rpc.Responder(handle_authenticate_success, handler_failure));
}
........
userVO=userService.getUser();
......
All are done in Login.mxml file correctly Now i am getting value.
How to get userVO object in Demo.mxml file ?
Actually i'm trying but it give some Null values......Plz help me
Thanks in Advance...
create a model class that is a singleton See my answer here about making a singleton.
then in your Demo.mxml
[Bindable] public var model:MyModel = MyModel.getInstance();
then in your login form
public var model:MyModel = MyModel.getInstance();
then when you get the response from the service:
model.userVO = userService.getUser();
now in your Demo.mxml, userVO is now populated and usable there.

How to make java Object visible in Sub mxml to Main mxml file in Flex?

In my Application using Flex-Blazeds-java...,in my Flex application side have two mxml file
Main.mxml
Login.mxml
In Main.mxml file have button called Login click this button one popup open that is called Login.mxml
in this File i have authentication logic to connect java...sample code`
public var userService:UserService = new UserService();
[Bindable] public var userVO1:UserVO = new UserVO();
protected function loginUser(event:MouseEvent):void
{
var rpcAuthenticateUser:AsyncToken = userService.authenticateUser(userid_id.text, password_id.text);//Hear authenticateUser(-,-) is a java method it return UserVO object
rpcAuthenticateUser.addResponder(new mx.rpc.Responder(handler_success, handler_failure));
}
private function handler_failure(event:FaultEvent): void {
Alert.show("in handler_failure :" + event.message);
}
private function handler_success(event:ResultEvent): void {
userVO = event.result as UserVO;
Alert.show("test "+userVO.loginId);
}
Hear Login Working Perfectly according my Database logic and also if it is ResultEvent the Alert box show correct value (for ex:loginId is 'narasimham')...and everthing working perfectly no default in Login.mxml
Now The Problem Start...
I want to Use UserVO object in Main.mxml file so in that i'm using following code..
public var loginUserVar:Login = new Login();
protected function afterLoginUser(event:FlexEvent):void
{
Alert.show("LoginId ="+loginUserVar.userVO.loginId);
}
Actually my thinking this Alert box giving value narasimham but it is giving null value.
Why it is giving Null value?Is their any Scope specify to create variable?
In handler_success you need to set the value of userVO1 otherwise it won't be available otuside of your mxml file. You also need to to reference it in afterLoginUser as userVO1 instead of userVO.
Correct Ethrbunny i'm not store the value of userVO object so it is not available to Out side mxml file....
That's way in Flex(3.5) Application in Login.mxml file i'm adding following code...
Application.application.userVO = event.result as UserVO;
//Hear userVO is Object defined in Main.mxml file....

Categories

Resources