How to get data from button attributes? - javascript

There are several buttons (they creates dynamically)
<button class="common" id="1.1" status="sale" oncontextmenu="rightButton('1.1'); return false" onclick="addOptions('1.1')" number="1">1</button>
I need to get attributes (class, id, status, number) and insert them into object array. Then input to database.
function saveScheme()
{
var table = document.getElementById('schemeTable');
var elements = table.getElementsByTagName('button');
var arrayIdButtons = {};
for(var i = 0; i<elements.length; i++)
{
arrayIdButtons[i] = {};
for(var j = 0; j<4; j++)
{
arrayIdButtons[i]["coord"] = elements.item([i]).id;
arrayIdButtons[i]["status"] = elements.item([i]).status;
arrayIdButtons[i]["type"] = elements.item([i]).class;
arrayIdButtons[i]["number"] = elements.item([i]).number;
}
}
console.log(arrayIdButtons);
var data='data=' + JSON.stringify(arrayIdButtons,"", 2);
$.ajax({
type: 'POST',
url: "handler.php",
data: data,
cache: false,
data: data,
success: function(data) {
alert(data)
}
});
}
result of this code(console.log(arrayIdButtons);):

Since you're already using jQuery, you can access the attributes of an element using .attr(). For example:
$('.common').attr('number');
Or, without jQuery,
elements[i].getAttribute('number');

Use HTML5 API data
<button class="common" id="1.1" data-status="sale" oncontextmenu="rightButton('1.1'); .....</button>
So,
elements.item([i]).data('status'); //if jquery enabled

You can try this html. then,
<button class="common" data-id="1.1" data-status="sale" data-number="1">1</button>
If DOM is not loaded, then you can get this by
$(document).ready(function(){
$(".common").on("click",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
});
And if DOM is already loaded you can get them by
$(document).on("click",".common",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
Then you can push this is an array. Note - this will give you the attributes of only the button was clicked

Related

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

Append some items to a div, and the rest to another div in jQuery

I'm writing a script to parse a JSON file, and I seem to have got myself into a tricky situation. Can I append half of the returned items in one div element and the other half in another div elemet?
Here is the original markup:
<div class="feed"><div class="displayfeed main"></div></div>
<div class="feed"><div class="displayfeed second"></div></div>
I want the page to display like this after appending the returned data:
<div class="feed">
<div class="displayfeed main">
<h3>item1's title</h3> //Half of the items in "div.main"
.......
</div>
</div>
<div class="feed">
<div class="displayfeed second">
<h3>item2's title</h3> //Half of the items in "div.second"
...........
</div>
</div>
JS Code:
$.ajax({
url: source,
success: function (data) {
var item_html =
$(data.items).each(function (index, item) {
'<h3>'+item.title+'</h3>';
});
//Any way to append some of them in ('.main') and the rest in ('.second')?
$('.displayfeed').append(item_html);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I'm looking for any possible suggestions, otherwise I have no choice but to parse the same feed twice. Any help would be appreciated.
Updated:
I've set up a FIDDLE using Gogole news feed in JSON format converted by YQL as an example
Use multiply selector.
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I don't know what structure you have but you can try this:
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
var count = data.count;
var half = count/2;
var counter = 0;
for(item in data) {
if(counter < half) {
item_html_main += item;
} else {
item_html_secodn += item;
}
counter++;
}
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
You can try something like this. if it does not matter which posts is displayed in which container
$.ajax({
url: "<your-URL>",
success: function (data) {
var length = 0;
var items = data.query.results.item;
items = items.map(function(item){
return '<h3>'+item.title+'</h3>';
});
var half = items.length/2;
for(var i = 0; i < items.length; i++)
if(i < half)
$('.main').append(items[i]);
else
$('.second').append(items[i]);
length++;
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
Of course, but you need some separator or something
You can append all to your first div and then copy the part you want in the second div out of the first.
Example
item_html
<h2>Headline</h2>
<span>
News Text
</span>
js
$('.displayfeed').append(item_html);
sec = $('.displayfeed').find('span').html();
$('.displayfeed').find('span').remove();
$('.displayfeed second').append(sec);

Getting wrong Form Data name when posting

I am trying to pass multiple parameters to a javascript function. When reviewing the post data I get incorrect data names.
HTML:
//Test function with button (HTML)
<button onClick='printList("projects",{"qid":1,"oid":3),getSampleEntity);'>Test getSampleEntity</button>
Javascript:
var getSampleEntity = function(oid, qid) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat_Organism.php',
type: 'POST',
data: { 'organismID': oid, 'quadratID': qid },
dataType: dataType
});
}
....
var printList = function(lid,options,get) {
var items = get(options);
var list = $("ul#"+lid);
list.empty();
items.success(function(data){
$.each(data, function(item,details) {
var ul = $('<ul/>');
ul.attr('id', lid+'_'+details.ID);
var li = $('<li/>')
.text(details.ID)
.appendTo(list);
ul.appendTo(list);
$.each(details,function(key,value) {
var li = $('<li/>')
.text(key+': '+value)
.appendTo(ul);
});
});
});
}
The resulting post data:
organismID[qid]:1
organismID[oid]:3
I see what is happening, but my question is how do I pass multiple parameters in to my printList() so that those parameters will be passed effectively to getSapleEntity()?
Try
var items = get(options.oid, options.qid);

Categories

Resources