angularjs changes in data not affected in views ajax - ajax

I am developing an application with angular js
Question: When I have an ajax call to server and I need to change the views based on the result of ajax call, the views don't get affected by this call, I think it the page renders before ajax call is finished but I don't know how to resolve it
For example the following piece of code
$scope.addItem = function() {
$http({
method :'GET',
url : 'addItem',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function(data) {
$scope.allItems = data;
});
}
the allItems changed after the ajax call but the view is not changed
how should I solve this?

Related

Do I sent two requests to the ActionResult?

I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post

Insert Data Using Ajax

I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data
If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:
$('#form-id').submit(function(e){
e.preventDefault();
$.ajax({...});
});
I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.
Everything of these can be created with a ajax request - example:
$.ajax({
method: "POST",
url: "/posts",
data: { title: "Hello World", text: "..." }
})
.done(function( post ) {
// assuming you return the post
alert(post.title + " created");
});
Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example
Controller function:
public function store(Request $request) {
$post = App\Post::create($request->all());
if($request->ajax()) {
return $post;
} else {
return redirect('/posts');
}
}
now you controller will return data on ajax calls and will redirect you on default calls without ajax.
Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head
and then (before doing all your calls etc.) add this to configure your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.
Things to keep in mind:
- if you stay very long on one page tokens might expire ( laravel-caffeine will help here )
- you need to handle validation for ajax calls

django JSON response does not attached to jQuery post sucess

I use Ajax post method to send my form information to django and after a time consuming process results get back to the ajax post . the problem is that when django view return
result It apear on web browser screen and seems it dose not bound to ajax post success method
here is my Ajax post method :
$('#LearnSubmit').on('click',function(e){
e.preventDefault
var form =$('#ParameterForm');
console.log("waiting ajax");
$.ajax({
type :"POST",
url : $form.attr('action'),
data : $form.serialize(),
success : function(data,status){
console.log('lablablab');
console.log(data)
}
})
}) ;
according to my ajax post method after djang oview return result "lablablab" and data should print in console but returing result is printed on screen
could time consuming django view cause that ?
here is my django view :
def NNLearnSin(request):
context = RequestContext(request)
if request.method=='POST':
response_dict = // a time consuming process here
return JsonResponse(respons_dict)
It sounds like your form submit button is actually submitting the form and the click event is not called. Looking at your code I would say that e.preventDefault should be e.preventDefault() otherwise the default form submit is not "prevented".

dynamicly fill table using zpt and ajax as update

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Jquery mobile changePage after Ajax call

I have a probleme with ah changePage.
I want to switch the Page after an Ajax call.
If the form get submit, this function will be executed, but after the ajax call the page does not switch.
If I wanna set a Breakpoint on this call, it do not stop.
What can I do, that I can switch the page after the ajax call.
$("#serialNumber").submit(function() {
$.ajax({
type: "POST",
url: "mobilemain.do",
data: "serialNumberInput=" + $("#serialNumberInput").val(),
success: function(msg)
{
$.mobile.changePage("#machine_manuals", "slide");
}
});
});
Edit:
Ok!
I found some hint to my Problem.
The SAP-Server call is from the form-submit and not from my ajax-call.
He never goes in the method above.
On my Server, I made that:
l_view = create_view( view_name = 'main.htm').
call_view( l_view ).
But I does not wanna call the main.htm .
I wanna call the second page in the jquery mobile project. (main.htm#machine_manuals)
How does that work?
Other than the page you are changing to, all options for $.mobile.changePage are passed as a key-value pair in an object.
Your changePage should look like this:
$.mobile.changePage("#machine_manuals", {transition: "slide"});
The documentation for the method, and the options available can be found here:
http://api.jquerymobile.com/jQuery.mobile.changePage/

Resources