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.
Related
I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});
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
I have a little problem here. ¿How i can manipulate a dynamically generated html, in Jquery?
I have a function like:
generatesomething : function(DestinationID,data){
result = $.DoSomething(data)
$('#'+Destinationid).html(data);
}
The script, in other point, receive through ajax an array. Naturally, I will iterate the array like:
$.each(response, function(key, value){
ThisHtml = '<div id="div'+key'"></div>';
$('#MyPlaceHolderDiv').html(ThisHTML)
//In this point, i really need to call my first function
$.generatesomething('div'+key',data)
//But not works!!!!
}
How i can manipulated the generated div using my function?
Thanks in advance!
Edit: in a try to clarify my question, i will paste the exact functions.
I made this function. Please do not laugh at my code, I am newbie in jquery.
jQuery.fn.extend({
/funciones Generales/
piegraph : function(GraficoDestino,tipo,arrayDatos,dato1,dato2,tooltiptemplate,labeltemplate){
var dataPoints = [];
$.each(arrayDatos, function(key, value){
var temporal = {};
temporal.label = value[dato1];
temporal.y = parseInt(value[dato2]);
dataPoints.push(temporal);
});
var opciones = {
animationEnabled : true,
data : [{
type : tipo,
startAngle : 0,
toolTipContent : tooltiptemplate,
indexLabel : labeltemplate,
dataPoints : dataPoints,
}]
};
$('#' + GraficoDestino).CanvasJSChart(opciones);
}
This function works pretty well... if i can give it the destination div to it.
In other part of my script, i have a ajax call:
Generadisco: function(){
var datos = {
"accion":"generadisco"
};
$.ajax({
type: "POST",
url: "blahblah.php",
data: datos,
dataType: "json",
success:function(response){
$.each(response, function(key, value){
esteHTML = '<div id="divdisco'+key+'"></div>
$('#discosplace').append(estehtml);
//the div is generated... but when i do...:
$(this).piegraph('divdisco'+key,'pie', response[3],0,1, "{label} #percent%","{label} ");
//nothing happens
});
}
});
}
I found some error in your code:
$('#MyPlaceHolderDiv').html(ThisHTML)
$.generatesomething('div'+ key ,data)
must to be:
$('#MyPlaceHolderDiv').html(ThisHTML);
$.generatesomething('div'+key',data);
Also try to add console.log(DestinationID) in first line of your function to see passed argument (DestinationID)
If you are generating the dynamic elements after your ajax call, try using async:false.
$.ajax({
url: "abcd.html",
async:false
}).then(function())
I have to pass some result string to the view after sucessful ajax post. At the moment my js is placed in the view and the callback function creates a resultstring and then posts it to the results div. Since I have some blade syntax in the string that is being generated by the callback function it works until I leave the js in the blade.php view file, if I put the javascript in public/js/some.js blade doesn't parse that syntax and the result is the view is rendered with the syntax instead of data. So I was thinking: Can I put the sting in a separate view/js/result.blade.php and in the jquery function do somtehing like:
var resultStr = (content of view/js/result.blade.php)
for(var i=0; i<obj.length; i++){
resultStr
};
$("#results").html(resultStr);
If so, how do I load the external file into partialstring?
My guess is that as it's a blade file it will be parsed.
#c-smile tried this code but is not working, the file is opened but then the view doesn't get the data
jQuery(function ($) {
$(document).ready(function () {
var form = $('form');
form.submit(function (e) {
e.preventDefault();
$.get("js/blade/filler.blade.php", function (data) {
var resultStr = data;
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function (data) {
var obj = (data);
for (var i = 0; i < obj.length; i++) {
resultStr;
}
$("#results").html(resultStr);
}
});
});
});
});
});
That's subject of AJAX functionality.
With jQuery you would do it as:
$.get( "view/js/result.blade.php", function( data ) {
var resultStr = data;
...
});
function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"+json.province_info[i].province_id+"' value='Delete' /></td><td>"+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
$(":input").click(function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});
}//end loadProvinces
i have called loadprovinces function when user add a province for a particular country
as user adds a province it inserts into a province table so it is working , a problem is that loadProvinces function is not calling when user presses a delete button .
As you are adding delete button dynamically then you shuld use .on to bind click event. Also keep this bind click event code outside function :
function loadProvinces(data){
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i=0; i<json.province_info.length; i++){
province += "<tr><td><input type='button' id='"
+json.province_info[i].province_id
+"' value='Delete' /></td><td>"
+json.province_info[i].province_name+"</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}//end loadProvinces
// bind click event for dynamically generated element
$(document).on("click",":input",function(e) {
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url,{"getProvince" : "delete_province","province_id":""+id},
function(data){
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});
There is syntax error. Not sure if it is the main Problem, but it can not works without this.
Have you checked console? F12
function(data){ miss }
Why don't you just do it this way:
function loadProvinces (data) {
var province = "<tr><th>Options</th><th>Province</th></tr>";
var json = $.parseJSON(data);
for(var i = 0; i < json.province_info.length; i++){
province += "<tr><td><input type='button' id='" + json.province_info[i].province_id + "' value='Delete' /></td><td>" + json.province_info[i].province_name + "</td></tr>";
}
$("#appendprovince").empty();
$("#appendprovince").append(province);
$("#appendprovince").show();
}
;//end loadProvinces
$(":input").click(function (e) { // it would be nice to add some more identifiers e.g. class to fire only when needed
var id = this.id;
var url = "http://localhost:8080/CurdServlet/ProvinceServlet";
$.post(url, {"getProvince": "delete_province", "province_id": "" + id},
function (data) {
alert(data); // its working and shows data successfully
loadProvinces(data); // here loadProvinces function not working only
});
});