Cakephp and Sweet Alert - javascript

I have a question about cakephp and sweet alert.
Are you able to replace, and instead of the standard Flash Message, give Sweet Alert? I have already managed to give Sweet Alert the confirmation of deleting the record, but I do not know how I can handle it when it saves data (for example in edit.ctp) and after saving it brings me to index.ctp (here I want Sweet Jump to pop out).
At the confirmation of removal I used cakephp-3-sweet-alert-helper by falco442.
This is my edit method:
public function edit($id = null)
{
$contact = $this->Contacts->get($id, [
'contain' => ['Users', 'Departments']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$contact = $this->Contacts->patchEntity($contact, $this->request->getData());
if ($this->Contacts->save($contact)) {
$this->Flash->success('Contact saved');
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The contact could not be saved. Please, try again.'));
}
$users = $this->Contacts->Users->find('list', ['limit' => 200]);
$this->set(compact('contact', 'users'));
}
How can I replace this $this->Flash->success('Your Success Message.'); with an alert from SWAL ?

You should leave controller code as is.
But you should update flash message templates at src/Template/Element/Flash/.
By default, CakePHP outputs <div>, you should replace it with <script>swal("Hello world!");</script>

here you can set sweet alert javascript
Path: src/Template/Element/Flash
success.ctp
error.ctp
first thing use sweet alert js and css
swal({
title: "Success",
text: "Successfully created",
icon: "success",
});

Related

LocalStorage to sent to email via PHP from jQuery

I am trying to build a eCommerce/checkout system that is very bare bones, but I would like to take localStorage data and send it to PHP via jQuery or some other form (open to whatever is easiest). When the email was sent I received a '.' for 'productsInCart' and no text for 'totalCost'. I got the idea for this code from here, but seems like I am missing something on the jQuery side of things.
Relevant jQuery code (nested in a vanilla JS file):
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
// methods between
var orderDetails = localStorage.getItem('productsInCart');
var orderTotal = localStorage.getItem('totalCost');
jQuery.post("checkout-handler.php", {orderDetails: value}, function(data) {
}).fail(function(){
alert("Sorry, we messed up something on our end. Please try again.");
// localStorage.clear() on fail so the user can go back and fix issue?
// return user to previous page and show new alert?
});
jQuery.post("checkout-handler.php", {orderDetails: value}, function(data) {
// do something with PHP
}).fail(function() {
console.log('yikes');
});
Relevant PHP code:
$orderInfo = $_POST['orderDetails'];
$orderTotal = $_POST['orderTotal'];
// other variables needed are here
$body .= "".$name." ordered: ".$orderInfo. ". \r\n";
$body .= "Amount sent to paypal should be: ".$orderTotal. "\r\n";
//mail(....) is after
// HTML code to show user a confirmation message
Well you declared parameters but you never really used them:
var orderDetails = localStorage.getItem('productsInCart');
var orderTotal = localStorage.getItem('totalCost');
in your jQuery it should be:
jQuery.post("checkout-handler.php", {orderDetails: orderDetails}, function(data) {
}).fail(function(){
alert("Sorry, we messed up something on our end. Please try again.");
// localStorage.clear() on fail so the user can go back and fix issue?
// return user to previous page and show new alert?
});
jQuery.post("checkout-handler.php", {orderDetails: orderDetails}, function(data) {
// do something with PHP
}).fail(function() {
console.log('yikes');
});
You see I replaced value with orderDetails, because that holds your value.

Can't show data in javascript console

I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).

Not allowing a user to move forward to logging in until given access [duplicate]

This question already exists:
Blocking a user from logging in with a certain permission level and then an alert displaying to let them know why
Closed 7 years ago.
I am trying to figure out how to deny a user access from signing in to my site unless they have been approved. I am making my site private to only those I allow to join. Anyone can register, but once they do they are given a permission/group level of 1 or 'bench'. Once I accept the user and change the permission level, then they are able to login.
As of now, I am stopping the level/group 1 users with a redirect back to the index page(where they sign in at). However, I want to not allow them to move forward to the next page at all. The reason being is I want to display some sort of pop up alert displaying a message that I created.
I'm not sure if I can do this with validation or the way I am trying to do it. I added on to my login code and am attempting to put my permission code I had on the signed in page to try to stop it from the start. Basically, in an attempt that if the user tries to log in, the script dies once it sees that the permission level is at the group 'bench'. Then a pop alert displays saying why.
I'm not having much success with it. My group/permission levels have a name and ID. I have tried putting both in this single quotatiob's like 'bench' and '1', but I get the same error with both.
Fatal error: Call to a member function hasPermission() on a non-object in /home4/pfarley1/public_html/example.com/index.php on line 12
I'm trying to log them in like this...
<?php
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
// added this line in
if($user->hasPermission('1')) {
die($permissionError);}
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('userIndex.php');
} else {
$tryagain = '<span class="signinpanel">' . "The information you entered did not match our records." . '</span>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
My permission code for users..
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
What am I doing wrong this this or is there a better way to do this?
Edit:
The last question wasn't specific enough, so I added info and there has been modification to the code in how I was trying to do this.
What is $user on line 12?
if($user->hasPermission('1')) {
Error message is pretty explicit.

yii in submit button display confirm message two time

In my form, I have given a confirmation message before saving.
CHtml::submitButton('Save', array('confirm'=>'Are you sure you want to save?'));
But the message box appears two times... What is wrong ?
Here is the form where you can got the answer of your thing... this is one way of doing it...!!!
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'customer-form-guest',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
alert("There are errors in form inputs please resolve it.");
}
else
{
var r = confirm("Are you sure y7ou want to do this ..?");
if(r == true)
{
return true;
}
else
{
return false;
}
}
}' ),
'htmlOptions'=>array('role'=>"form")));
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',
array('confirm'=> 'Are you sure?')); ?>
When Click on Save then Same Page render than Controller generate view that time also who messege that's an issue. You have to pass some value in URL and then When view load that time just write condition for that does't show twice.

Submitting one form and Ajaxing too

I use below code to submit the form AND get registered in aweber email list (addlead.pl is just a registration script).
Here is what i want to accomplish:
User submits a form - it registers him in aweber email list (using two of many form fields) as it woud be signup form, then user gets redirected to normal form action url with posted information from the form (all fields)
$('#redeemform').submit(function() {
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
});
alert("thank you"); //<<magic line
return true;
});
Code works but only with magic line - alert "thank you" - without this line it woud only submit to default form action not registering to aweber.
I've figured out that if i try submitting form (return true) and in the same time send those POST requests like this - site will refresh too fast and ingnore one of the requests.
Question is how do i do it without alert / some fixed delay in this line. Is there some kind of fancy command for it ?
Absolutely BEST solution is to let your form request call weber using CURL or similar on the server
since you cannot Ajax to another domain, you need to be more inventive if you are to run this on the client
So in the submission event we
Change the target to hiddenframe2
submit the aweber form to hiddenframe1
let the main form submit to hiddenframe2
Now you need in the RESULT of your main form return something like
<script>top.location.replace("thankyou.html");</script>
assuming your form sends the request to the same server the html comes from
and have
$('#redeemform').on("submit",function() {
$(this).prop("target","hiddenframe2");
if (!$("#hiddenframe1")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe1"})
.css("display","none")
.appendTo("body");
}
if (!$("#hiddenframe2")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe2"})
.css("display","none")
.appendTo("body");
}
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$("<form>",{"action":"http://www.aweber.com/scripts/addlead.pl",
"target":"hiddenFrame1"})
.append("<input/>",{meta_web_form_id: '1234'})
.append("<input/>",{meta_split_id: ''})
.append("<input/>",{listname: 'listname'})
.append("<input/>",{redirect: ''})
.append("<input/>",{meta_adtracking: 'newsletter'})
.append("<input/>",{meta_message: '1'})
.append("<input/>",{meta_required: 'name,email'})
.append("<input/>",{meta_tooltip: ''})
.append("<input/>",{email: emailVal})
.append("<input/>",{name: nameVal})
.submit();
});
Here is what COULD have done had you been able to Ajax to aweber, which you cannot because of cross domain scripting. If they support JSONP/CORS you may be able to do it anyway
$('#redeemformButton').on("click",function() {
var $form = $('#redeemform');
var nameVal = $form.find('input[name="custname"]').val();
var emailVal = $form.find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
},function() {
$form.submit();
});
});
and have a
<input type="button" id="redeemformButton" value="Sign up and submit" />

Categories

Resources