I have a new.html.twig,I am using few ajax calls on this page on changes events of drop down.
So I have created a septate js file called new.js and keep my all JavaScript code inside this file, instead to write it on same view file.
But here in this js file I am unable to access the routing path which is call a ajax request. on change event.
===========New.twig.html=====================
include(new.js);
<select><name='a' onchange="setLabel('123')"></select>
============new.js.=============
function setLabel(voucherTypeID) {
queryString = "voucherTypeID=" + voucherTypeID;
$('#loading-image').show();
$.ajax({
type: "POST",
url: "{{path('vouchergeneration_getLedgers')}}", //THIS PATH How TO GET
data: queryString,
cache: "false",
dataType: "html",
success: function (data){
});
So here I am not able to access the URL Path, while it was accessible in twig file before. Please guide me how to fix this. I do not want to use anykind of Bundle for this simple work.. Thanks in advance..
There is very simple bundle for this simple work FOSJsRoutingBundle
Once this bundle is enabled you only need to do
Routing.generate('my_route_to_expose', { id: 10 }); // will result in
/foo/10/bar
Routing.generate('my_route_to_expose', { id: 10, foo: "bar" }); //
will result in /foo/10/bar?foo=bar
$.get(Routing.generate('my_route_to_expose', { id: 10, foo: "bar" }));
// will call /foo/10/bar?foo=bar
Routing.generate('my_route_to_expose_with_defaults'); // will result
in /blog/1
Routing.generate('my_route_to_expose_with_defaults', { id: 2 }); //
will result in /blog/2
Routing.generate('my_route_to_expose_with_defaults', { foo: "bar" });
// will result in /blog/1?foo=bar
Routing.generate('my_route_to_expose_with_defaults', { id: 2, foo:
"bar" }); // will result in /blog/2?foo=bar
EDIT:
Of course you can do it without bundle (which I don't think is a good idea). In that case I would advice set your routes in controller's action and set use it in twig template to set js variable. Something like:
Controller:
public function indexAction()
{
return array('yourRoute' => $router->generate('yourRoutName'));
}
your template:
<script type="text/javascript">
var yourRoute = '{{yourRoute}}';
</script>
your js:
(...)
url: yourRoute,
(...)
If you want to embed an URL and get it with your JS, you could do something like the following:
// HTML/Twig
<html data-my-route="{{ path('vouchergeneration_getLedgers') }}">
...
</html>
Then in your JS:
$.ajax({
type: "POST",
url: $('html').attr('data-my-route'),
data: queryString,
cache: "false",
dataType: "html",
success: function (data){
});
It avoids having global variable, and you can use as many data-attribute as you want.
If you are using fetch then you can get the url of the post by using data.url:
fetch('/check', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(qrinfo)
})
.then((data) => {
let url = data.url;
if(url.includes('/leave.html')) {
window.location.replace('/leave.html');
}
else {
console.log("Page not changed.");
}
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
You can check if the path name is included in the url instead by using .includes() so changing ports won't be an issue.
Related
I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];
I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that
Sorry for my terms incase they are incorrect, but I have a php function that I am going to interop with ajax so I can use a php function to get a value for a jquery variable.
So now I am just at the point where I have received the ajax callback and would like to set the jquery variable to the response value I got back. Here is my code as an example:
$(document).ready(function() {
$('body').videoBG({
position:"fixed",
zIndex:0,
mp4:'', //This is where I want to use the ajax response value
opacity:1,
});
})
jQuery.ajax({
type : "POST",
url : "index.php",
data : {
request : "getvideo_Action"
},
success : function(response) {
alert(response);
//Do my response stuff
}
});
So basically what I want to do is set the 'Mp4' var(or is it property?) with the value that I get from the response. Can anyone help me out with this? Thanks.
You can put the entire thing inside the success function, like this:
jQuery.ajax({
type: "POST",
url: "index.php",
data: {
request: "getvideo_Action"
},
success: function (response) {
$('body').videoBG({
position: "fixed",
zIndex: 0,
mp4: response,
opacity: 1
});
}
});
In this script, I'm fetching a load of data from a MySQL aray, and adding in a little favourite button on each array of returned data, the code for that is
...php while code to fetch array...
...more output...
<a class="favlink" id="'.$row['id'].'">favourite</a>
..more output...
and from that, I've used this bit of jQuery to run a PHP script:
<script>
$(function() {
$(".favlink").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "fav.php",
success: function(data) {
alert('asf');
}
});
});
});
</script>
That works fine, but what I actually want to do, is change the success to something like this:
success: function(data) {
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
And, that didn't work!
Is there any way I can change the clicked favourite link to a different font color / and change the text from 'favourite' to 'favourited'?
I assume the 'this' property is no longer 'this' on success for some reason, but I'm not sure?
Thank You!
You have to define the context of the ajax. See the docs from Jquery site:
contextObject This object will be made the context of all Ajax-related
callbacks. By default, the context is an object that represents the
ajax settings used in the call ($.ajaxSettings merged with the
settings passed to $.ajax). For example specifying a DOM element as
the context will make that the context for the complete callback of a
request, like so:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
So in your's case I think this is what you need:
$.ajax({
url: "test.html",
context: this,//OR: $(".favlink")[0], // Depends on your scope.
success: function(){
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
});
Add the following line to the $.ajax parameters. By default the context is linked to the $.ajaxSettings of the request. Setting the below line changes the context of this in the ajax request to equal that of the calling method.
context: this,
So your new code will look like this:
<script>
$(function() {
$(".favlink").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "fav.php",
context: this,
success: function(data) {
$(this).html("<font color='#ccc'><a href='#'>favourited</a></font>");
}
});
});
});
</script>
$(function() {
$('.favlink').click(function() { // this may match more than one element
var $this = $(this);
$.ajax({
'type': 'GET',
'data': 'v=' + this.id,
'url': 'fav.php',
'success': function(data) {
$this.html('whatever you want');
}
});
});
});
You could also use the context parameter for jQuery.ajax, but I personally think this (hah!) is more readable.
I'm building a chatroom that sends messages via AJAX. Whenever I hit enter, with the data: parameter, it returns an error, but if I remove data:, it doesn't do anything. This is very puzzling, and I'm wondering what I'm doing wrong. Here is what I have:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: "message="+$("#message").val()+"&user="+$("#user").val()+"&room="+$("#room").val(),
success: $("#message").val(""),
error: $("#message").val("FAIL"),
});
return false;
}
});
I use PHP in my AJAX call, so I don't know if that is causing the problem?
Try this:
...
$.ajax({
type: 'POST',
url: "send-message.php",
data: {message: $("#message").val(), user: $("#user").val(), room: $("#room").val()},
success: function() { $("#message").val(""); },
error: function() { $("#message").val("FAIL"); }
});
...
In the above code:
a) data sent as JSON - this will make sure that any url encoding and escaping will be correctly performed by jQuery as needed
b) success and error options must be callback functions
I would do this just to check if it grabs all the data correct:
var data = {
message: $('#message').val(),
user: $('#user').val
};
console.log(data);
You need to change these lines:
success: $("#message").val(""),
error: $("#message").val("FAIL"),
to
success: function () { $("#message").val("") },
error: function () { $("#message").val("FAIL") // removed trailing comma
I wrapped your handlers in a function and removed the trailing comma.
You can pass an object into data, and jQuery takes care of transforming it into the correct form for the type of request you issue, in this case a POST:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: {
message: $("#message").val(),
user: $("#user").val(),
room: $("#room").val()
},
success: function () {
$("#message").val("");
},
error: function () {
$("#message").val("FAIL");
},
});
return false;
}
});
Also, error and success are callbacks, so you need to provide a function, not a string if you want it called. Fixed it for you.
If you want to pass your data in POST you should use the javascript key:value format (or JSON format).
Input the following in
data: {"message": $("#message").val(),"var2":variable}
and a hint
...
data: $("#form").serialize();
...