How to put custom url in angularjs $resource? - angularjs-resource

This is my angularjs service:
app.service("ConfigurationMasterService", function($resource){
return $resource('/configurationMasters/crud/:id',{
id: '#id'
},{
saveConfig : {
action : 'saveConfig',
method : 'GET',
URL : 'configurationMasters/crud/test',
}
});
});
Angular js controller as follows,
ConfigurationMasterService.saveConfig().$promise.then(function(response){
alert(response);
}, function(reason) {
alert(reason);
});
Here, i call the saveConfig() action.
My Rest Controller :
#RequestMapping(value = "configurationMasters/crud/test", method = RequestMethod.GET )
public void getString(){
System.out.println("test Method");
//return "Welcome Custom Method!";
}
"saveConfig" is my custom action ,but it is not works while calling this custom action. the error message throwing while try to call the saveConfig action

Related

How to make an admin ajax call in prestashop 1.7.6

I'm trying to make an ajax call in Prestashop Admin:
I created a module without a config page. It just add a button in some backoffice page, I'm trying to make an ajax call to my module file without success.
Making an ajax call in frontend is working (I added an ajax.php file in my modules/mymodule/controller/front/ directory), I tried to do the same thing for admin but it's not working at all.
What I've done:
loading the js file from actionAdminControllerSetMedia is ok
adding this in the composer.json file:
"autoload": {
"psr-4": {
"MyModule\\Controller\\": "controllers/admin/"
},
"config": {
"prepend-autoloader": false
},
created the controllers/admin/ajax.php file with this code (based on this documentation code):
namespace MyModule\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class DemoController extends FrameworkBundleAdminController
{
public $auth = false;
public $ssl = true;
public $ajax = true;
public $errors = false;
public $message;
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$this->ajaxDie(json_encode(array('success'=> !$this->errors, 'message' => $this->message)));
}
}
Then I tried to call the ajax from different way in js but never worked (the post query return is a message from prestashop "page not found" with http 200 response.
the doc isn't very helpful and I only find old messages/ways to do (from Prestashop 1.7.5 I'd be able to create a custom Admin controller but it doesn't work), can someone explain me the steps to follow?
thanks
Assuming it is for a PS1.7+ module, using Symphony:
Declare a link in a method of your admin controller (src/Controller/Admin) e.g
$adminLink = $this->generateUrl()
and return in with:
return $this->render
In your views/js/back.js"
$.ajax({
url: adminLink,
type: 'POST',
async: false,
data: {
},
success: (data) => {
}
});
Note: check the generateUrl and render functions for the necessary arguments.

How to return ajax response with error http code from PrestaShop ModuleFrontController?

I start working with PrestaShop 1.7.6 (before I worked with Symfony) and I write few custom modules to PrestaShop, but now I want send json data from my front controller module to user. Everything works fine if I send json with http code 200, but now I want send error message with proper http code (e.g 400). In Symfony I can do that by using JsonResponse (I try to do that here but it's not working as expected).I saw in presta controller are just two methods with ajax response (ajaxDie - which is deprecated and ajaxRender), but both of them doesn't takes as parameter http code response and always send 200.
if (!$product) {
$json = Tools::jsonEncode(['status' => false]);
$this->ajaxRender($json);
//return new JsonResponse($json, Response::HTTP_BAD_REQUEST);// doesn't send proper code
}
Can anyone tell me how to send error code from module front controller which extends ModuleFrontController?? Now only possible to me action is send error message with http code 200 (but I think it's bad idea to send error with that code). Thanks a lot for any help.
The proper way to send and receive data using AJAX is displayed below.
More information can be found at Prestashop Docs
Ajax post
$.ajax({
type: 'POST',
dataType : 'json',
url: 'linktoyourfile.php',
data: { action: 'getMyrequest' },
success: function(data) {
alert(data.result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' ' + errorThrown);
}
});
Module Front Controler
class TestModuleFrontController extends ModuleFrontController
{
public function init()
{
parent::init();
}
public function displayAjaxGetMyrequest()
{
// ERROR HANDELING
if ($this->errors) {
die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
} else {
echo Tools::json_encode(array('result' => 'test result'));
}
}
}

ReferenceError: data is not defined in angular 6

Im calling a service from one of my component, via the assignGirdle function. While this service is being executed, I get the above error, but when I check in the network tab and click on the API call, in response in can see the data.
Note girdleNew is of type any. Also this function I'm calling on ngOnInit()
assignGirdle() {
this.diamondSearchService.getDistinctValues()
.subscribe((data) => {
this.girdleNew = data;
}, error => {
this.alertify.error(error);
});
}
The service:
getDistinctValues() {
return this.authHttp
.get(this.baseUrl + 'distinct/girdle')
.map(response => response.json())
.catch(this.handleError);
}
Check if you have imported service in your component. Below is my data service import.
import { DataService } from '../data.service';
Create object of the same in your component:
constructor(public data: DataService) { }
In my component I have called this getUser() method which is defined in DataService.
this.data.getUser(email).subscribe( data => {
if(data.length > 0){
console.log(data);
}
});
Below is my service:
getUser(email){
// definition
}
This works for me.

Call Ajax Play FrameWork

I have a problem with ajax, play framework 2.1.1:
My Play Project
routes:
POST /sample/testapi controllers.Application.testapi()
GET /sample/ajax controllers.Application.ajax()
Application.java
public static Result testapi() {
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
public static Result ajax() {
return ok(ajax.render());
}
When I call action "testapi" from ajax.scala.html through ajax
My ajax code
$.ajax({
url : "http:// localhost:3333/sample/testapi",
type: 'POST',
data: {data: "test"},
dataType: "text",
success : function(result) {
alert(result);
},
error : function(request,error) {
alert(error);
}
});
It working fine.
And I have a html file and I call to play project through ajax.
The action had been called, but not return result and show alert "error".
Please help me. Thanks.
I added "response().setHeader("Access-Control-Allow-Origin", "*");" to my action.
public static Result testapi() {
response().setHeader("Access-Control-Allow-Origin", "*");
DynamicForm dynamicForm = DynamicForm.form().bindFromRequest();
String data= dynamicForm.get("data");
Logger.debug(data);
return ok("<user no='1'><id>1</id><name>Peter</name></user>");
}
"response().setHeader("Access-Control-Allow-Origin", "*");" allow other domain call it.

A challenge with onclick occured while combining MVC4, SignalR, knockoutJS

I have a simple MVC4 app where however I want to combine knockoutJS and SignalR and I got a challenge which seems to be caused by the fact that I'm trying to assign 2 onclick events on the same button: using knockoutJS and signalR. Please let me know what's wrong here. Below is the code.
This is my viewModel:
var viewModel = {
searchString: ko.observable("Monique"),
search: function () {
$.ajax({
url: "#Url.Action("Search")",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
$('#info').append(result.message);
}
});
},
searchClient: function () {
//do sth
},
showAll: function () {
//do sth
}
};
ko.applyBindings(viewModel);
And this part is related to signalR:
This is my hub on a server:
[HubName("send")]
public class DataHub: Hub
{
public void Send(string text)
{
Clients.All.addMessage(text);
}
}
and this is a signalR js part:
$(function () {
var hub = $.connection.send;
hub.client.addMessage = function (text) {
alert(text);
$('#info').append(text);
};
$.connection.hub.start().done(function () {
$('#btnServer').click(function () {
alert('btn server clicked');
hub.server.send("something");
});
});
});
So as you can see, knockoutJS has onclick event processing here search: function () { }
and in signalR I also have $('#btnServer').click(function() {.
And as a result, what is related to knockoutJS works but the part related to signalR does not work...
In that function where you bind click event using knockout, return true. By default, Knockout will prevent the click event from taking any default action.