Save userId in sessionStorage giving error? - javascript

I want to store the variable "clients[i]._id" and send it to another page when I click the button in the for loop.I want to later use that id to get more specific information about that client on its seperate window.
Im getting an undefined error where clients is undefined. Also the console.log in the store(function) doesnt work. Can you find whats wrong?
let thisArray = [];
//let clientId = $('#clientId').val();
$.ajax({
method: 'GET',
url: '/auth/clientsGET',
dataType: 'json',
success: function(clients) {
thisArray = clients
buildTable(thisArray);
console.log(thisArray);
}
})
function buildTable(clients) {
let table = document.getElementById('tabelaClientesAdmin')
for (let i = 0; i < clients.length; i++) {
let row = `<tr>
<td>${clients[i]._id}</td>
<td>${clients[i].name}</td>
<td>${clients[i].admin}</td>
<td><button type="button" class="btn btn-primary" onclick="store()">Ver Cliente</button></td>
</tr>`
table.innerHTML += row
}
}
function store() {
console.log("Trying to get clientId....")
let clientId = clients._id;
sessionStorage.setItem("clientId", clientId);
location.href = "./ver_cliente";
}
I'll update straight away when information is needed.

You could pass the index like that:
onclick="store(${i})"
then retrieve it like that:
function store(index) {
const clientId = thisArray[index]._id;
sessionStorage.setItem("clientId", clientId);
}

Here is a slightly modified but working example of your page:
The most important part is probably:
let clientId=+ev.target.closest("tr").children[0].textContent;
where I navigate from the clicked button (ev.target) via the parent-<tr> to the first child (a <td>). There I read the textContent, convert it into an integer with the unary +-operator and store it in variable clientId.
I also introduced the global variable clients that could be used for further reference in the page. But currently this array not really used anywhere.
var clients
$.ajax({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/users',
dataType: 'json',
success: function(d) {
clients = d
buildTable(clients);
console.log(clients);
}
})
function buildTable(clients) {
let table = document.getElementById('tabelaClientesAdmin')
for (let i = 0; i < clients.length; i++) {
let row = `<tr>
<td>${clients[i].id}</td>
<td>${clients[i].name}</td>
<td>${clients[i].username}</td>
<td><button class="btn btn-primary">Ver Cliente</button></td>
</tr>`
table.innerHTML += row
}
}
document.body.onclick=function(ev) {
if (ev.target.tagName==="BUTTON") {
let clientId=+ev.target.closest("tr").children[0].textContent;
console.log("Trying to get clientId:",clientId);
// sessionStorage.setItem("clientId", clientId); // not in SO snippets
console.log("go to ./ver_cliente");
}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tabelaClientesAdmin"></table>

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)

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

How to pass multiple variables from ajax to function in javascript?

How can I pass 2 variables from ajax to function ?
I can successfully pass 1 variable, but I don't know how to write the code to pass 2 variables. I'm stuck here:
<button id ="+data[i].id+" onclick='tahu("+data[i].id+","+data[i].nama+")'>Detail</button>
Here is my function
function tahu(x, y) {
window.alert(x);
window.alert(y);
}
Here is my full ajax code
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
data_table +="<tr><td>"+data[i].id+"</td><td>"+data[i].nama+"</td><td>"+"<button id ="+data[i].id+","+data[i].nama+" onclick='tahu("+data[i].id+")'>Detail</button>"+"</td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
Ok, I've tried to solve your problem but without actually doing a json request so bear with me. Firstly, You are already using jquery for your ajax call so why not leverage jquery for your DOM manipulation as well? I have written your function to store the id and nama as attributes on the button element and instead of having an inline function call, I have written a click event handler in jquery to execute any time a button (with class detailButton) is clicked. This function will grab the data-id and data-name from the button itself and should display the information you want, specific to that button.
The final button element:
<button data-id ="id" data-name="nama" class="detailButton">Detail</button>
and the jquery:
//ajax request
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
var id = data[i].id;
var nama = data[i].nama;
data_table +="<tr>";
data_table +="<td>"+id+"</td>";
data_table += "<td>"+nama+"</td>";
data_table += "<button data-id ="+id+" data-nama="+nama+" class="detailButton">Detail</button>";
data_table += "<td></td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
//click event handler
$('.detailButton').click(function() {
var id = $(this).data('id')
var nama = $(this).data('nama');
alert(id);
alert(name);
});
I took the liberty of expanding your data_table concatenation into multiple lines for ease of reading. Hope this is closer to your final solution.

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

Passing arrays js variable to php

Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.
First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}

Categories

Resources