I want to put the ajax call in outside jsp and call it in the JS file .. here is my code
deleteRow : function() {
$("input:checkbox:checked").each(bindContext(function(index, item) {
var str = $(item).attr("id");
str = str.substring(str.indexOf("_") + 1);
var id = this.data[str][this.columns[1]];
$.ajax({
url : '/Spring3HibernateApp1/deleteDep',
type : 'GET',
data : {
"id" : id,
},
dataType : "json"
});
So what if I want to just put the ajax call in function in another jsp ??
Related
I am trying to get JSON out of my Rest API and want to use this JSON information to show them on my application.
Is the function renderUserState ever called? Because the rest of my Code should work fine.
function testSubmit() {
var card = getQueryVariable("select_card");
var action = getQueryVariable("select_action");
var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
$.ajax({
type : 'GET',
url : urlGet,
dataType : 'json',
encode : true
}).done(renderUserState);
}
function renderUserState(userState){
$("#gold").text(userState.goldAmount);
}
Thanks for your help!
Yup, your code is correct you just need to call a function in the done since the done will receive the data returned by your endpoint.
Hope this will help you click on the button and see the log.
function testSubmit() {
// var card = getQueryVariable("select_card");
// var action = getQueryVariable("select_action");
// var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
var urlGetTest = "https://jsonplaceholder.typicode.com/posts";
$.ajax({
type : 'GET',
url : urlGetTest,
dataType : 'json',
encode : true
}).done((userState) => {
renderUserState(userState);
});
}
function renderUserState(userState){
console.log(userState);
// $("#gold").text(userState.goldAmount);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="testSubmit();">Click Here</button>
I am trying to use json_encode so that my jquery ajax function can retrieve data from my php script however the array I am attempting to encode and retrieve is an array of objects
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo);
I am trying to retrieve this using the jquery ajax function
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data["uinf_desc"][0]);
},
error : function(log) {
console.log(log.message);
}
});
I am getting the following error
Uncaught TypeError: Cannot read property '0' of undefined
I can't tell if it's going wrong in the php code or the jquery code, what is the correct way to retrieve an array of objects?
Change your PHP to:
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo); //$la_uselessinfo is already an array, no need to wrap it again, and doing so causes you to misjudge the depth of your array
Then change your jQuery to :
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data[0]["uinf_desc"]); // this line changed
},
error : function(log) {
console.log(log.message);
}
});
To loop over your results do this:
// sample data
var data = [{
"uinf_idno": "1",
"uinf_desc": "website db "
}, {
"uinf_idno": "2",
"uinf_desc": "local apache "
}]
$.each(data,function(i,e){
var uinf_idno = e.uinf_idno;
var uinf_desc = e.uinf_desc;
$('#result').append('uinf_idno= '+uinf_idno+' and uinf_desc= '+uinf_desc+' <br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
dataType: "json",
success : function(data) {
console.log(data[0]["uinf_desc"]);
console.log(data[0]["uinf_desc"]);
},
It should be data[0]["uinf_desc"] as written in your PHP
I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}
I am new to jQuery.
I have to reload a div after sending some values to server using ajax.
My jQuery code is
selectionChanged: function () {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var columnname = record.columnname;
var datatype = record.datatype;
var columnlength = record.columnlength;
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
});
after this code is executed I want to reload a div
<div id="loadedtablecontainer"></div>
this div will get the selected data of 1st jtable .. and display it in this jtable.
So by using this div id I have to call or reload this div soon after above jQuery function got executed
Something like
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
$("#loadedtablecontainer");
So I am assuming the Ajax call returns the new content, so set the html() in the callback.
$.post('meta?action=dataload',
{
columnname : columnname,
datatype:datatype,
columnlength:columnlength
},
function (data) {
$( "#loadedtablecontainer" ).html(data);
}
);
You have a callback parameter which returns your result from post. Use that to manipulate the data and form the HTML. Then simply append it
$.post('meta?action=dataload', {
columnname : columnname, datatype:datatype,columnlength:columnlength
},
function (result) {
// make your manipulations here, (Ex: var manipulatedHTML )
$("#loadedtablecontainer" ).append(manipulatedHTML );
}
);
If its a json
function(result) {
//result is your json
var manipulatedHTML = '<div class="result">'+result.value"+'</div>';
}
$("#loadedtablecontainer" ).append(manipulatedHTML )
Use a for loop if its a json array
function loadCustomerCorpPopup(id) {
$("#eBody").mask("${loading}");
$.ajax({
url : '${url}/customer/ajax_customer_corporate_popup',
data : {
customerCorporateId : id,
},
dataType : 'text',
cache : false,
success : function(data) {
$('#popupId').html(data);
$('#popupId').modal('show');
$("#eBody").unmask("${loading}");
}
});
}
You can use this way $('#popupId').html(data);
data can a html code or url.
I have next select2:
siteSelector = $('#siteSelector').select2(
{
placeholder : "Select site ...",
ajax : {
type : 'GET',
dataType : 'json',
contentType : 'application/json',
url : {url_of_my_rest_service},
data : function(term, page) {
return {
startswith : term,
};
},
results : function(data, page) {
var items = data.content;
var res = {
results : []
}, i;
for (i = 0; i < items.length; i++) {
res.results.push({
id : items[i].id,
text : items[i].name
});
}
return res;
}
},
minimumInputLength : 3
});
How can I make that when I press a dropdown button some values will already be preloaded in there?
The best way to do it is to insert the data in the DOM before calling the ajax.
$(document).ready(function () {
//as many as you need, using loop or manually
$('#siteSelector').append("<option value='value1'>Value 1</option>")
//only then start select2 using the function you wrote
//siteSelector = $('#siteSelector').select2(......
})
As far as I know, the data attribute in select2 doesn't work well (or at all) with ajax calls. This method will work.