Showing kartik growl via ajax in yii2 - javascript

Am using kartik growl and i would like to show the growl via ajax success
I have tried
This is the javascript code:
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys,user:userdata},
success: function(data) {
console.log(data);
//$.pjax.reload({container:'#forward-grid'});
$.growl( data.growl );
},
error: function(err){
alert(err);
console.log("server error");
}
});
This is the controller code:
$growl = [
'title' => "Group members updated.<hr>",
'icon' => 'glyphicon glyphicon-ok-sign',
'message' => "Successifully updated.",
'showSeparator' => true,
];
echo json_encode(['response'=>"Successifully forwarded pr(s)", 'growl' => $growl ]);

If you see TypeError: $.growl is not a function, then it means you have not included required files to AppAsset.php file.
To solve this problem, go to assets/AppAsset.php file and add:
public $css = [
// ... Something else might be here
'css/jquery.growl.css',
];
And
public $js = [
// Something else might be here
'js/core.js',
];
Because of missing .js file, you have that error in console (TypeError: $.growl is not a function). But you also must add .css file as well because without it you will not see growl, even though it works.

I believe you're using the wrong function. Here's offical docs:
"Another important update is since version 3.x you no longer call the
plugin using $.growl(...) you must use $.notify(...)."
In another words, just try using $.notify(...) instead of $.growl(...).

Related

Axios get call in Vue3 not working, although curl and javascript work as expected

I'm trying to make an API call from my Vue3 app. The prepared API has an endpoint like http://localhost:8888/api/dtconfigsearch, where one needs to pass a json payload like { "Modelname": "MyFancyModel"} to get the full dataset with the given modelname. Pure get functions without a payload / a body do work from my Vue3 project to the golang backend, but I'm having problems with passing a payload to the backend.
Test with curl -> ok
$ curl -XGET localhost:8888/api/dtconfigsearch -d '{"Modelname" : "MyFancyModel" }'
{"ID":4,"Modelname":"MyFancyModel","ModelId":"96ee6e80-8d4a-b59a-3524-ced3187ce7144000","OutputTopic":"json/fancyoutput"}
$
This is the expected output.
Test with javascript ok
Source file index.js:
const axios = require('axios');
function makeGetRequest() {
axios.get(
'http://localhost:8888/api/dtconfigsearch',
{
data: { Modelname : "MyFancyModel" },
headers: {
'Content-type' : 'application/json'
}
}
)
.then(resp => {
console.log(resp.data)
})
.catch(err => {
console.log(err)
})
}
makeGetRequest()
Output
$ node index.js
{
ID: 4,
Modelname: 'MyFancyModel',
ModelId: '96ee6e80-8d4a-b59a-3524-ced3187ce7144000',
OutputTopic: 'json/fancyoutput'
}
$
Here, I also get the desired output.
Test within Vue fails :-(
Source in the Vue one file component:
onSelection(event) {
let searchPattern = { Modelname : event.target.value }
console.log(event.target.value)
console.log("searchPattern = " + searchPattern)
axios.get("http://localhost:8888/api/dtconfigsearch",
{
data : { Modelname : "Windshield"},
headers: {
'Content-type' : 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err)
alert("Model with name " + event.target.value + " not found in database")
})
},
Output in browser:
In the image you can see in the terminal log on the right side that the backend is not receiving the body of the API call. However, in the browser information of the call there is content in the config.data part of the object tree, which is the payload / the body. The only thing that bothers me that it is not a json object, but stringified json, although it was entered as json object. According to the documentation, the parameter name (data) in the call should be correct to hold the body content of the api call.
I've tried different header information, looked if it could be a CORS issue, what it isn't to my opinion, exchanged key data with body, used axios instead of axios.get and adapted parameter, all without success. The version of the axios library is 0.27, identical for Vue and vanilla javascript. After checking successfully in javascript, I was sure that it would work the same way in Vue, but it didn't.
Now I'm lost and have no further ideas how to make it work. Maybe someone of you had similar issues and could give me a hint? I'd be very grateful for some tipps!!

All Put & Delete route method Throw 302 error in my laravel vue js project

I'm developing a laravel vue js application. Here I have a problem that all put & Delete method are throwing 302 error
this is my localhost response
this is my server response
Everything is running perfectly on my local pc but when I'm uploading this to the server then only get and post method working perfectly. Put & delete method throwing 302 error.
My route
Route::apiResource('category','CategoryController');
My Controller
public function update(Request $request, Category $category)
{
$this->validate($request, [
'name' => 'required',
]);
$category->name = $request->name;
$category->slug = Str::slug($request->name);
$category->save();
}
My Vue Component(I'm using V-form)
updateData() {
if (this.$middleware.admin()) {
this.$Progress.start();
this.form.put('api/category/' + this.form.id)
.then(() => {
Fire.$emit('getCategory');
$('#modal').modal('hide');
Toast.fire({
icon: 'success',
title: 'Category Updated successfully',
});
this.$Progress.finish();
})
.catch(() => {
this.$Progress.fail();
});
}
},
Try spoofing your method by adding <input type="hidden" name="_method" value="PUT"> to your form.
Or you could add _method: "PUT", to your component's form definition.
Take a look at the docs: https://laravel.com/docs/8.x/routing#form-method-spoofing

How to handle error from controller using PJAX in YII2?

I am using Yii2 Pjax widget which is unable to throw error from controller due to which I am unable to log error for users when there is any error coming from the controller.
PJAX code
<?php Pjax::begin([
'id' => 'createBucketPjax',
'timeout' => 4000,
'formSelector' => '#createBucketForm',
'enablePushState' => false,
'clientOptions' => [
'skipOuterContainers' => true,
'error' => new JsExpression("function(event) {
alert('Anything');
}"),
]
]); ?>
CONTROLLER code:
if(!$fieldModel->save()){
$transaction->rollBack();
//Here I want to send error
$error = $fieldModel->getErrorsString();
return [
'success' => false,'error' => $error
];
}else{
return $this->renderAjax('create', [
'model' => $model
]);
}
I have tried below clientOptions but not working
'error' => new JsExpression("function(event) {
alert('Please work');
}"),
Also used javascript but no help :-
$(document).on('pjax:error', function(event) {
console.log(event);
})
Is there any way from which I can send 404 from controller in yii2 ? That can actually resolve my problem
From the Yii2 Pjax docs.
In responding to the AJAX request, Pjax will send the updated body content (based on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then be updated using pushState. The whole process requires no reloading of the layout or resources (js, css)
You must deal with full form content and not with json.
So you code must look like following (always return the form html back):
if(!$model->save()){
$transaction->rollBack();
}
return $this->renderAjax('create', [
'model' => $model
]);

Vuejs won't let me console.log within request

In the methods section of my Vue.js script im trying to do a console.log but nothing is happening, in fact i can do no javascript at all within this section but the request to '/register' remains working.
postRegister: function(){
//code here works fine
console.log('working')
this.$http.post('/register', this.user, function(response){
//Any code here does not work even though the request itself has worked
console.log('not working');
});
}
My Controller
public function Register(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|unique:users|max:12',
'email' => 'required|unique:users|email',
'password' => 'required|confirmed'
]);
if ($validator->fails()) {
return $validator->errors()->all();
}
}
As i originally said, everything works the validator returns the correct responses and everything and the post attempt is made successfully, there is no console data being logged however within the http post request!
Since you are using the validator you're not getting back a 200 status code and that's why the success function will not get triggered. You should catch the error and then console.log it:
this.$http.post('/register', this.user)
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});

How to call code in app.js from mithril

I am creating a website where the backend is node.js with express, and clientside is using mithril. We cannot use ajax, form and jquery.
My question is how can we communicate from mithril js file to express? Let me give you example:
app.post("/testFunction",function(req,res){
//Pass result
});
In mithril:
m.render(document.body, [
m('input[type=text]'),
m('button'),
m('span', 'show the result')
]);
Here I have an input box and a button. When i click on button it should call my function in express, save data and return the message to be displayed in a span.
Any ideas?
You need to use m.request to make a post to your endpoint. Check out the docs here (http://mithril.js.org/request.html). Here's a quick example.
m.render(document.body, [
m('input[type=text]#testInput'),
m('button', {
onclick: function() {
document.getElementById("testInput").value
m.request({
method: "PUT",
url: "http://127.0.0.1:3000/testFunction",
data: {
inputValue: document.getElementById("testInput").value
}
})
.then(function(response) {
console.log(response);
})
}
}, "Send Request")
]);

Categories

Resources