I am able to fetch all my data from database successfully but only the last item in the array displays. What am I doing wrong?
HTML
#foreach($groups as $group)
<button type ="button" value="{!! $group->id !!}" id="btn" name="btn">{!!$group->name!!}</button>
<div class="panel">
<label for="myvalue"><input type="checkbox" id="myvalue" /> <span>Label text x</span></label>
</div>
#endforeach
JavaScript
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data: {
id: $(this).val(),
access_token: $("#access_token").val()
},
success: function (result) {
$.each(result, function (i, fb) {
$("label[for='myvalue']").text(fb.name);
});
}
);
This way you are replacing the label text, not creating labels. What you are looking for would be something like:
<div class="panel" id="labels_cotainer">
<label for="myvalue">
<input type="checkbox" id="myvalue" />
<span>Label text x</span></label>
</div>
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data:{
id: $(this).val(),
access_token: $("#access_token").val()
},
success:function(result) {
$.each(result, function (i, fb) {
$("#labels_cotainer").append('<label>'+fb.name+'</label>');
}
}
});
This code will append every label to your panel
You have to dynamically create new labels and add fb.name to it otherwise you will replace all values until the last value
success:function(result) {
$.each(result, function (i, fb) {
$("#outerDiv").append('<label>'+fb.name+'</label>');
});
}
Related
Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);
I'm struggling with some javascript to figure out the proper way to make it work.
I have a button showing the number of items in the cart. By default is zero. As items added the cart the number is increasing. But at the beginning, I don't want to show "0" in the cart.
HTML:
<p id="cart_button" onclick="show_cart();">
<input type="button" id="total_items" value="0">
</p>
<div id="mycart"></div>
<div id="item_div">
<div class="items" id="item1">
<input type="button" value="Add To CART" onclick="cart('item1')">
<p>Simple Navy Blue T-Shirt</p>
<input type="hidden" id="item1_name" value="ITEM-ID1">
</div>
<div class="items" id="item2">
<input type="button" value="Add To CART" onclick="cart('item2')">
<p>Trendy T-Shirt With Back Design</p>
<input type="hidden" id="item2_name" value="ITEM-ID2">
</div>
</div>
JAVASCRIPT:
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
});
function cart(id) {
var name = document.getElementById(id + "_name").value;
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
item_name: name
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
}
function show_cart() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
showcart: "cart"
},
success: function(response) {
document.getElementById("mycart").innerHTML = response;
$("#mycart").slideToggle();
}
});
}
I basically want the button with 0 to be hidden until it gets a value. if it goes back to zero I want it to be hidden again.
Thank you for the help!
You can add 'change' event listener to this button:
let totalItems = $('#total_items');
totalItems.change(function () {
if (totalItems.val() == 0) {
totalItems.hide();
}
else totalItems.show();
});
Also you should trigger this event in your success method of ajax:
success: function(response) {
document.getElementById("total_items").value = response;
totalItems.change();
}
And finally hide this button at start:
<input type="button" id="total_items" value="0" style="display: none">
Check this working in fiddle:
https://jsfiddle.net/xpvt214o/771844/
You can show/hide when update cart:
// Add this function
function update_cart(value) {
document.getElementById("total_items").value = response;
if (value > 0) {
// Show the cart
document.getElementById("total_items").style.display = "block";
} else {
// Hide the cart
document.getElementById("total_items").style.display = "none";
}
}
Then, you need to change your code, when update cart:
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
update_cart(response);
}
});
I've AJAX response which needs to be rendered in HTML setup in PHP file. I'm confused regarding how to render it as there are multiple data in AJAX response and each of them must be put in specific places in html
for example AJAX response has two(or n) objects like this:
0:Object
id: "111"
Name: "abc"
1:Object
id: "112"
Name: "xyz"
Then, There already would be two(or n) divs with user class in HTML
<div class='user'>
<div class='userId'>
<div class='usernm'> </div>
</div>
</div>
<div class='user'>
<div class='userId'>
<div class='usernm'> </div>
</div>
</div>
What I need is put those response values in this divs like this:
<div class='user'>
<div class='userId'> 111
<div class='usernm'> abc </div>
</div>
</div>
<div class='user'>
<div class='userId'> 112
<div class='usernm'> xyz</div>
</div>
</div>
I'm lost as to how can I achieve that on AJAX Success here using jQuery:
$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$.each(data, function(key, value){
console.log(value); //this outputs response as Objects shown above
});
}
});
Use the append function in your loop to add the elements to the page
$('body').append('<div class="user">
<div class="userId"> '+value.id+'
<div class="usernm">'+value.name+'</div>
</div>
</div>');//note change the body element to your desired parent element
if you only need to put the data do the following:
success: function(data) {
$('.userId').each(function(key, value){
$(value).prepend(data[key].id);
$(value).find('.usernm').text(data[key].name);
});
}
demo:https://jsfiddle.net/gf32wd7L/1/
Can you please try
$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
$('<div/>', {
'class': 'user'
}).append(
$('<div/>', {
'class': 'userId'
}).text(this.id).append(
$('<div/>', {
text: 'usernme'
}).text(this.Name)
});
});
}
});
This is another way, Use if it is convenient,
Let us say ur HTML,
<div class="append-div"></div>
Your JSON,
{
"Objects":[
{
"id": "111",
"name": "abc"
},
{
"id": "112",
"name": "xyz"
}
]
}
The JS,
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'json.js',
dataType: "json",
success: function(data) {
var userDiv = "";
$.each(data.Objects, function(key, value){
console.log(value); //this outputs response as Objects shown above
userDiv += '<div class="user"><div class="userId">' + value.id + '</div>' + value.name + '</div>';
});
$(".append-div").append(userDiv); // Append the results
}
});
});
I am having some anchor tags in the page and I have to set them all a value in query string and then
trying to send it in controller can this be possible.Actually I have a hidden field on the page and that hidden field is set to a value
when somebody selects a user from auto complete of jquery. Now my Question is that I am able to set hidden field a value but how can I assign value of hidden
field to query string in an anchor tag. Please help me. I am trying in this way.
<div id="page">
<div class="note-row2">
<div class="form-left">
<input type="text" id="txt_Autocomplete" />
<input type="hidden" id="hdnPkClientId" />
</div>
<div class="form-right">
</div>
<div class="right-row">
<h3><a href="/GoToPage/Index?Client_ID="+"'$('#hdnPkClientId').val()'" >My Page</a></h3>
</div>
</div>
</div>
Here I am setting the value in hidden field
<script>
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/ClientHome/SearchClientDetail",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id,
data: item
};
}));
},
error: function (xhr)
{ }
});
},
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
</script>
I
in your html:
<a id="YOUR_A" href="/GoToPage/Index?Client_ID=" >My Page</a>
in your js:
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
$("#YOUR_A").attr("href", "/GoToPage/Index?Client_ID="+ui.item.data.Id);
}
I am trying to pull text from another page (ajaxuseradd.psp) which is in JSON format. I am then trying to insert this text into several text boxes and/or select lists. For right now, I am merely trying to do the text boxes.
Here's my code, a good deal of which was given to me, because I am not all that familiar with jQuery:
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
</script>
<form action="adduser.psp" method="get">
<fieldset>
<label for="uname">Username:</label>
<select name="uname" id="useruname" onchange="updateAdduser();">
<%
Random Python Code That Isn't Important But Generates Option Values
%>
<%= options %>
</select>
</fieldset>
<fieldset>
<label for="fname">First Name:</label>
<input type="text" name="fname" />
</fieldset>
<fieldset>
<label for="lname">Last Name:</label>
<input type="text" name="lname" />
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="text" name="email">
</fieldset>
Output from ajaxuser.psp should be as follows, or some variation thereof. This will be displayed on the page ajaxuser.psp when the argument ?uname=neverland is used, for example:
{"fname" : Neverland, "lname" : Conference Room, "email" : nobody#mediaG.com, "deptid" : deptid, "active" : active, "sentient" : sentient}
So my code should look like this?
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$("#fname").val(data.fname);
});
},
dataType: 'json'
})
});
});
</script>
EDIT: This is still not working - I select a drop down value, and NO CHANGE for any of the fields.
The first thing I see is that you need to wrap the onchange handler in this:
$(document).ready(function () {
});
So it looks like this:
$(document).ready(function () {
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
});
Also, this:
$.each(data, function(key, value) {
$('#' + key).val(value);
});
Is not going to work like you think. You get back ONE object with the properties, so more like this:
success: function(data, status, xhr) {
$("#fname").val(data.fname);
....
},