I have a following HTML:
<div id="main">
<div id="blogcont">
<p></p>
</div>
<button class="nvgt" id="prev" >Previous</button>
<button class="nvgt" id="next" >Next</button>
By clicking on either the Previous or Next button, I want to load the data from a JSON file - articles content. My JSON at the moment looks like below and it is located in separated folder (it is only a test version):
var = articles [
{
"Title":"test1",
"Content":"test1",
"related":"test1"
},
{
"Title":"test2",
"Content":"test2",
"related":"test2"
}
]
_(I am not sure if the syntax is correct)
function (){
$ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function (data){
$.each(data, function (key, val){
});
});
}
It's supposed to be done via an AJAX request. Any ideas how to do it?
First of all, if JSON, it needs to be like:
[
{
"Title":"test1",
"Content":"test1",
"related":"test1"
},
{
"Title":"test2",
"Content":"test2",
"related":"test2"
}
]
Then, do not load data everytime you click on prev, next buttons. Load it once and use it later, as and when you need. Irrespective of that, here are the click/ajax calls:
$('#main').on('click', 'button', function(){
//OR $('#main').on('click', '#prev,#next', function(){
$ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function (data) {
$.each(data, function (key, val){
//Do your stuff here;
});
});
});
Related
I'm outputting API data on separate pages coming from different end point urls, ie. https://api.server.com/first, https://api.server.com/second, etc.
The code is working, but it seems awfully redundant and I'm sure there's a better way of expressing this that's more optimal and faster:
var $rubys = $('#rubys');
$(function () {
$('#loading-rubys').show();
$.ajax({
type: 'GET',
url: 'https://api.server.com/first/',
success: function(rubys) {
$.each(rubys, function(i, ruby) {
$rubys.append('$'+parseFloat(ruby.price).toFixed(2)+' |
$'+parseFloat(ruby.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-rubys').hide();
}
})
});
var $emeralds = $('#emeralds');
$(function () {
$('#loading-emeralds').show();
$.ajax({
type: 'GET',
url: 'https://api.server.com/second/',
success: function(emeralds) {
$.each(emeralds, function(i, emerald) {
$emeralds.append('$'+parseFloat(emerald.price).toFixed(2)+' |
$'+parseFloat(emerald.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-emeralds').hide();
}
})
});
The following:
var $rubys = $('#rubys');
$('#loading-rubys').show();
are set for each post page using YAML front-matter (Jekyll) like so:
---
title: Post about Ruby
var-id: rubys
load-id: loading-rubys
---
and output them in HTML:
<div id="{{ page.var-id }}">
<div id="{{ page.load-id }}">
<img src="/assets/img/loading.svg"/>
</div>
</div>
Current workflow
So basically whenever I create a new post, I:
Set the var-id and load-id custom parameters for each post in the front-matter
Create a new function to include those and make a new GET request to the respective url, ie. https://api.server.com/third/, https://api.server.com/fourth/.
How would you write this better?
Something like this could help.
function getGems(gems,gemsURL) {
var $gems = $('#'+gems);
$('#loading-'+gems).show();
$.ajax({
type: 'GET',
url: gemsURL,
success: function(data) {
$.each(data, function(i, v) {
$gems.append('$'+parseFloat(v.price).toFixed(2)+' |
$'+parseFloat(v.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-'+gems).hide();
}
});
}
$(function () {
getGems('rubys','https://api.server.com/first/');
getGems('emeralds','https://api.server.com/second/')
});
Hi everybody I need to change text label from JsonResult on my Controller... I have two problems...
1) I can't print on my view the text that I send from my
controller...
2) I want to send 3 labels from my controller when I selected a
option from my dropdownlist.
Please help if someone know how to do this... :)
On my View
<div class="col-md-6 col-sm-6 col-xs-12">
<label id="lblCargo"></label>
</div>
#section scripts{
<script>
$(document).ready(function () {
$("#ddlEmpleado").change(function () {
var selectedItemValue = $(this).find(":selected").val()
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("getLabels", "AsignarBien")',
data: {
"id": selectedItemValue,
},
contentType: 'application/json; charset=utf-8',
Success: function() {
$("#lblCargo").text(data);
},
error: function() {
alert("error");
}
}
);
});
});
</script>
}
On my Controller I got this
public JsonResult getLabels(Guid id)
{
var result = (from item in vempleados.GetAll().ToList()
where item.IdEmpleado == id
select item.Cargo).SingleOrDefault();
return Json(result, JsonRequestBehavior.AllowGet);
}
Three small changes and it will work:
success must be lower case.
Add the data parameter to the success function.
There should be no comma (,) after selectedItemValue
Basically make your $.ajax call like this:
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("getLabels", "AsignarBien")',
data: { "id": selectedItemValue},
success: function (data) {
$("#lblCargo").text(data);
},
error: function () {
alert("error");
}
});
NOTE:You don't need to specify the contentType for the GET request, so you can take that out completely.
so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"
I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function
i have the below knockout js code..
Design Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<div class="acmenu">
<ul id="accordion" data-bind="foreach: CategoryList">
<li data-bind="click$parent.categorySelected),attr: {iddata.CategoryId},htmldata.CategoryName">
</li>
</ul>
</div>
self.categorySelected = function (selectedCategory, event) {
$('#newproducttitle').hide();
event.preventDefault();
selectCategoryId = selectedCategory.CategoryId();
var refurbishedUrl = "/services/ShopService.asmx/XGetRefurbishedproducts";
$.ajax({
url: refurbishedUrl,
data: JSON.stringify({ ItemID: itemid, categoryid: selectCategoryId, language: lang }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
/******Lines of code**********/
}});
}
This function is calling for every click but ajax requesting is sending for second click only. i need to send ajax request for first click, is there any solution for that....
here i am proving one drive link for js file https://onedrive.live.com/redir?resid=143242b617ba6be2!6684&authkey=!AAJQbpV8ZQ7fnGI&ithint=file%2ctxt
Though we don't have enough to work on still I think it is calling on first request as well (unless you have verified in developer tools etc.). The reason it seems to work on second click is that ajax call has not returned and on second click it appears to work.
Try this to disable button until ajax returns:
$.ajax({
url: refurbishedUrl,
data: ...,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend:function(){ $(event.target).prop('disabled', true);},
}).done(function(data){
/*USE THIS INSTEAD OF success*/
}).fail(function(data){
/*USE THIS INSTEAD OF error*/
}).always(function(){
$(event.target).prop('disabled', false);
});
You are using knockout against its design.
The viewmodel manages data and state - and nothing else. It is not supposed to contain any code that does HTML or DOM manipulation, at all.
In this case your data is a list of category objects. You want to inform the server when one of them becomes the selected category. Additionally you want to keep track of whether the viewmodel is busy talking with the server.
Therefore we need categoryList, selectedCategory and busy observables, as well as a subscription to changes in the selected category:
function ViewModel() {
var self = this;
self.categoryList = ko.observableArray([/* category objects ... */]);
self.selectedCategory = ko.observable();
self.busy = ko.observable(false);
self.selectedCategory.subscribe(function (newCategory) {
self.busy(true);
API.post("XGetRefurbishedproducts", {
ItemID: itemid, // wherever that comes from
categoryid: newCategory.CategoryId(),
language: lang // wherever that comes from
}).done(function (data) {
/******** Lines of code ********/
}).always(function () {
self.busy(false);
});
});
}
The view displays the category list, provides a way of changing the selected category, and reacts to whether the viewmodel is busy.
Therefore we need foreach, text, click and disable bindings:
<div class="acmenu">
<ul id="accordion" data-bind="foreach: categoryList">
<li>
<span data-bind="text: CategoryName"></span>
<button data-bind="
click: $parent.selectedCategory,
disable: $parent.busy
">Select</button>
</li>
</ul>
</div>
Note that you can use an observable as a click handler.
Finally, to keep the viewmodel tidy, here's a helper that concentrates all Ajax handling in a central spot.
var API = {
ajax: function (httpMethod, apiMethod, data) {
return $.ajax({
type: httpMethod,
url: "/services/ShopService.asmx/" + apiMethod,
data: data,
dataType: "json"
}).fail(function (jqXhr, status, error) {
console.error("Could not call " + method + ", error: " + error, data);
});
},
get: function (apiMethod, data) {
return this.ajax("get", apiMethod, data);
},
post: function (apiMethod, data) {
return this.ajax("post", apiMethod, data);
}
};