Im trying to fill a select with elements from a database using Ajax but it wont work.
If have pinned down the problem to the javascript function but I don't seem to find the problem myself.
What am I missing here? :/
$(document).ready(function()
{
$(function()
{
$.ajax(
{
url:"<?php echo site_url("c_admin/ajaxCategorie");?>",
type: 'POST',
success: function(msg)
{
var jsonMsg = $.parseJSON(msg);
var count = Object.keys(jsonMsg).length;
for(var x = 0; x < count; x++)
{
$("#categorieSelect").apend($("<option></option>").val(jsonMsg[x].CategorieID).html(jsonMsg[x].CategorieNaam));
}
}
});
});
})
It seems to me you made a simple typo;
$("#categorieSelect").apend($("<option></option>").val(jsonMsg[x].CategorieID).html(jsonMsg[x].CategorieNaam));
Change apend to append.
Your code should be ok !
Related
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.
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();
}
})
})();
});
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;
...
});
I am using Brad Birdsall's Swipe.js plugin as a touch friendly, library agnostic plugin for a slider in my current mobile project. When I populate the slider on page load, everything works great. However if I try and populate the slider with $.ajax() on click, the slider will receive all of the slides, but is not responsive to touch events, or any of the methods associated with the slider.
The general slider HTML structure looks like this:
<div id="slider" class="swipe">
<ul>
<li style='display:block;'>
<img src="/someImageUrl.jpg" />
</li>
<li style='display:none;'>
<img src="/someImageUrl.jpg" />
</li>
</ul>
</div><!-- .swipe -->
<nav>
PREV
NEXT
</nav>
I am using an $.ajax() response to populate the <li><img src="..." /></li> on a click event handler in my doc.
Here's my JS:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var swipeSlides = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length <= 1) {
list += "<img src="+photoArray[i]+" />"
} else {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
$.getScript('../assets/js/swipe.js');
var slider = new Swipe(
document.getElementById('slider')
);
};
};
} // end success function
}); // end AJAX
This will sucessfully populate my page with all of the necessary content, but when I click one of the previous or next puttons, I get this error in my console:
Uncaught TypeError: Object #<HTMLCollection> has no method 'next'
Which tells me that my script is not being loaded into the page appropriately, or, my slider is not being instantiated at the proper time.
I have tried executing my code inside of the $.getScript() method like this:
$.getScript('../assets/js/swipe.js', function(data, textStatus, jqxhr) {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
var slider = new Swipe(
document.getElementById('slider')
);
});
Or even just using a good old fashioned <script src="/assets/js/swipe.js"></script> before my jQuery script executes, and I keep getting the same exact error.
If anyone has any suggestions I will be forever grateful.
I figured out the problem.
In order to make the instantiation of the Swipe element recognized, I needed to use $.globalEval() inside of the $.getScript() function.
Heres my working code:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var list = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length === 1) {
list += "<img class='noPhoto' src="+photoArray[i]+" />";
var parent = $(self).parent().find("#data");
parent.find("table, .noPhoto").remove();
parent.append(list);
} else {
list += "<div id=\"slider\" class=\"swipe\"><ul>";
for (i = 0; i < photoArray.length; i++) {
list += "<li><img src='"+photoArray[i]+"' /></li>"
}
list += "</ul><nav>PREVNEXT</nav></div>";
var parent = $(self).parent().find("#data");
parent.find("table, div").remove();
parent.append(list);
$.getScript("../assets/js/swipe.js", function(data, textStatus, jqxhr) {
$.globalEval("var slider = new Swipe(document.getElementById('slider'));")
});
};
};
} // end success function
}); // end AJAX
Hopefully this helps someone else down the road.
Why use getScript in the first place? Append it to your other javascript files as (before your javascript file), then new Swipe() should work.
Also, if you want to call functions of your Swipe object later, you should declare the var outside your ajax function. Example:
var mySwipe;
document.ready(function(){
//...
});
function pullFromAjaxFunction() {
//... do some more stuff
mySwipe = new Swipe(...)
}
I've looked over a lot of 'similar' q&a threads on SO but to be honest, as I don't have too much of a grip on js programming, I'm finding it difficult to make sense of a lot of the answers (as far as they may apply to my own situation).
The context is this, I have two php scripts one returning a list of customer_ids (json encoded) for a set period and the other returning their preferences for news feeds (json encoded).
I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery:
$('document').ready(function() {
$.ajax({
type:'GET', url: 'cust_selection.php', data: '',
succes:function(cstmrid) {
var clistlen = cstmrid.length;
var i=0;
var cstmr;
for( ;cstmr=cstmrid[i++]; ) {
$('#adminPanel>ul>li').append("<a href='' onclick='alert("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>"); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType:'json'
});
var cstmrid = "483972258"; //hardcoded for testing purposes
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(npfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
});
Now from the first ajax function, I get a list of links which I want to be able to click to launch the second ajax function and pass it the customer id so that it can grab a list of the news sources that they've configured for their pages.
The alert and the hard-coded customer id both suggest that the functions are 'working', but when I try and adjust the first function so that:
...
$('#adminPanel>ul>li').append("<a href='' onclick='getCustomerNP("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>");
... is calling a modified version of the second function, as below:
...
function getCustomerNP(cstmrid) {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(nprfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
}
Everything seems to just fail at this point. The second function doesn't seem to 'receive' the variable and I'm not sure if it's something elementary that I've overlooked (like some muddled up " and ' placements) or if what I am trying to accomplish is actually not the way jQuery ajax functions interact with each other.
As you can see, I've cannibalised bits of code and ideas from many SO q&a threads, but copying without much of an understanding makes for a frustratingly dependent life.
I would appreciate as much - expansive - comment as you can provide, as well as a solution or two (naturally).
EDIT: Not to confuse anyone further, I've been modifying the above and correcting my (many) errors and typos along the way. At present, the code looks like below:
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmr) {
alert(cstmr);
}
});
You've got a typo in the $.ajax() success function within getCustomerNP(). The function declaration:
success:function(nprfdata) {
... has a parameter nprfdata, but then within the function you use npfdata (missing the r).
Also this code:
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
...declares and sets variable news that you never use. And it doesn't seem right to increment n in the for test expression but then use n within the loop. You never set item to anything but you use it in your .append().
(Note also that JS doesn't have block scope, only function scope, so declaring variables inside an if or for loop doesn't limit them to that if or for block.)
I would not create inline onclick handlers like that. I'd probably do something more like this:
$('#adminPanel>ul>li').append("<a href='' data-cstmr='"+cstmr+"' class='lst_admin basic'>"+cstmr+"</a>");
...and then within the document ready setup a delegated event handler to catch the clicks on those anchors:
$('#adminPanel>ul>li').on('click', 'a.lst_admin', function() {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+ $(this).attr('data-cstmr'),
success:function(npfdata) {
var item,
n=0,
// cache the jQuery object rather than reselecting on every iteration
$table = $('#adminMain>table>tbody');
// increment n only after the current iteration of the loop
for( ;item=npfdata[n]; n++) {
// change to use item
$table.append("<tr><td>"+item.nsource+"</td></tr>");
}
},
dataType:'json'
});
});
As you append your like with <a href='' onclick='getCustomerNP("+cstmr+")', Make sure you can access the function getCustomerNP.
Try to define getCustomerNP as
window.getCustomerNP = function(cstmrid) {
...
If you defined it in the $(document).ready(function(){ ... }) block, try this
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmrid) {
$.ajax({
type: 'GET', url: 'newsfpref.php?', data: 'cref=' + cstmrid,
success: function (nprfdata) {
var item;
var n = 0;
for (; item = npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>" + item + "</td></tr>");
}
},
dataType: 'json'
});
}
});