How Can I pass the variable (stock.id) return from Ajax response to the route to generate the url to edit a stock
$.ajax({
url: 'sectors/stocks/' + $(this).data('sector-id'),
dataType:'json',
beforeSend:function() {
$('.stocks_list').html('Loading...');
}
})
.done(function(data) {
$('.stocks_list').html('<ul>');
$.each(data, function(index, obj_data) {
$.each(obj_data.stocks, function(indx, stock) {
$('.stocks_list').append('<li>' + stock.symbol + ' </li>');
});
});
})
You can first use a placeholder to generate the URL with and then replace that in javascript.
var url = '{{ route("admin.stocks.edit", ":id") }}';
url = url.replace(':id', stock.id);
$('.stocks_list').append('<li>' + stock.symbol + ' </li>');
In my opinion the simplest way is by concatenating javascript variable with blade string as follows.
Case 1: Route paramter is required
In this case pass the empty string in place of route parameter to by pass the required validation.
var url = "{{route('admin.stocks.edit', '')}}"+"/"+stock.id;
Case 2: Route paramter is optional
In this case you do not have to pass the empty string.
var url = "{{route('admin.stocks.edit')}}"+"/"+stock.id;
Best way to use route in ajax.
Add route in hidden input or take as a attribute into the button or link. Like below.
This will save the other jquery code like get id and pass into the url. It's simple just get the url from input and pass as a URL. That's it.
<a data-url="{{ route('delete.PendingPatient',['id' => $u->id]) }}" class="btn btn-xs btn-danger btn_delete"> Delete </a>
Route
<?php
Route::delete('/pending_patient/{id}','PatientController#pending_patient'])->name('delete.PendingPatient');
jQuery
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(document).on('click','.btn_delete',function(){
var current = jQuery(this);
var url = current.data('url');
$.ajax({
url: url,
dataType:'json',
beforeSend:function() {
$('.stocks_list').html('Loading...');
}
})
.done(function(data) {
$('.stocks_list').html('<ul>');
});
});
});
});
</script>
Thanks lukasgeiter, you make my day. It works. Only must to change the replace method because laravel scape ":" to "%3A"
var url = '{{ url("/admin/solicitud", ":id") }}';
url = url.replace('%3Aid', data.datos[i].id);
dhtml+='<td>Ver más...</td>';
or simple let the id string only
var url = '{{ url("/admin/solicitud", "id") }}';
url = url.replace('id', data.datos[i].id);
dhtml+='<td>Ver más...</td>';
let calculatedId = e.currentTarget.id.split("_")[1];
let url = '{{route('queryToggleStatus', ':queryId')}}';
url = url.replace(':queryId', calculatedId);
$.get(url, function(data, status) {
console.log (data);
})
Related
Currently, I am sending url to the ajax as :
$('.togglebtn').on("click",function(){
console.log("Hello")
$.ajax({
type: 'GET',
url: "http://localhost:8000/toggle/2945016571198",
contentType: 'application/json',
success: function (data) {
appendData(data);
function appendData(data) {
var mainContainer = document.getElementById("switch_{{forloop.counter}}");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
mainContainer.appendChild(div);
}
}
}
});
Currently, I am sending request into a static url. Can we use {% url toggle i.id %} to set the url dynamically in the ajax request? Does this ajax function repeats at all or not?
Not in that way or fashion, the {% url toggle i.id %} is for the Django template, so that is executed when rendering the page server side. What you want to do is client side.
Your are also trying to use "switch_{{forloop.counter}}", which won't work unless you have multiple snippets of the 'click' function. Which I would advise against since it simply doesn't make sense. You define a function once and then use it. See first example.
Best thing I can think of is exposing a 'base url' in your template and use that in javascript.
For example in your Django template:
<script>
// Put the Django variable into javascript context.
toggle_base_url = {{ toggle_base_url_from_django_view_context }};
// Use it in your ajax url by combining strings.
$('.togglebtn').on("click",function(){
console.log("Hello")
var obj = $(this); // Save the clicked button for reference.
var objectId = obj.attr('id');
var buttonId = obj.attr('data-button-id');
$.ajax({
type: 'GET',
url: toggle_base_url + "/" + buttonId
contentType: 'application/json',
success: function (data) {
// Cannot use 'this' in this context (IIRC), use the obj var we assigned.
// Replace with something to find your parent container
// Could use have a attribute on your button that points to the container.
// Probably the number you use in the url?
var mainContainer = obj.parent('containerclass');
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
mainContainer.appendChild(div);
}
}
}
});
</script>
In your Django view you do something like this:
# Make a base url to reuse, remove the last part.
# So turn `/toggle/1` into `/toggle`
base_url = reverse('toggle', args=[1]).rsplit('/', 1)
context = {
'toggle_base_url_from_django_view_context': base_url,
}
return render(request, 'yourtemplate.html', context=context)
So I have this piece of code:
$(document).on('click','.download_now[data-inputid={{ $field['name'] }}-filemanager]',function (event) {
event.preventDefault();
var loc = document.getElementById('proofAttach-filemanager').value;
document.location = "{{ url("+loc+") }}";
});
However, I'm getting the following url:
http://localhost/+loc+
If I remove the plus sign I get /loc and if I insert document.getelementbyid right there I get the text instead of the result.
What am I doing wrong?
Solved it
By using javascript to extract the base URL:
$(document).on('click','.download_now[data-inputid={{ $field['name'] }}-filemanager]',function (event) {
event.preventDefault();
var loc = document.getElementById('proofAttach-filemanager').value;
var base_url = window.location.origin;
document.location = base_url + "/" + loc;
});
This is my current code, any help would be greatly appreciated. I need to call my listApp.json file and parse it. I want to display my list which currently has one link. I'm new to this.
<script type = "text/javascript">
// If the .js files are linked correctly, we should see the following output inside the JavaScript Console
console.log("starting...");
// Gets the .json file and applies the function
var json;
// When the document is ready then run the function
$(document).ready(function(){
// Standard jQuery ajax technique to load a .json file
$.ajax({
type: "GET", // Requests data from a specified resource
url: "include/listApp.json", // Gets the file on which the url is directed to
dataType: "json", // Data Type needs to be json in this case. This can be xml
success: jsonParser // If successful then run the, 'jsonParser' function
});
});
// Actual parse function
function jsonParser(data) {
JSON = data;
$(JSON).find("games").each(function (){
games = $(this);
var name = $(games).find("name").text();
var url = $(games).find("url").text();
var id = $(ganes).find("id").text();
console.log(name);
// Appends list + link + name
$("#myList").append('<li>'+ ""+name+""+'</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "'+ id +'"><img src = '+ url +'> test</div>');
});
}
</script>
Since data is an object, you can access the games array using data.listApp.games and iterate over it using $.each(), then inside the loop callback you will the game object as second param and you can access its properties using member operator
function jsonParser(data) {
$.each(data.listApp.games, function (i, game) {
var name = game.name;
var url = game.url;
var id = game.id;
console.log(name);
// Appends list + link + name
$("#myList").append('<li>' + "" + name + "" + '</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "' + id + '"><img src = ' + url + '> test</div>');
});
}
I have the following link that passes an id to my controller to render a report.
Print Report
I would like to assign this value id in the link above to the result I have returned from the database in the call below....
// Global variable
var DocumentID = null;
$('#Save').click(function(e) {
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "/Home/SaveDetails",
dataType: "json",
type: "POST",
data: ko.toJSON(viewModel),
contentType: "application/json;charset=utf-8",
success: function(result) {
if (result > 0) {
//Assign return value to DocumentID
DocumentID = result;
alert("This work request has been successfully saved in database. The Document ID is: " + result);
} else {
alert("The Work Request was not saved, there was an issue.");
}
},
complete: function() {
// Hide loading image.
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle error.
alert(errorThrown);
}
});
} else {
alert("Form is not valid");
}
});
The call above works and returns a DocumentID and displays this in an alert with success. The link above works if the id has a hard-coded value; I would just like to make this value dynamic.
if (result > 0) {
//Assign return value to DocumentID
var DocumentID = result;
var href = '#Url.Action("GetReport", new { type = "PDF", id =' + DocumentID +'})';
$("a:contain('Print Report')").attr('href', href);
}
The above suggestions will generate an error for an unsupported pseudo, in this case 'contain' which is not available or known to the anchor tag. There is also an error with the syntax of putting the DocumentID in the Url.Action. I was not able to get this to work, instead I found another error: Too many characters in literal.
Instead give your anchor an id and find that id using jQuery and replace it's href attribute, this is done in the second line of code under Javascript.
html:
<a href="#" **id="Report"**>Print Report</a>
Javascript:
var DocumentID = result; var href = '#Url.Action("GetReport")?type="PDF"&id=' + DocumentID + '';
$("#Report").attr('href', href);
Take note of two things. The URL is formed and the anchor tag is found differently versus previous suggestions.
This has been tested and works for parameters of type string and int, respectively in your callback function to handle getting the report. If you want two strings then add an additional double-quote around the DocumentID like this: id=" ' + DocumentID + ' "';
in your ajax-success handler just set the href of the anchor to whatever you want
var newHref = '#Url.Action("GetReport", new { type = "PDF", id = '+DocumentID +'})';
$('a').attr('href',newHref);
I'm trying to pass a string from javascript to a razor ActionLink
string filtering =$("#Hello").val();
#Html.ActionLink(Name, ControllerName, new { sort = columm, order = orderby, filters = filtering })
but I'm not able to access to this variable, I already try #:filtering or "#filtering" but doesn't work anyway,
How can I pass the variable to the controller?
If you want to send or post the data to Controller's Action then you may try this...
<input type="submit" id="btnFilter" value="Filter" name="btnFilter" />
$('#btnFilter').click(function () {
var sort = sortValue;
var order = orderValue;
var filter= filterValue;
$.ajax({
type: 'POST',
url: '#Url.Action(ActionName, ControllerName)',
data:'{"sort":"' + sort+ '","order":"' + order+ '","filter":"' + filter+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function () {
}
});
});
then.... in controller action
public ActionResult ActionName(string sort ,string order , string filter)
{
// do Something here....
}
You'd have to add the parameter to the URL yourself manually using jQuery to assign the href attribute of the anchor tag.
First, let's take off the filter parameter off your ActionLink and give it an ID (so we can reference it in jQUery):
#Html.ActionLink(Name, Controller, new { sort = columm, order = orderby }, new { id = "myLink" })
Then do the following jQuery:
$(function () {
var newLink = $("#myLink").attr("href") + "?filter= " + $("#Hello").val();
$("#myLink").attr("href", newLink);
});
the way that I could do it was passing the Url to the controller
window.location = window.location.protocol + "//" + location.host + "/Name/Controller/" + "?sort=sort" + "&order=order" + "&page=page" + "&filters=" + filter;