With the code below I am trying to update PartialView's HTML.
open_Modal_AssignAmendRoles = function (url) {
$.ajax({
url: url,//PartialView URL
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
var modalhtml = data;
var result = datafetchfunction("action URL", )
if (result.compleate == true) {
result.data.employeeroles.forEach(function (roletype) {
var tagbox = $(modalhtml).find("#tagbox" + roletype.clientroletypeid);
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
var roletypeid = roletype.clientroletypeid
roletype.roles.forEach(function (role) {
var roleid = role.FK_ClientRoleID
var roledescription = role.ClientRole_Description;
var rolecode = role.ClientRole_Code
var markup = ""
markup += " <li class='taglist' id='" + roleid + "'>"
markup += " <button onclick='$(this).parent().remove()' class='tagclose'>"
markup += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>"
markup += " </button>"
markup += " <a class='assignedrole' href='Javascript:void(0);' onclick='pop_click_fn(this)'"
markup += " role-id='" + roleid + "' role-type-id=" + roletypeid + ""
markup += " data-toggle='popover' data-trigger='hover' data-content='" + roledescription + "' data-placement='top' > " + rolecode + " </a>"
markup += " </li>";
$(span).append(markup)
})
})
openModal( modalhtml);
}
}
});
}
Step 1:
On button click the open_Modal_AssignAmendRoles() function is called. Then it goes to the success() function.
Step 2:
var result = datafetchfunction("action URL" )
this fetch data as JSON format
Step 3:
Then I start some loop, I already create some spans and find them with
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
Step 4:
then I build a markup and assign this
$(span).append(markup)
and finally, call
openModal( modalhtml);
But modalhtml is not updated as expected, it means lis which I created with loop is not added.
Can someone tell me what is the problem and how to solve this?
Related
i have a page with clickable divs that has been populated dynamically with Json. The divs contains list of items, and when i click on a specific one, i get a new page that contains the name and details of the clicked item.
My issue is that i can't figure out how to display the label (name) of the item cliked, if you can give some help. Many thanks !
Here is my JSON array:
$data['dataHeader'] = array('id', 'Name', 'Value');
$data['dataJson'] = array(
array('id1', 'Jeans', 'blablablabla'),
array('id2', 'Leather Jacket', 'some random description'),
array('id3', 'Suede Boots', 'description of boots')
);
Here is what i tried to do :
(function( $ ) {
// Plugin to clickable element
$.fn.infoClickable = function() {
this.each(function() {
// get the object
var elm = $( this );
// Define click event
elm.on("click", function(){
//Get info relative to clicked element
var currentPage = elm.data("page");
loadPage_X_Content(elm);
});
});
}
// Load page 1
loadPage1Content();
// Application du plug-in
$('.clickableDiv').infoClickable();
}( jQuery ));
function loadPage_X_Content(elm){
var nextPage = currentPage + 1;
var nextPageName = '#LV' + nextPage +'Content';
arrayOfData = reponseData;
currentValue = arrayOfData;
var elm = $( this );
var elmID = elm.attr("id");
var PageContent = '';
PageContent += '<div>' + elmID + '</div>';
$.ajax({
url : "Pages/index.php",
type: 'GET',
dataType: 'json',
data: 'action=loadPage' + '&ID=' + elmID,
success: function(reponseData) {
For header :
LVContent += '<div class="HeaderLine">';
$.each(arrayOfData['dataHeader'], function(currentIdx, currentValue)
{
if (currentIdx > 0) PageContent += '<div class="' + arrayOfData[currentIdx] + '">'+ currentValue +'</div>';
});
For data :
$.each(arrayOfData['dataJson'], function(currentIdx, currentValue){
PageContent += '<div class="BlocLine clickableDiv" ';
PageContent += ' id="' + currentIdx + "_" + currentContext + '"';
PageContent += ' >';
// columns
$.each(currentValue, function(currentIdx, currentValueCol){
if (currentIdx > 0){
PageContent += '<div class=" '+ arrayOfData[currentIdx] +' "';
PageContent += ' >'+ currentValueCol +'</div>';
}
});
PageContent += '</div>';
});
$(nextPageName).append(PageContent);
$(nextPageName).find('.clickableDiv').infoClickable();
});
The code included does not specify what elm is.
So just to clarify, is your elm:
var elm = document.getElementById('theAttrDivId');
?
Also you're asking for the name but searching for the ID, so make sure it's:
var elmID = elm.attr("name");
I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
I have a page that uses a couple of AJAX calls to get and update data. A user enters a product number in an input box, then clicks a <button>, which runs a function that has a jQuery AJAX call to populate a div. See below.
HTML
<form rol="form">
<div class="form-group">
<label for="sku" id="sku-label">Please enter the SKU below</label>
<input class="form-control text-center" type="input" id="sku">
<button class="btn btn-primary col-md-12" type="button" id="bClick" onclick="getSku( $( '#sku' ).val() );">Get SKUs</button>
</div>
<input type="hidden" id="badgeNum" value="<?php echo $_SESSION['BADGE_NUMBER']; ?>">
</form>
<div class="col-md-12" id="sku-results"><!--This div gets populated. -->
</div>
jQuery
function getSku(sSku) {
//AJAX call to get SKUs goes here.
$.ajax({
type: 'POST',
url: 'sku-query.php',
async: false,
mimeType: 'json',
//dataType: 'application/json',
data: {sku: sSku},
success: function(data) {
var disp = "";
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2'><strong>SKU</strong></div>";
disp += "<div class='col-md-3'><strong>Description</strong></div>";
disp += "<div class='col-md-2'><strong>Master</strong></div>";
disp += "<div class='col-md-2'><strong>Daughter</strong></div>";
disp += "<div class='col-md-2 text-center'><strong>Location</strong></div>";
disp += "<div class='col-md-1 text-center'><strong>Update</strong></div>";
disp += "</div>";
counterp = 0;
$.each(data, function(i, data) {
disp += "<div class='col-md-12' id='skuDisplay'>";
disp += "<div class='col-md-2' id='dSku' >" + data[0] + "</div>";
disp += "<div class='col-md-3' id='dDesc'>" + data[1] + "</div>";
disp += "<div class='col-md-2' id='dMast'>" + data[2] + "</div>";
disp += "<div class='col-md-2 text-center' id='dDaughter'>";
disp += "<input class='col-md-6 text-center' type='number' value='"+ data[3] + "' id='dChange'>";
disp += "</div>";
disp += "<input type='hidden' id='oldQty' value='" + data[3] + "'>";
disp += "<div class='col-md-2 text-center' id='dLoc'>" + data[4] + "</div>";
disp += "<div class='col-md-1 text-center'><a class='inv-click' id='" + counterp + "' onclick='updateDaughter(this.id)' value='" + counterp + "'><i class='fa fa-check-square-o'></i></a></div>";
disp += "</div>";
counterp = counterp + 1;
});
//Success function if all goes well.
$( "#sku-results" ).empty();
$( "#sku-results" ).append( disp );
},
error: function() {
alert('There seems to be an error fetching SKUs.');
}
});
}
So the above code works fine. In each div that is appended to the page, there is an <a> element. The purpose of these divs being added is that each div has an input box where the user can change a value. When the value is changed and the a element is clicked, another function, with another AJAX call is run. When the second AJAX call in this function is done running, I need to then run the first function AGAIN to update the page with the updated value. See the second function below.
function updateDaughter(getId)
{
var master = $( "#" + getId ).closest("#skuDisplay").children("#dMast").html();
var daughter = $( "#" + getId ).closest("#skuDisplay").children("#dDaughter").children("#dChange").val();
var loc = $( "#" + getId ).closest("#skuDisplay").children("#dLoc").html();
var oldQty = $( "#" + getId ).closest("#skuDisplay").children("#oldQty").val();
var emp_id = $( "#badgeNum" ).val();
var sku = $( "#" + getId ).closest("#skuDisplay").children("#dSku").html();
var dDate = new Date();
var dDay = ("0" + dDate.getDate() ).slice(-2);
var dMonth = ("0" + dDate.getMonth()).slice(-2);
var dYear = dDate.getFullYear();
var dHour = ("0" + dDate.getHours() ).slice(-2);
var dMin = ("0" + dDate.getMinutes()).slice(-2);
var dSec = ("0" + dDate.getSeconds()).slice(-2);
var dFullDate = dYear + "-" + dMonth + "-" + dDay;
var dFullTime = dHour + ":" + dMin + ":" + dSec;
var dAllDate = dFullDate + " " + dFullTime;
var move_from = "Adjustment";
//var created = date('Y-m-d h:i:s');
var worktype = "Reslot";
var qty = daughter - oldQty;
alert("DATE:" + dAllDate + ". SKU:" + sku + ". MASTER:" + master + ". LOC:" + loc + ". DAUGHTER:" + daughter + ". OLD:" + oldQty + ". EMPID:" + emp_id + ". QTY:" + qty + ". MOVEFROM:" + move_from + ". TYPE:" + worktype);
var workTypeId = "";
if (worktype = 'Putaway') {workTypeId = 1;}
if (worktype = 'RTI') {workTypeId = 2;}
if (worktype = 'Replen') {workTypeId = 3;}
if (worktype = 'Manual Replen'){workTypeId = 4;}
if (worktype = 'Reslot') {workTypeId = 5;}
if (worktype = '01 Replen') {workTypeId = 6;}
if (worktype = '03 Replen') {workTypeId = 7;}
if (worktype = '02 Replen') {workTypeId = 8;}
$.ajax({
type: 'POST',
url: 'http://a/location/that/works',
async: false,
data: JSON.stringify({
workTypeID: workTypeId,
completedDate: dAllDate,
startLocation: move_from,
endLocation: loc,
quantity: qty,
assignedAdministratorID: emp_id,
createdDate: dAllDate,
startedDate: dAllDate,
createdAdministratorID: emp_id,
sku: sku
}),
contentType: 'application/json',
success: function(data) {
if(data.status == 'Success') {
$('#result').text(data.status);
} else {
$('#result').text('Failed on update: ' + data.status + ', ' + data.errorMessage);
}
},
error: function() {
$('#result').text('There might be some problem on the web service. Please contact administrator.');
}
});
$( "#bClick" ).click();
}
What's the problem?
The second function works in that it updates the corresponding database with the information that it needs to update it with. The problem is that I cannot get my page to then reload with the updated information. After I change the value and click the <a> tag, the page runs the first function again but the old value shows up. The only way I can get the new value to show up is if I click on the button with the same product number again.
Upon reading about this, I came across that AJAX will run its own process apart from the rest of your function. So in my second function, if I am calling my first function again, what looks like is happening is that my first function is being called in my second function before the AJAX call is even done.
What I tried
-I figured that I would try adding async: false to both of my jQuery AJAX functions, which did not work.
-I tried running my first function in my second function in various places. Inside of the AJAX success parameter, after the AJAX call altogether, etc... This did not work either.
-I tried to patch this by replacing the old value with the new value in the input box manually (empty() then append()) just to show the user than their changes have "updated", but even this gets overwritten by the old data (which is not even there anymore because of the second AJAX call). The AJAX call is getting "outraced" by the rest of the function, it seems.
-I tried just triggering the button to be "clicked" again inside, and after the second AJAX call by $( "#bClick" ).click();. Same thing. Didn't work.
What I need
This is what I need to happen:
-The user types a product number (works)
-The user clicks a button (works)
-The button triggers a function that runs an AJAX call to populate the page with info; each row of info has an input box with a number that can be changed, and an <a> button that will run another function. (works)
-When the <a> button is clicked, another function is run that has another AJAX call that updates a database with information, including the changed value in the input box. (works)
-Inside of the second function, after the AJAX call is run, the first function with the first AJAX call should be run again to update the page with the changed information. (does not work)
Can someone help me figure this out?
I'm trying to add a simple 'wait box' on a javascript function, like this:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working good on Firefox, but not on Internet Explorer 11, that's not showing it. The HTML is:
<div id="ctl00_Wait1_WaitBox" class="updateProgress">
Attendere...<br />
<img src="../Images/wait.gif" align="middle" />
</div>
The weirdest thing is that I try this, for a simple check:
function caricaElenco(indice) {
(...)
alert($("[id*=Wait1_WaitBox]").css('display'))
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert($("[id*=Wait1_WaitBox]").css('display'))
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working, I mean that it's showing the alert with 'none' and after 'block'... And it's showing the box too! But not without the alert... Why?
UPDATE:
Tried with [id*="Wait1_WaitBox"], but it's the same. jQuery version is 1.8.2.
With
it's working only with the alert
I mean that if I do:
function caricaElenco(indice) {
(...)
alert('whatever');
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert('whatever');
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's showing the box, but if I do:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's not working (I mean not showing the 'wait box', but doing all the other stuff the function has to do in (...) correctly—load a gridview with an AJAX call) on Internet Explorer 11, in Firefox are both working. No JavaScript error.
UPDATE 2:
Almost entire javascript function:
// Fill part of gridView
function loadList(index) {
index = parseInt(index);
buffer = 100; // Number of rows to load
$("[id*=divGrid]").unbind('scroll');
$('[id*="Wait1_WaitBox"]').show(); // Show loading 'wheel'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PageName.aspx/webMethodName",
data: '{id:' + $("[id*=hdnID]").val() + ', index:' + index + '}',
dataType: "json",
async: false,
success: function (response) {
if (index == 0) {
(...)
$("[id*=grid] tr:last-child").remove();
var row = "<tr class='" + response.d[index].State + "'>";
row += "<td class="Column1"></td>";
(...)
row += "<td class="DateColumn"></td>";
(...)
row += "<td class='columnN'></td></tr>";
$("[id*=grid]").append(row);
}
row = $("[id*=grid] tr:last-child").clone(true);
$("[id*=grid] tr:last-child").remove();
if (index <= response.d.length) {
if (index + buffer > response.d.length)
var stop = response.d.length;
else
var stop = index + buffer;
(...)
for (var i = index; i < stop; i++) {
var j = 0;
(...)
$("td", row).eq(j).html("<span id='lblCodeNumber" + i + "' >" + response.d[i].CodeNumber + "</span>"); j++;
(...)
var effectDate = new Date(parseInt(response.d[i].effectDate.substr(6)));
$("td", row).eq(j).html(effectDate.getDate() + '/' + (effectDate.getMonth() + 1) + '/' + effectDate.getFullYear()); j++;
}
(...)
var toBeCounted = "";
var checked = "";
if (response.d[i].ToBeCounted != null)
toBeCounted = response.d[i].ToBeCounted .toString();
else
toBeCounted = "true";
if (toBeCounted == "true")
checked = "checked = 'checked'";
else
checked = "";
var rdToBeCounted = "<span><input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='s' id='sToBeCounted" + i + "' />";
rdToBeCounted += "<label for='s" + i + "'>YES</label>";
if (toBeCounted == "false")
checked = "checked = 'checked'";
else
checked = "";
toBeCounted += "<input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='n' id='nToBeCounted" + i + "' />";
rdToBeCounted += "<label for='n" + i + "'>NO</label></span>";
$("td", row).eq(j).html(rdToBeCounted);
$("[id*=grid]").append(riga);
(...)
riga = $("[id*=grid] tr:last-child").clone(true);
}
if (stop < response.d.length) {
$("[id*=divGrid]").scroll(function (e) {
if (element_in_scroll(".congruenti tbody tr:last")) {
loadList($(".congruenti tbody tr:last td:last").html());
};
});
}
$('[id*="Wait1_WaitBox"]').hide();
}
},
error: function (result) {
alert("Error! " + result.status + " - " + result.statusText);
}
});
}
At the end you seem to be hiding it again $("[id*=Wait1_WaitBox]").hide();.
You need to show what goes in between these two lines.
It works with alert because the execution of the script is frozen until you close the alert (and that final line is not executed yet).
Hi All i have a quick question about JSON data into href for AJAX
I have JSON coming into AJAX example data[i].listingid
How do i put that into a href inside the ajax?
Below are my codes, it will explain the situation more clearly.
Thanks for your time
<script>
$.ajax({
type: "GET",
url: "listing.php",
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
console.log(data)
var listingid = data[i].listingid;
var myOtherUrl =
"SpecificListing.html?Listingid=" + encodeURIComponent(listingid);
var html1 = "<div class=two> Listing Address : " + data[i].address + "<a href=myOtherurl>" +
data[i].listingid + "Click to view the details" + "</div>" +
"</a>"
$('#display12').append(html1);
}
}
});
</script>
You can straightly add it with concatenation like below :
var html1 = "<div class=two> Listing Address : " + data[i].address +
"<a href='"+ myOtherurl + "'>"+
data[i].listingid+"Click to view the details" + "</a></div>";
or else you can use jquery attr method after you finish with appending html to div like below:
var listingid = data[i].listingid;
var myOtherUrl = "SpecificListing.html?Listingid=" + encodeURIComponent(listingid);
var html1 = "<div class=two> Listing Address : " + data[i].address +
"<a id='hrefholder' >"+
data[i].listingid+"Click to view the details" + "</a></div>";
$('#display12').append(html1);
$('#hrefholder').attr("href",myOtherurl );
Tip : Don't forget to add id to anchor tag
Here's a cleaned up version of your callback (I try to avoid string concatenation for HTML as much as possible):
var successCallback = function(data) {
var baseUrl = 'SpecificListing.html?Listingid=';
for (var i=0; i<data.length; i++) {
var listingId = data[i].listingid;
var newUrl = baseUrl + encodeURIComponent(listingId);
var $newDiv = $('<div />').addClass('two');
var $newLink = $('<a />')
.attr('href', newUrl)
.text(listingId + ': Click to view details');
$newDiv.append($newLink);
$('#display12').append($newDiv);
}
};
Find a full working implementation including simulated AJAX call here:
http://jsfiddle.net/klenwell/N2k8X/
var html1 = "<div class=two> Listing Address : " + data[i].address + "<a href=myOtherurl>" + data[i].listingid+"Click to view the details" + "</a></div>";
Will work. Are u binding ajax event to this link?
Anjith and Orion are both right but ya'll have a typo:
the variable in your definition is called myOtherUrl but inside your concatenated string it is myOtherurl. Variables are case-sensitive.
your variable will be parsed as a variable if you leave your double quotes around it so it's good as is