I'm trying to create delete confirmation in my app using sweet alert when I click to delete button so I am facing an error on console Uncaught TypeError: Cannot call a class as a function
Please suggest on how to fix this error?
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
if ( $delete == 1) {
$success = true;
$message = "User deleted successfully";
} else {
$success = true;
$message = "User not found";
}
}
HTML view
<a class="btn btn-danger" onclick="deleteConfirmation({{$digitizing-
>id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-
token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
It's because of the swal({ part of your code.
Swal is the name of the class. You will want to replace it with Swal.fire(.
Additionaly, please note that your php code will return $success = true; in both scenarios. You might want tot update that as well.
Related
i am new at laravel ,when i enable switch popup message is working perfectly but I don't want to show error popup message when i disable to switch please how can i do that help me thanks.
Does Anyone have an idea please help me thank.
CONTROLLER
public function featured(Request $request)
{
if ($request->is_featured) {
$assignFeature = Product::where('is_featured', 1)->exists();
if ($assignFeature) {
$response['error'] = 'Product is already featured';
return response()->json($response, 422);
}
}
$id = $request->input('id');
$featured = $request->input('is_featured');
$featurediItem = Product::find($id);
if ($featurediItem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
you can use axios.post.then method to work after getting response success fully. Something like this
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
}
here you can use your response variable to check if is_featured true do something what you want
I don't want to show popup message when i click to enable first any checkbox popup message should not be shown product is already feature! i have already made if condition for enable switch button, except any first switch i want to show popup message please help me how can i do that ?
please check image
https://ibb.co/QdFCd3z
i have made condition when i click to any switch enable message should be showing but now i want that when i click to any first switch enable popup message shouls not be shown
if(is_featured == true) {
swal({
text: "Product is already featured!",
type: 'error',
})
}
controller
public function featured(Request $request)
{
if ($request->is_featured) {
$assignFeature = Product::where('is_featured', 1)->exists();
if ($assignFeature) {
$response['message'] = 'Product is already featured';
return response()->json($response, 404);
}
}
$id = $request->input('id');
$featured = $request->input('is_featured');
$featurediItem = Product::find($id);
if ($featurediItem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
if(is_featured == true) {
swal({
text: "Product is already featured!",
type: 'error',
})
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
I'm making litte app to get pages by URL and check their title.
I need check URLs line by line which is user pasted in textarea.
Process sequence :
Check URL > append response to page > then check next url......
Here is my code :
HTML :
<textarea id="textarea" name="urlLine"></textarea>
<button type="button" name="action" id="check">Check IT!</button>
Js :
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500)
},
fail: function (msg) {
console.log(msg);
}
});
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
}
$(document).ready(function () {
$('#check').click(function () {
var uris= $('textarea').val().split('\n');
getResp(uris);
});
PHP :
sleep(5); // I don't know why i'm adding. Just wait for performance.
$title = 'title_i_searching';
$adress = $_POST['uriLine'];
if($check->chekURL('https://'.$adress) == $title){
echo ' OK';
}else{
echo 'NOT OK';
}
PHP CLASS :
class checkES
{
public $url;
public function chekURL($url){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http"=>array(
"timeout"=> 5
)
);
$str=
file_get_contents($url,false,stream_context_create($arrContextOptions));
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str));
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
return $title[1];
}
}
public function parseByLine($content){
$lines = preg_split('/\r\n|[\r\n]/', $content);
return $lines;
}
}
But when i run this code for example; in 20 URL searching on 5th url page alert 'finish'. But append function still continue.
Sometimes, page crash down.
I could not find the healthy method.
I wish i was explain. Sorry for bad language.
Try moving the code to process next uri in success function like this:
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500);
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
},
fail: function (msg) {
console.log(msg);
}
});
}
Right, i only want a very simple ajax request to get this working. im new with yii 2.0 framework you see.
in my view index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
Now when i call this i assume that it should go to my CasesController to an action called actionAjax.
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
EDIT::
Ok great, so this works up to here. I get back the alert that pops up with the new value for $test. However i want to be able to access this value in php as ultimately i will be accessing data from a database and ill be wanting to query and do various other things.
So how do i now use this variable in php instead of just the pop up alert()?
Here is how you can access the post data in controller:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}
//Controller file code
public function actionAjax()
{
$data = Yii::$app->request->post('test');
if (isset($data)) {
$test = "Ajax Worked!";
} else {
$test = "Ajax failed";
}
return \yii\helpers\Json::encode($test);
}
//_form.php code
<script>
$(document).ready(function () {
$("#mausers-user_email").focusout(function () {
sendFirstCategory();
});
});
function sendFirstCategory() {
var test = "this is an ajax test";
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax') ; ?>",
data: {test: test},
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
})
;
}
</script>
You can include js this way in your view file:
$script = <<< JS
$('#el').on('click', function(e) {
sendFirstCategory();
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
data: {test: test},
success: function(data) {
alert(data)
}
});
}
How can I prevent collection.create from adding items into its collection if there is an error found in the input?
html,
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea name="content"></textarea><br>
<input type="submit" value="Post">
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
backbone,
var Status = Backbone.Model.extend({
initialize: function(){
},
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
url:"dummy.php",
sync: function (method, model, options) {
return $.ajax({
type: "POST",
dataType: 'json',
url: 'server.php',
data: {
text: this.get("text")
}
});
}
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
_.bindAll(this, 'addStatus', 'clearInput');
this.listenTo(this.collection, 'add', this.clearInput) ;
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
So, when you hit the submit button without typing any text, you get an error popup from this part in the model,
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
But how can I tell the collection that there is an error and do not add this empty item and also do not fire sync in the model?
EDIT:
got it worked with collection.create in this way...
model,
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
view,
addStatus: function(e) {
e.preventDefault();
var one = new Status({ text: this.$('textarea').val() });
if (!one.isValid()) {
alert(one.validationError);
} else {
this.collection.create(one);
}
},
it seems to work fine unless it is not a good approach or against MVC pattern?
I don't think collection.create is the right choice here.
addStatus: function(e) {
e.preventDefault();
var status = new Status({"text": this.$('textarea').val()})
var error = status.valiate();
if(!error) {
this.collection.add(status);
}
},
Also not that the backbone docs says this about validate:
If the attributes are valid, don't return anything from validate; if
they are invalid, return an error of your choosing. It can be as
simple as a string error message to be displayed, or a complete error
object that describes the error programmatically.
So, your validate function should be fixed:
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
Your Model's validate method should return an error string so that models save is not fired in case of alert.
validate: function(attrs, options) {
if(attrs.text === ''){
alert("please enter some text");
return "Text is empty."; // OR proper error CODE
}
}
Check validate method of Backbone.Model.