How to populate Span elements in an Ajax success setting - javascript

After a form is submitted (form not shown) My page is receiving a JSON encoded array from my php script with no issue. The page has the following elements that I am trying to populate with the data from json. I'm trying to get the data to show up between the span elements.
<div class="added_display">
<ul>
<li>
<p>Title: <span class="title"></span></p>
</li>
<li style="color: #FF0004">
<p><span class="comment" style="color: #FF4245"></span></p>
</li>
<li>
<p>Address: <span class="address"></span></p>
</li>
<li>
<p>Sale Price: <span class="sale-price"></span></p>
</li>
<li>
<p>Lease Price: <span class="lease-price"></span></p>
</li>
<li>
<p>Lot Size: <span class="lot-size"></span></p>
</li>
<li>
<p>Building Size: <span class="building-size"></span></p>
</li>
<li>
<p>Zoning: <span class="zoning"></span></p>
</li>
</ul>
</div>
and the following ajax script directing everything. I am using the span elements class in the success setting:
$("document").ready(function() {
$(".data-form").submit(function() {
data = $(this).serialize();
if (confirm("Are you ready to sumbmit this listing?\nYou can always edit the listing after going to the menu tab - edit listing."))
{
$.ajax({
type: "POST",
dataType: "json",
url: "add-list.php",
data: data,
success: function(response) {
if (response.success) {
$("#modal1").modal('hide');
$(".added_display").show();
$(".title").data(title);
$(".comment").data(comment);
$(".address").data(address);
$(".sale-price").data(sale_price);
$(".lease-price").data(lease_price);
$(".lot-size").data(lot_size);
$(".building-size").data(build_size);
$(".zoning").data(zoning);
$(".ad_link").data(ad_link);
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
error: function() {
alert("An Error has ocurred contacting the server. Please contact your system administrator");
}
});
return false;
}
});
});
I think my error is tied up in the success setting. How can I correct this code to populate my span elements?

Instead of .data(value); try .text(value);
The as per docs, .data() will store arbitrary data on an element. It won't be used to display a value in the DOM. If you want to set the text inside an element use .text(text).
If the values are HTML, use .html(htmlString).

Related

JQUERY/AJAX-multiply classes based on content number

I'm trying to extract specific data and send them to the client side so in order to achieve that I used AJAX like below :
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`) // event1 is the id of field name
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} |
${data[i].events.targetAmPM} </b>`)// time1is the id of field time and date
$("#comment1").html(`<b>${data[i].events.caption}</b>`) // comment1 is the id of field description
$("#location1").html(`<b>${data[i].events.location}</b>`) // location1 is the id of field location
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
and this is the output
this script works perfectly and fill one container with the requested values but what I'm looking for is to fill every container and multiply them based on data found from my db
which mean :
1- if there is more than one data data[i].events.eventName or other another container must be created and get filled by the new value
the HTML code is below :
<div class="card">
<div class="card-header" id="headingOne-1">
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`)
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} | ${data[i].events.targetAmPM} </b>`)
$("#comment1").html(`<b>${data[i].events.caption}</b>`)
$("#location1").html(`<b>${data[i].events.location}</b>`)
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
<div class="event-time">
<time id="time1" datetime="2004-07-24T18:18">9:00am</time>
<div class="more"><svg class="olymp-three-dots-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-three-dots-icon"></use></svg>
<ul class="more-dropdown">
<li>
Mark as Completed
</li>
<li>
Delete Event
</li>
</ul>
</div>
</div>
<h5 class="mb-0 title">
<a href="#" data-toggle="collapse" data-target="#collapseOne-1" aria-expanded="true" aria-controls="collapseOne" id = "event1">
Breakfast at the Agency
<i class="fa fa-angle-down" aria-hidden="true"></i>
<span class="event-status-icon" data-toggle="modal" data-target="#public-event">
<svg class="olymp-calendar-icon" data-toggle="tooltip" data-placement="top" data-original-title="UNCOMPLETED"><use xlink:href="svg-icons/sprites/icons.svg#olymp-calendar-icon"></use></svg>
</span>
</a>
</h5>
</div>
<div id="#collapseOne-1" class="collapse show" aria-labelledby="headingOne" data-parent="#headingOne-1">
<div class="card-body" id ="comment1">
Hi Guys! I propose to go a litle earlier at the agency to have breakfast and talk a little more about the new design project we have been working on. Cheers!
</div>
<div class="place inline-items">
<svg class="olymp-add-a-place-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-add-a-place-icon"></use></svg>
<span id ="location1">Daydreamz Agency</span>
</div>
</div>
</div>
Any idea how to multiply that box based on data found with the script mentioned above ?
Hope I mentioned everything :-D ?
Best Regards,
Every time your loop works, $("#event1").html(....), $("#-----").html(....) will be replaced with your new values. So why don't you rather create a variable name html outside a loop and every div section or html tags that needs to be rendered in DOM, inside the loop and append after the div you want to render. Like mentioned on above answer,
var html="";
for(let i =0; i< data.length;i++){
html += `<div class="card-header"> ${data[i].event.eventName} </div>` +
`<div class=" -----"> $${data[i].event.eventDate} ` +
------------------and so on---------------------------;
}
$("#NAME OF ID BEHIND YOU WANT TO SHOW YOUR NEW DIV").append(html);
Hope it will work :)
I believe you should just create the whole HTML in javascript then append that HTML to DOM. for example.
let html = "";
for(let i =0; i< data.length;i++) {
html += "<p>"+ data[i].events.eventName + "</p>";
html += "<p>"+ data[i].events.eventDate + "</p>";
}
$("#ParentDivIDWhereToAppendThisContent").html(html);
The above code is just an example of how you can do it. You need to customize it to suit your needs.

How to load separate html page into a div on click?

I am really new to javascript and jquery, but I am trying to create a page that will allow the user to click on a Country name and information for that country will load in a div from a separate html file.
Else where I found this code which works nicely for this, using the .click(function) on the <a> tag:
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#partnerContent").html(response);
}
});
return false;
});
});
Here is the basic html:
<div id="contentcontain">
<div class="partnercol1">
<div class="container">
<div id="menu" class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data- toggle="dropdown">International Sales <span class="caret"></span></button>
<ul class="dropdown-menu scrollable-menu" role="menu">
<li>Belgium</li>
<li>Brunei</li>
<li>Bulgaria</li>
</ul>
</div>
</div>
</div>
<div class="partnercol2">
<div id="partnerContent"></div>
</div>
However, now every <a> tag on the page (including top and bottom menus) loads their href into the div when clicked. How can I target just the div containing the state menu to work with this function?
Make the selector for the elements you're attaching the events to more restrictive:
// this selects all the anchors below the items with ID menu
$j("#menu a").click(function () {
...
});
in your html, put:
<ul class="dropdown-menu scrollable-menu" role="menu">
<li><a class="menu-item" href="partners/belgium.html">Belgium</a></li>
<li><a class="menu-item" href="partners/brunei.html">Brunei</a></li>
<li><a class="menu-item" href="partners/bulgaria.html">Bulgaria</a></li>
</ul>
And in your javascript
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(".menu-item").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#partnerContent").html(response);
}
});
return false;
});
});
You're loading an entire html page, which means you're loading
<html>...</html>
and then stuffing that in its entirety into your page, that means you'll eventually have
<html>
....
<html>...</html>
...
</html>
which is NOT valid. If you're trying to replace the contents of a single <div> in your page, then either you fetch that entire page into a var and slice out the chunk you want, or have jquery fetch/insert ONLY the part you want, e.g.
$('#div_to_replace').load('source_of_new.html #id_of_element_to_use_for_replacement');
Note the second #... argument in the .load() call. That tells jquery to ignore everything in the page EXCEPT for the specified element/ID. Only that ID's contents will be stuffed into #div_to_replace.

Load JSON data into a Bootstrap modal

I want to load a JSON file that creates a list inside a Bootstrap Modal. I have it set where if you click on a person's picture, the modal pops up.
<li class="project span3" data-type="pfa">
<a data-toggle="modal" data-target="#myModal" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
Here's an example of the JSON data:
var florida_exoneration = [
{
"last_name":"Atkins",
"first_name":"Kenneth",
"age":16,
"race":"Caucasian",
"state":"FL",
"crime":"Sexual Assault",
"sentence":"10 years",
"conviction":2004,
"exonerated":2008,
"dna":"",
"mistaken witness identification":"",
"false confession":"",
"perjury/false accusation":"Y",
"false evidence":"",
"official misconduct":"",
"inadequate legal defense":"",
"compensation":""
}
]
I'd like the modal to display something like this inside the box:
Title = "first_name + last_name"
Age = "age"
Race = "race"
State = "state"
""
""
I also want to make sure the data is tied to the picture so the modal doesn't get confused. I'm sorry if this is a bit confusing. I'll try and clarify if anyone has any questions.
Method 1: using Ajax
Every time a user clicks an image, you get the id from the clicked image and then you send an Ajax request to server in order to get the JSON object.
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" data-id="2" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
$.ajax({
type: "GET",
url: 'getJson.php?id='+$(this).data('id'),
dataType: 'json',
success: function(data){
htmlData = '<ul><li>title: '+data.first_name+'</li><li>age: '+data.age+'</li></ul>';
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
}
});
return false;
});
})(jQuery);
Method 2: using hidden div
No need to any Ajax request, but you need to create a hidden div that contain all the information you want to display in the modal
HTML
<ul>
<li class="project span3" data-type="pfa">
<a href="#" class="thumbnail">
<img src="img/anon.jpg" alt="Kenneth Atkins" />
<h1>Kenneth Atkins</h1>
<p>[Description here]</p>
<div class="profile hide">
<ul>
<li>title: Atkins Kenneth</li>
<li>Age: 16</li>
</ul>
</div>
</a>
</li>
</ul>
JavaScript
(function($) {
var infoModal = $('#myModal');
$('.thumbnail').on('click', function(){
htmlData = $(this).find('.profile').html();
infoModal.find('.modal-body').html(htmlData);
infoModal.modal('show');
return false;
});
})(jQuery);

MVC display partial view on navigation bar click

I want to display the partial view, when I click on navigation bar click. I have a view which contains left side menu. when user click on navigation bar item, appropriate view should display.
I am not getting how can I implement such view?
Manage.cshtml
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h1>My Account</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked nav-stacked-extended">
<li class="active">
<a id="A3" target="_self" runat="server" href="#Url.Action("Contactinfo", "Account")">Contact Info</a>
</li>
<li class="">
<a id="A4" target="_self" runat="server" href="#Url.Action("changePassword", "Account")">Password</a>
</li>
</ul>
</div>
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
#Html.Partial("Contactinfo")
</div>
</div>
</div>
In above code, I have created left side menu i.e contactinfo, changepassword etc. when Manage.cshtml load first time I want to display Contactinfo view. When user click on password menu, contactinfo get's changed with changedpassword page. Please check following screen shot.
Here in above image you can see left side menu and appropriate page. What I want when user click on password, view changed to password page. Currently it shows contact info page. How can I do this?
i think you should render partial through JavaScript.
Let's say you have <div id="partialView"></div>
Then you should run Ajax query when user clicked on link.
Something like:
$.ajax({
url: $(this).data('yourUrl'),
type: 'GET',
cache: false,
success: function(result) {
$('#partialView').html(result);
}
});
Took me a little while to figure this out too.
Essentially, you want your Controller action to return a partial view, then use Ajax to load that returned partial view.
JavaScript / Ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { 'viewName': 'password' },
success: function (data) {
$('#partial-container').html(data);
}
});
Controller return type
Public ActionResult GetView(string viewName)
{
return PartialView(viewName, model);
}
Ideally, change your HTML so it's easier to reference the div container where you'd like to load the partial
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
<div id="partial-container">#Html.Partial("Contactinfo")</div>
</div>
</div>
In your requirement just make partial Views of the links present in your left side bar and when user clicks on a specific option in left side bar then just load a appropriate partial view from ajax call using jquery and just replace html of right side bar with the html coming from ajax call.
Give your left side menues unique id and then :
A Demo :
$(document).ready(function(){
$("#menu1").click(function(e){
e.preventDefault();
$.ajax({
url: "/MyController/getdata",
type: 'GET',
datatype: 'html',
data: { },
success: function (data) {
$("#div1").html('');
$("#div1").html(data);
});
});
});
Controller(MyController) :
[HttpGet]
Public ActionResult getdata(string dropval)
{
//bind model here
return PartialView("mypartialview",model)
}
try This JS for Clickevent
$(document).on('click', '#anCalcBtn', function () {
$('#anCalcDetail').load('/Home/Contactinfo/');
});
If I am not wrong you are trying to do like This

Cannot debug jQuery button

I have this button, and when clicked, it sends an ajax call which changes the value of score_up.
I dont see what the problem is. I tried firbug, but apparently it's not even detecting the javascript? :)) Thanks.
jquery:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
//get the id
var the_id = $(this).closest('.score').attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$(this).siblings("h2.score_up").html(msg).fadeIn();
//remove down button
// and remove support button
}
});
});
html:
<ul class="stats">
<li id="support_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
//vote down button
<li id="down_23"class="score">
<h2 class="score_down">12</h2>
<span style="text-align:center;">down</span>
</li>
<li>
<button type="submit" value="Actions" class="down" title="down">
<i></i>
<span>down</span>
</button>
</li>
</ul>
It is not valid HTML for a <button> to be a direct child of a <ul>.
Children of <ul> should be <li>. I wouldn't expect things to work properly with invalid HTML.
HTML with <button> inside a <li>:
<ul class="stats">
<li id="topic_23" class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
</ul>
jQuery, fixing some of the traversal methods:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
// cache a reference to the previous <li> element
// since it is used more than once
var $prevLi = $(this).closest('li').prev('li');
//get the id
var the_id = $prevLi.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$prevLi.find("h2.score_up").html(msg).fadeIn();
}
});
});
Your HTML is invalid, so I would do:
<form action="javascript:alert('form')";>
<ul class="stats">
<li id="topic_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i><span>Support</span></button>
</li>
</ul>
</form>
And then the jQuery (which in your original would not work, since you wanted .siblings() and not .closest() would now be:
var the_id = $(this).closest("li").siblings('.score').attr('id')
.split('_').pop();
and success:
$(this).closest("li").siblings("li.score").find("h2.score_up")
.html(msg).fadeIn();
I think you also run into troubles with prevent default, since you want to prevent default on the form, and in that case you might run into problems with delegate.
Here is what I would do with .live():
// Prevent form from submitting
$("form").live("submit", function(e) {
e.preventDefault(); });
// Run Ajax
$('button.support').live('click', function(e) {
//get the id
var $score = $(this).closest("li").siblings('.score'),
the_id = $score.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$score.find("h2.score_up").html(msg).fadeIn();
}
});
});
​
Try it out on this jsFiddle

Categories

Resources