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.
Related
Im having some real problems getting JQuery autocomplete to work in Net Core.
here is my client side script :
<script>
$(document).ready(function () {
$('#txtSystemUserDisplayName').autocomplete({
change: function (event, ui) {
if (!ui.item) {
$('#txtSystemUserDisplayName').val("");
}
},
source: function (request, response) {
$.ajax({
url: "#(Url.Action("SearchEmployeesAJAX", "Home" ))",
// data: "{ 'term': '" + request.term.replace(/'/gi, "\\'") + "'}",
data: { term: 'fumanchu' },
dataType: "json", type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var x = Array.prototype.slice.call(data);
response($.map(x, function (item) {
return {
label: item.employeeDisplayName,
}
}))
}, error: function (response) { alert(response.responseText); }, failure: function (response) { alert(response.responseText); }
});
},
select: function (e, i) {
$("#hfSystemUserDisplayName").val(i.item.label);
},
minLength: 1
});
});
Now when i start typing , the autocomplete fires but the param in the controller method is NULL , no matter what i do. it doesnt matter what i call the 'term' in the data object of the request. And yes i am making sure that the controller method parameter is named the same . eg
public JsonResult SearchEmployeesAJAX(String term) {
as you can see ive even commented it out and hardcoded a string in there, still null.
it DOES work if I set the string as part of the URL eg:
url: "#(Url.Action("SearchEmployeesAJAX", "Home", new {#term="blahblahblah" }
This is how I have always done autocompletes in the past on .Net Framework, and never had an issue. Is there something different about Net Core that im not aware of, maybe something different about how requests are formed?
Any help would be appreciated.
Ok so if anyone else is also having this problem, it appears that you cant use the Url.Action helper anymore and still have the parameter not be null.
You will need to use a raw string as the url instead, which seemed to solve this.
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.
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'));
}
}
}
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
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.