Angular $http returning new values only once - codeigniter

I am new to Angular, and set up a simple example with a REST Api config in Codeigniter that returns a json (default) thread list. No problems!
Until, I add an update to the Database. If I clear/then call getThreads again, I receive the same list of items. A page refresh solves this. I can see in firebug that its only calling the url:api/example/threadlist/id/'x' once per page load.
function ThreadsCtrl($scope, $http, $templateCache) {
$scope.getThreads = function(id) {
if (!id) { id = 'reset'; }
$http({method: 'GET', url: 'api/example/threadlist/id/' + id, cache: $templateCache}).
success(function(data) {
$scope.threadslist = data; //set view model
}).
error(function(data) {
$scope.threadslist = data || "Request failed";
});
};
How would I make it so that it always calls a new list of data rather than reuses the old.
Thanks!

If i understood your question correctly your ajax call is being cached so you have to remove cache:$templatecache from your code

Related

Ajax call to webapi does not hit the ajax response and not returning results

I have a webapi project where I'm returning a list of products and I have an ajax call on my another project.
When I use ajax call on webapi index page it gets the response, while when I'm using it on the project that references webapi, it doesn't hit the ajax's response bit.
In both cases the api Get method is called and returns correct results and response, it's just ajax doesn't exceute on the other project.
The ajax code is exactly the same on both webapi index page as it is on the other project page:
Ajax:
$.getJSON("http://localhost:65331/dataapi/Product")
.done(function (data) {
// On the other project it never gets to this bit below:
$.each(data, function (item) {
var label = item.Name + ' (' + item.Code + ')';
});
});
WebAPI get method:
public HttpResponseMessage Get()
{
ProductSearcher searcher = new ProductSearcher();
List<ProductModel> products = searcher.GetResults();
// Then I return the list
return Request.CreateResponse(HttpStatusCode.OK, products);
}
I tried also to use $.ajax({type: "GET", ...}) but it doesn't change anything.
Any ideas why how can I get the ajax response working?

Kendo grid batch editing - making a single call to save

With Kendo grid batch editing turned on, I know that you can hook into the create, update and destroy commands where Kendo will send 3 separate commands to the server when you click on Save Changes.
I was wondering if there was any way to send all three sets of updates as a single call to the server -like a transaction. Or even send each in a specified order, with a check for success before sending the next .
The only way I could come up with was to have a custom Save Changes implementation which ,when invoked, would lookup the grid datasource to find out all rows that have been added (isNew() for added rows), deleted (_destroyed for deleted rows), updated (isDirty for updated rows) and then craft my own call to a server endpoint using ajax using the identified datasets.
Telerik posted a work-around in their code library recently: http://www.kendoui.com/code-library/mvc/grid/save-all-changes-with-one-request.aspx. Unfortunately the work-around is rather bare-bones. It gives a good example of how to capture destroyed, dirty, and new records but finishes with some hand waving to handle any errors in the response and synchronizing the data source on success. Also note that there is no check to ensure there are destroyed, dirty, or new records before making the ajax request.
Here is the relevant code. Download the full example from the link above to see how the grid is setup and to ensure you have the latest version.
function sendData() {
var grid = $("#Grid").data("kendoGrid"),
parameterMap = grid.dataSource.transport.parameterMap;
//get the new and the updated records
var currentData = grid.dataSource.data();
var updatedRecords = [];
var newRecords = [];
for (var i = 0; i < currentData.length; i++) {
if (currentData[i].isNew()) {
//this record is new
newRecords.push(currentData[i].toJSON());
} else if(currentData[i].dirty) {
updatedRecords.push(currentData[i].toJSON());
}
}
//this records are deleted
var deletedRecords = [];
for (var i = 0; i < grid.dataSource._destroyed.length; i++) {
deletedRecords.push(grid.dataSource._destroyed[i].toJSON());
}
var data = {};
$.extend(data, parameterMap({ updated: updatedRecords }), parameterMap({ deleted: deletedRecords }), parameterMap({ new: newRecords }));
$.ajax({
url: "/Home/UpdateCreateDelete",
data: data,
type: "POST",
error: function () {
//Handle the server errors using the approach from the previous example
},
success: function () {
alert("update on server is completed");
grid.dataSource._destroyed = [];
//refresh the grid - optional
grid.dataSource.read();
}
})
}
Maybe you can enable the batch property of the Datasource
batch Boolean(default: false)
If set to true the data source will batch CRUD operation requests. For example updating two data items would cause one HTTP request instead of two. By default the data source makes a HTTP request for every CRUD operation.
Source : Datasource API
After six years we have an answer, check submit function to execute single request to save all changes: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.submit

Should i use threads when executing action method through AJAX?

I am building a questionnarie. When a user clicks on an answer possibility for a multiple choice question (this is a radio button), i call an action method to save this answer.
The code:
<script language="javascript">
$(document).ready(function () {
$('.MCQRadio').click(function () {
var question_id = $(this).attr('question-id');
var mcq_id = $(this).attr('mcq-id');
$.ajax({
url: '/SaveSurveyAnswers/SaveMCQAnswer',
data: { "mcq_id": mcq_id, "question_id": question_id },
success: function (data) {
}
});
});
});
The code to save the answer:
public EmptyResult SaveMCQAnswer(int mcq_id, int question_id)
{
MCQ_Answers mcqa = null;
try
{
mcqa = db.MCQ_Answers.Single(x => x.question_ID == question_id);
}
catch (InvalidOperationException e)
{
}
if (mcqa != null)
{
mcqa.mcq_id = mcq_id;
}
else
{
MCQ_Answers mcq_answer = new MCQ_Answers()
{
question_ID = question_id,
respondent_id = 1
};
db.MCQ_Answers.AddObject(mcq_answer);
}
db.SaveChanges();
return new EmptyResult();
}
If a question has 5 answer possibilities, and i click on them randomly and fast, and then go back to the previous page, ie, when i return the correct answer wont be saved. Should i use threading to make sure the correct answer is saved? And how?
Thanks
rather than saving your answer by post all the time, you can just create a JSOn object and save the answers within json. you can then at the end post all completed answers in one go.
take a look at this: http://msdn.microsoft.com/en-us/scriptjunkie/ff962533
basically this will allow you to store session data - json on the remote machine you then just need an add, delete function and away you go....
i use this to huge extent in an application that would require the server to be updated with the location of objects on a canvas, however with sessvars i just keep all the X and Y locations within there and do a final push of JSON when i am done.
if you change pages, you can then get your values from the JSON object without a server call.
as a note you may also be better off with tabs or hiden sections of form, and therfor reduce the need to re-populate say page1, page2 etc as they will already be there, just hidden!

How can I pass parameters with callback functions to search APIs like Yahoo BOSS and BING?

I am using Yahoo BOSS and Bing APIs to provide search functionality to my site. Specificaly, I use their JSON response formats where I would pass a callback function to the search provider that would later be called back with the search results. My callback function actually gets called, but the problem is, if I make more than one requests at a time, I can't tell which request a certain response is for. To this end, is there a way to pass additional parameters with the callback function to the search provider so that I can later use it to identify which response goes with which request?
Thank you
I have a same problem with you! I googled and find some solutions
and I has solve my problem. Now i show it to you, I hope it can help you :)
Previous code:
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d
$.each(pins, function (index, pin) {
var geocodeRequest = 'http://ecn.dev.virtualearth.net/REST/v1/Locations/' + pin.City + ',' + pin.Country + '?output=json&jsonp=GeocodeCallback&key=' + credentials;
CallRestService(geocodeRequest);
});
function CallRestService(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
}
function GeocodeCallback(result) {.. to do with result callback, --> i want to add some pin infomation here}
Because each sccipt when add to document ( document.body.appendChild(script);) it will be run --> and callback, you cant add more params.
I solve it by request through ajax (doesnt add to document any more), when the ajax call success --> I call the GeocodeCallback(result, pin)
Here is the complete code.
function MakeGeocodeRequest(credentials) {
var pins = checkLocation.d;
$.each(pins, function (index, pin) {
$.ajax({
url:"http://ecn.dev.virtualearth.net/REST/v1/Locations/",
dataType: "jsonp",
data:{key:credentials,q:pin.City + ',' + pin.Country},
jsonp:"jsonp",
success: function(result){
GeocodeCallback(result,pin);
}
});
});
}
function GeocodeCallback(result,pin) { ... to do here}

Handling Json data outside a function with pebble.js

In the function getweather() I do fetch some weather data from a Json-object and store that data in the variable data. Within that function, I can handle the Json-data, but how do I access the data from outside of getweather()?
It doesn't matter if i return the variable location or data. The variable place is just not Json.
How do I handle the place variable in order to make it work as it does within the function getweather()?
var ajax = require('ajax');
var place;
place = getweather();
function getweather()
{
// Make the request
ajax(
{
url: 'http://api.openweathermap.org/data/2.5/weather?q=paris.fr', type: 'json'
},
function(data)
{
// Success!
console.log("Successfully fetched weather data!");
// Extract data
var location = data.name;
return location;
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
}
The A in AJAX stands for asynchronous. What's happening in your code is that you are trying to assign a value to place before the asynchronous call to api.openweather.org has returned.
You can check this by placing a statement like console.log(place); directly after place = getweather();. You will notice in the console that None is returned before you see Successfully fetched weather data!
This issue has been described in detail in this post. It recommends restructuring your code around your callbacks.

Resources