sending ajax request to a module service without no ajaxController - zend-framework3

I want to count how many times my menu items are clicked. for this task, I have a visited cell in my menu table that is retrieved by some models. the menu items are shown on my layout.phtml each specified by their id and I am trying to use ajax for this matter as below:
### menu items in layout.phtml
<li>about</li>
### ajax code
$(document).ready(function(){
$('a#menuItems').click(function () {
var data={};
data.id =$(this).attr("data_id");
$.ajax({
type : 'POST',
url :'../../../module/Application/src/Model/visitCounter.php',
data :data,
success: function(data){
},
error:function(){
}
});
});
});
the visitCounter.php is a service model that gets the variables via POST method do the rest of the work but the problem is how to send this ajax request to the service model page. I wonder if there is a way to achieve that without any controller.
I really appreciate if anyone could help me with this.

Related

Detect users input values from any wordpress form

I'm trying to develop a wordpress plugin, I need to get users input data from any form in a specific page (not knowing its action) I come up so far with this solution which is to get values using javascript and then passing it to php:
jQuery(function ($) {
$(document).ready(function(){
$( "form" ).submit(function( event ) {
if($( "form" ).valid()){
var inputs = $( "form input" );
var inputValues = [];
inputs.each(function(index){
if($(this).attr('type') !== 'submit')
inputValues.push($(this).val());
});
}
event.preventDefault();
});
});
});
I tried to pass the Javascript variable inputValues to my plugin using Ajax
$.ajax({
type: 'POST',
url: '../wp-content/plugins/myplugin/myplugin.php',
data: {'variable': inputValues},
});
But I get problems with the url for some pages and I couldn't use $_POST['variable'] in myplugin.php file.
Is there a way to accomplish what I'm trying to do, or do you know an alternative solution?
Thanks in advance.
in terms of how to implement AJAX calls using WordPress, please check out the WordPress Codex. You're not doing it correctly.
JavaScript seems like a round about way of doing this. I would suggest to hook into one of hooks that are being called almost every single time like template_redirect (https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect).
Then you can check what's in the $_POST variable and do what you need to do with it. This would even Capture AJAX forms as long as the URL links to a proper AJAX WordPress endpoint.
Hope this helps

Trigger.io + Angular.js and updating a view after calling forge.ajax

Having a problem, and so far couldn't get any solutions for seemingly similar SO questions to work. Problem is this:
Using Trigger.io's forge.ajax, my Angular.js view is not updated after the data is returned. I realize this is because forge.ajax is an asychronous function, and the data is returned after the view has already been displayed. I have tried to update the view by using $rootScope.apply(), but it doesn't work for me as shown in the many examples I have seen.
See the Controller code below:
function OfferListCtrl($scope) {
$scope.offers = [];
$scope.fetchOffers = function(callback) {
$scope.offers = [];
var successCallback = function(odataResults) {
var rawJsonData = JSON.parse(odataResults);
var offers = rawJsonData.d;
callback(offers);
};
var errorCallback = function (error){
alert("Failure:" + error.message);
};
forge.request.ajax({
type: 'GET',
url: 'https://www.example.com/ApplicationData.svc/Offers',
accepts: 'application/json;odata=verbose',
username: 'username',
password: 'password',
success: successCallback,
error: errorCallback
});
};
$scope.fetchOffers(function(offers) {
$scope.offers = offers;
forge.logging.info($scope.offers);
});
}
All the code there works fine, and $scope.offers gets populated with the Offer data from the database. The logging function shows the data is correct, and in the correct format.
I have tried using $rootScope.apply() in the logical places (and some illogical ones), but cannot get the view to update. If you have any ideas how I can get this to work, I would greatly appreciate it.
Edit: Added HTML
The HTML is below. Note the button with ng-click="refresh()". This is a just a workaround so I can at least see the data. It calls a one-line refresh function that executes $rootScope.apply(), which does update the view.
<div ng-controller="OfferListCtrl">
<h1>Offers</h1>
<ul>
<li ng-repeat="offer in offers">
<p>Description: {{offer.Description}}<br />
Id: {{offer.Id}}<br />
Created On: {{offer.CreatedOn}}<br />
Published: {{offer.Published}}<br />
</p>
</li>
</ul>
<input type="button" ng-click="refresh()" value="Refresh to show data" />
</div>
You need to change
$scope.fetchOffers(function(offers) {
$scope.$apply(function(){
$scope.offers = offers;
});
forge.logging.info($scope.offers);
});
It is because all changes to the $scope has to be made within the angular scope, in this case since you are calling ajax request using forge the callback is not executing within the angular framework, that is why it is not working.
You can use $scope.$apply() in this case to execute the code within angular framework.
Look at the $apply() methods doc
$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life-cycle of
exception handling, executing watches.
do this
function MyController($scope, myService)
{
myService.fetchOffers(data){
//assign your data here something like below or whateever
$offers = data
$scope.$apply();
}
});
Thanks
Dhiraj
When I do that I have an error like : "$digest already in progress"...
I'm Working with $q...
Someone knwo how I can resolve this issue ?
yes, this is caused where ur data comes fast enough and angular has not finished his rendering so the update cant update "outside" angular yet.
so use events:
http://bresleveloper.blogspot.co.il/2013/08/angularjs-and-ajax-angular-is-not.html

Many-to-Many Ajax Forms (Symfony2 Forms)

I have a many-to-many relationship in mongodb between Players and Tournaments.
I want to be able to add many Players to a Tournament at once. This is trivial to do without ajax, but we have a DB of thousands of Players, and so the form select becomes huge.
We want to use ajax for this. Is it possible to create a single widget (with js) to handle this properly? If so, any hints on what jquery plugin (or other) to use?
If not, whats the standard strategy to do this? I suppose I could heavily change the view for this form and use an ajax autocomplete to add one player at a time, and then some more code to delete each player one at a time. However, I'd really like to have a single widget I can re-use because its so much cleaner and seems much more efficient.
I have been playing with Select2 all day (similar to jQuery Chosen) and I have it working for adding many Players via ajax, but it does not allow me to set the already attached players when I initially load the page, so I won't be able to see who's already in the tournament and would have to retype everyone in.
Thanks for ANY input on this matter! I can't find anything via Google.
I was able to accomplish this by $.ajax after the constructor within the onload function where //website/jsonItem is a json-encoded list of all items, and //website/jsonItemUser is a json-encoded list of all items attached to user. I used // to keep the https/http consistent between calls.
$(document).ready(function(){
$('.selectitem').select2({
minimumInputLength:0
,multiple: true
,ajax: {
url: "//website/jsonItem"
,dataType: 'jsonp'
,data: function (term, page) {
return {
q: term, // search term
limit: 20,
page: page
};
}
,results: function (data, page) {
var more = (page * 20) < data.total;
return {
results: data.objects, more: more
};
}
}
,initSelection: function(element, callback){
var items=new Array();
$.ajax({
url: "//website/jsonItemUser"
});
callback(items);
}
});
$.ajax({
url: "//website/jsonItemUser"
,dataType: 'jsonp'
,success: function(items, status, ob) {
$('.selectitem').select2('data',items);
}
});
});

How to post parameter value to some actionlink

In my view i have 10 link every link associated with some unique value. Now i want that associated value at my controller action and from that action i want to redirect the flow to some other action based on that value.
But the condition is i dont want to display it on url.
How can i acheive this?
I tried ajax.post/#Ajax.ActionLink but doing this will not facilitate redirect to another action.
Is there anything with route i need to do?
View
<ul>#foreach (var item in Model)
{<li>
#Ajax.ActionLink(item.pk_name, "Index","Candidate", new { para1= item.para1 }
, new AjaxOptions { HttpMethod = "POST" })</li>
}</ul>
Action
[HttPost]
public ActionResult(int para1)
{
return RedirectToAction(para1,"anotherController");
}
I am getting value at para1 with ajax post(that is what i primarily needed) but here also want to redirect my application flow base on para1 value which is action name.
Confision : here i am not sure is this is the right way to do this thing. So i am asking you guys should i go for route map of working with ajax post will solve my objective.
If you only need to redirect the user based on what he clicks on without showing him the link, I believe the best way to achieve this is by client-side coding.
In my opinion there is no need to take any request through the server in order to change the page for such a low-complexity redirect.
View
// HTML
// Might be broken, been awhile since I worked with MVC
// Can't really remember if that's how you put variables in HTML
<ul id="button-list">
#foreach(var item in Model)
{
<li class="buttonish" data-para1="#item.para1">#item.pk_name</li>
}
</ul>
// JS
// I wouldn't do any server related work
$('#button-list li.buttonish').click(function(){
// Your controller and action just seem to redirect to another controller and send in the parameter
window.location.href = "/controller/method/" + $(this).data('para1');
});
I think you should make one jQuery function that is call when clicked and pass unique parameter.In that function you can use AJAX and post it on appropriate controller method.
Example:
<input type="button" id="#item.pk_name" onclick="getbuttonvalue(#item.para1);" />
In script
<script type="text/javascript">
$(document).ready(function () {
function getbuttonvalue(para1) {
$.ajax({
cache: false,
type: "POST",
dataType: 'json',
url: "/controller/method/" + para1,
success: function (data) {
}
});
}
});
</script>

Node.js HTTP: request 'end' event is never called

I have a client that is sending data chunks to my node.js server.
I want to listen on the "end" event and retrieve the accumulated request body.
Here is my code:
app.post('/users', function(req, res){
req.on('end', function() { // WHY IS THIS NEVER FIRED?
console.log(req.body);
res.send({
"status": "ok"
});
});
});
The problem is that the 'end' event is never fired.
Anyone knows why?
Also, if I do in this way, will the req.body be the accumulated body of all the body chunks?
Basically http POST only fires when you POST to the server. I can't be certain, but I'm assuming you are just attempting to visit server:port/users in your web browser and fail to get a response. By default the web browser is GETing the server. To fix this you have two options.
1. If you change app.post to app.get the event will correctly fire when you visit /users
2. Or you can fire the post function using a form. For example the following code will display a form if you visit the page using GET. When you submit the form it will fire POST.
var express = require('express'),
app = express.createServer();
app.listen(1337, "127.0.0.1");
app.get('/users',function(req,res){
res.send('<form method="post" action="/users"><input type="submit" value="Submit" /></form>');
})
app.post('/users', function(req, res){
req.on('end', function() {
console.log('success');
res.send('success!!!');
});
});
I encountered the same problem, and found this discussion helpful:
My http.createserver in node.js doesn't work?
Simply put, by inserting the line:
request.on("data",function() {})
inside the .createServer loop but after the request.on loop made it work.

Resources