Can't call variable result inside string - javascript

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;
});

Related

How to send django url with parameters to ajax request?

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)

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

Laravel 4, Pass a variable to route in javascript

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);
})

How to call a function when a page loads in Javascript with Jquery

<script type="text/javascript" >
function getDetails() {
var IDex = getQueryStringVariableByName("GameID");
$.ajax({
type: "POST",
url: "http:/...",
data: "{'ItemID': '" + escape(IDex) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.d;
$('#output').empty();
$.each(data, function (index, item) {
var str = "Title: " + item.Name + "<br /> Current Price: " + item.CurrentPrice + "<br /> Developer: " + item.Developer + "<br /> Genres: " + item.Genre
$('#output').append('<li>' + str + '</li>');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
function getQueryStringVariableByName(name) {
//use this function by passing it the name of the variable in the query
//string your are looking for. For example, if I had the query string
//"...?id=1" then I could pass the name "id" to this procedure to retrieve
//the value of the id variable from the querystring, in this case "1".
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = GetDetails;
//$(document).ready( function () {
// getDetails();
//
</script>
I have tried multiple methods to get getDetails to run when the page loads. I have tried the window.onload method, putting it in the body tag, and a few others but I can't seem to find a way to get it to load automatically.
it should be getDetails or you could use:
$(document).ready(function(){
functionname();
});
To check if the compiler was actually reading your code when the page loads is
$(document).ready(function() {
getDetails();
});
function getDetails() {
alert("this is a try");
//or
console.log("this is a try");
}
and of course include the jquery framework to your document like
<script src = "path" type = "text/javascript"></script>
The best way to do is write it before you have to close the body tag
Hope it helps!
I'm not sure I understand the question, but the way to run a function a after page loads in jQuery is this:
$(document).ready(function() {
// Your code goes here..
myFunction();
});
It doesn't work?
$(function(){
getDetails();
});
$(document).ready(function() {
getDetails();
});
will work for sure.

Removing HTML code from a javaScript array?

Hi I have the following code in a javaScript file called songs:
var marchMD = new Array();
marchMD[0] = ["Save the Best for Last - Vanessa Williams"];
marchMD[1] = ["Informer - Snow"];
marchMD[2] = ["The Sign - Ace of Base"];
for (var i=0;i<marchMD.length; i++) {
songList = songList + '<p>' + marchMD[i] + '</p>';
}
$('#songs').html(songList);
Once this has been loaded, the follow javaScript in the file youtube reacts with the code above:
$(document).ready(function() {
$('#songs p').click(function(e) {
var $el = $(e.currentTarget);
var search = $el.html();
//alert(search);
//return;
var keyword = encodeURIComponent(search);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type:"GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i, data) {
var video_id = data.id;
var video_frame = "<iframe width='420' height='315' src='http://www.youtube.com/embed/" + video_id + "' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").hmtl("<div id='no'> No Video</div>");
}
}
});
});
});
The alert that I have in the code above was a test to see if it would return anything and it doesn't. However, if I remove the href html tag from the code this works. The reason I have it is so when someone clicks one of the songs, it takes them to the top of the page to view that song in youtube.
Thanks
If you know that the element that contains your link will only ever contain your link, you could use text() to strip out the HTML formatting, like this:
var search = $el.text();
When you have the <a> in there, var search = $el.html(); includes the tag as well, not just the text. Try this:
$('#songs p').click(function(e) {
var search = $(this).find('a').html();

Categories

Resources