I have problem with resolving my response which always resolve as true. I am submitting a form for forgotten password, and i have only one field there, that is e-mail. I check in the database for the record on base on the e-mail, and if the record is returned, i set the json to true, else to false. Here is the code from my Codeigniter controller:
public function checkEmail()
{
// set the validation rules
$this->form_validation->set_rules('checkemail', 'E-Mail', 'valid_email');
$this->form_validation->set_error_delimiters('<br /><p class=jsdiserr>', '</p><br />');
// if validation is passed
if ($this->form_validation->run() != FALSE)
{
$ids=array();
$ids[0]=$this->db->where('email', $this->input->post('checkemail'));
$query = $this->backOfficeUsersModel->get();
if($query)
{
$data = array(
'userid' => $query[0]['userid'],
'username' => $query[0]['username'],
'password' => $query[0]['password'],
'firstname' => $query[0]['firstname'],
'lastname' => $query[0]['lastname'],
'email' => $query[0]['email']
);
$currentUser = array();
$currentUser = $this->session->set_userdata($data);
echo json_encode(array("success" => "true"));
} else {
echo json_encode(array("success" => "false"));
}
// form validation has failed
} else {
$errorMessage = "Wrong email!";
}
} // end of function checkEmail
Now, when i check the result in my javascript file, i get always true. Here is the code:
$("#formSendPassword").submit(function(e){
e.preventDefault();
var email = $(this).find("#checkemail").val();
var obj = {email: email};
var url = $(this).attr("action");
$.post(url, obj, function(r){
if(r.success == "true") {
console.log(r.success);
$('#forgotPasswordForm').hide();
$('#successMailMessage').fadeIn()
} else {
$('#forgotPasswordForm').hide();
$('#errorMailMessage').fadeIn()
}
}, 'json')
})
Can anyone give me a hand with this?
Regards,Zoran
Firstly modify the PHP...
json_encode(array("success" => "true"));
to
json_encode(array("success" => true));
and also
json_encode(array("success" => "false"));
to
json_encode(array("success" => false));
Then modify the JS as follows by changing...
if(r.success == "true") {
to...
if(r.success === true) {
See how you go from there!
EDIT: In liaison with the OP we concluded that the actual issue was the way JS was posting the data.
var obj = {email: email};
Should have been...
var obj = {checkemail: email};
There were also a few specific problems with the PHP that were unrelated to the issue but have now been fixed.
if ($this->form_validation->run() != FALSE)
should be
if ($this->form_validation->run() !== FALSE)
or simply
if (!$this->form_validation->run())
Is the best way to chekc for false... != may not always do as you expect!
You need to parse the JSON in the JS: myObj = $.parseJSON(r);
then use myObj.success
Related
My middleware Code:
public function handle($request, Closure $next) {
$api_headers = getallheaders();
$error_msg = '';
$error = 0;
if (isset($api_headers) && !empty($api_headers)) {
if (isset($api_headers ['device_id']) && !empty($api_headers['device_id'])) {
} else {
$error_msg = 'Please send device ID header.';
$error = 1;
}
if (isset($api_headers['device_type']) && !empty($api_headers['device_type'])) {
} else {
$error_msg = 'Please send device type header.';
$error = 1;
}
} else {
$error_msg = 'Please send headers.';
$error = 1;
}
if ($error == 1) {
return base64_encode(response()->json(['error' => true, 'message' => $error_msg, 'code' => 0]));
} else {
return $next($request);
}
}
I want to convert the JSON to a encoded string and send it as a response. So i used base64_encode to converted it into a string. But it is not working in middleware. I do not know its reason I made a lot of efforts but did not understand what to do. I am also attaching a screenshot of the error. Please help if possible.
I dont know what status code you want to respond with, but try:
$encoded = base64_encode(response()->json([
'error' => true,
'message' => $error_msg,
'code' => 0
]));
return response($encoded, ?response status code?)
->header('Content-Type', 'text/plain');
I want to add Ajax validation to check the form before updating. In the view, added to the required field
['enableAjaxValidation' => true]
In the controller in the actionUpdate
if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
if ($modelForm->validate()) {
$model->setAttributes($modelForm->getAttributes());
if ($model->save()) {
return $this->redirect([my way]);
}
if ($model->hasErrors()) {
return ActiveForm::validate($model);
} else {
return ['success' => 1, 'html' =>
$this->renderPartial('view', [my data];
}
} else {
return ActiveForm::validate($modelForm);
}
}
The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?
In controller try it like this:
$model = new ExampleForm;
// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Add this before your if statement, and remove Yii::$app->request->isAjax from your if statement.
Add some thing like below in your form
$form = ActiveForm::begin([
'id' => 'example',
'action' => ['your_action'],
'validateOnSubmit' => true,
'enableAjaxValidation' => true,
])
I want to handle user registration via ajax call. So therefore I've created a registration class (defined as a service) which will be loaded in different controllers:
public function loadRegisterForm($request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user, array('attr' => array('class' => 'ajaxRegisterForm',)));
$form->handleRequest($request);
$errors = "";
$parametersArray['result'] = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Success! User registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig')
), 400);
}
else
{
$errors = $this->get('validator')->validate($form);
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Failure! User not registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig'),
'errors' => $errors,
), 200);
}
}
$parametersArray['register_form'] = $form;
$parametersArray['errors'] = $errors;
return $parametersArray;
}
Then I've created a main controller, where registration form is being loaded:
/*
* #Route("/", name="MainPageNotPaginated")
*/
public function indexAction(Request $request)
{
/**
* Load register form
*/
$registerForm = $this->get('register_form_service');
$registerFormParameters = $registerForm->loadRegisterForm($request);
return $this->render(
'ImmoBundle::Pages/mainPage.html.twig',
array(
'register_form' => $registerFormParameters['register_form']->createView(),
'errors' => $registerFormParameters['errors'],
'result' => $registerFormParameters['result'],
)
);
}
Further I've added an ajax call to my javascript file:
$('.registerFormContainer').on('submit', '.ajaxRegisterForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
$('.registerFormContainer').html(data.result);
}
alert('success');
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
$('.registerFormError').html(jqXHR.responseJSON.result);
} else {
alert("fail");
}
});
});
Now, when I submit the registration form without filling in data (which normally should return an error) I've got an 'success' alert. The same 'success' alert is visible when the submitted registration form is valid.
I've tried
console.log(data.message)
but console says 'undefined'.
What am I doing wrong here?
Ok, I've figured it out. I've just added this line to my main controller (not the service one):
if ( $request->isXmlHttpRequest() ) {
return $registerFormParameters['result'];
}
I cannot save hashed password to my 'users' table, but if it's not hashed, the password saved. Can everybody help me?
Controller
public function add()
{
$this->data['title'] = 'add new user';
$this->data['subview'] = 'admin/user/add';
$validate = $this->user->validate;
$this->form_validation->set_rules($validate);
if ($this->form_validation->run() == TRUE){
$this->user->insert(array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->user->hash($this->input->post('password'))
));
$this->session->set_flashdata('message', msg_success('Data Saved'));
redirect('admin/user', 'refresh');
}
$this->load->view('admin/_layout_main', $this->data);
}
my Hash function in user_model
public function hash($string)
{
return hash('md5', $string . config_item('encryption_key'));
}
What's wrong with my code, or is there any other way to do it without any library? or How you do it basically to do this using codeigniter? Thanks
EDIT
this is my insert function from MY_Model
public function insert($data, $skip_validation = FALSE)
{
if ($skip_validation === FALSE)
{
$data = $this->validate($data);
}
if ($data !== FALSE)
{
$data = $this->trigger('before_create', $data);
$this->_database->insert($this->_table, $data);
$insert_id = $this->_database->insert_id();
$this->trigger('after_create', $insert_id);
return $insert_id;
}
else
{
return FALSE;
}
}
Im using Jamie Rumbelow Base Model for my base model, and I have follow his tutorial for insert into database
I'm using CakePHP v2.2.1 stable. I have a UsersController with the action add(). I'm trying to send the user info via ajax (from the home page to /users/add) and save the data. My code is something like this:
// /app/View/Pages/home.ctp
<?php
$data = array('User' => array('username' => 'vegeta_super_sayajin',
'password' => 'over9000!', 'email' => 'vegeta#supersayajin.com',
'profile_pic' => '/home/pics/scouter.jpg', 'firstname' => 'Vegeta',
'lastname' => 'Vegeta', 'level_id' => '9001'));
?>
<script type="text/javascript">
var data = <?php echo json_encode($data); ?> //convert $data into json format
$.ajax({url: '/users/add', data: "data="+data, type: 'post'});
</script>
How do I receive this data in the UsersController, so that I can process and save it?
Currently, I'm trying:
// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
//returns "Error: [object Object] in logfile
$this->log($this->request->data);
} else {
$this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}
$this->log($this->request->data) returns Error: [object Object] in the /app/tmp/logs/error.log file, and this user info does not exist in any of $this->request->params's indexes. All my googling so far has returned only complicated cakephp v1.3 techniques. How is this done in cakephp v2.2.1?
You can try the following code. It will work for you.
<?php
$data = array(
'User' => array(
'username' => 'vegeta_super_sayajin',
'password' => 'over9000!',
'email' => 'vegeta#supersayajin.com',
'profile_pic' => '/home/pics/scouter.jpg',
'firstname' => 'Vegeta',
'lastname' => 'Vegeta',
'level_id' => '9001')
);
?>
<script type="text/javascript">
var data = [<?php echo json_encode($data); ?>] //convert $data into json format
$.ajax({
url: 'checks/add',
data: "data="+JSON.stringify(data),
type: 'post'});
</script>
And in your controller's code:
// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
$this->log(json_encode($this->request->data, true)); //returns "Error: [object Object] in logfile
} else {
$this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}
Here is the json_decode documentation. The second parameter true will convert the object into an array.