$http({
method: 'GET',
url: 'http://localhost:55090/login/login',
}).success(function(data){
// With the data succesfully returned, call our callback
$("html").html("");
debugger
$("html").html(data);
window.history.pushState("object or string", "Title", "/login/login");
}).error(function(){
alert("error");
});
Above code is working, i am able to load the data of another page without refreshing but the the thing is i am using two different angular for both pages.
As soon as i load another html, all the functionality(including models,directives) stopped working.
If you have 2 differents pages the 2nd will probably have his own angular injector created with the ng-app attribute. So you won't have the service/controller of the 1st page.
Angular is meant to be single page application and not to be used with jQuery like this. If you want to perform some navigation check ngRouteor ui-routeron the net.
If you need to add some HTML at a specificed location check $compile and angular.element even though it's not recommanded.
Related
In my project I have rows of modules loaded from Partial views.
So imagine a grid of small squares with information.
There is a popup dialog for all of them, that displays the data of the clicked module.
Currently when I submit a change in the dialog, the javascript reloads the entire page. BUT, this takes a long time, and I need to be able to refresh only the one dialog.
I can imagine to make a separate js function for each type of module, and then pass some data in, so jquery can find the specific module, and then make an ajax get, for the data. But this requires me to do all the data insertion from js always. instead of using razor and MVC's built in awesomeness.
Does anyone know of a way, to call a partial view inside a div?
Also in the future I will need to reload "some" but not all the modules in an interval refresh. So for future proofing purposes:
What im looking for is something like:
function reloadElement(row, column, id){
var target = $("#div1");
// todo find row and column
target.html.partial("url", model); //<----- looking for something like this. cross fingers.
}
Thanks to GregH for a few key words, that lead to some ideas.
I solved it myself, so if you land on this problem also, here is how i solved it:
Controller:
You want to make your controller return PartialView("somePartialViewUrl", new SomeModel()), apparently saving the model and relying on the data collection isn't good enough, i hadto make a new instance of the model.
Javascript
in the "click" that handles the event, put:
$.ajax({
url: "controllerName/actionName",
data: JSON.stringify({ row:1,column:2 .... }),
contentType: "application/json",
dataType: "html",
type: "POST",
success: function (partial) {
$("#div2").html(partial);
}
});
this will override the html in your "#div2".
im sure you can also use $("#div2").innerHTML = partial; or $("#div2").load("url",parameters); and probably many other ways.
done.
I'm working on a Flask app. One of my views contains dynamically created elements. In order to collect the values and write them my MongoDB database, I created a JS script that goes over the elements and extracts the values to JS variables. After that I POST them to my Flask backend through an AJAX $.post() method. That part works correctly, but when getting to the end of my #app.route function, and I try to redirect to another landing page, I get the following error:
Mixed Content: The page at 'https://cocktail-recipe-book-gabyguedezh.c9users.io/get_add_cocktail_form' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://cocktail-recipe-book-gabyguedezh.c9users.io/get_my_recipes'. This request has been blocked; the content must be served over HTTPS.
The POST itself gets executed and the form sends a document to my database, however, the redirect doesn't happen.
The entire backend route looks like this:
#app.route('/write_to_cocktail_database', methods=['POST'])
def write_to_cocktail_database():
recipes = mongo.db.recipes
recipes.insert_one(request.json)
return redirect(url_for('get_my_recipes'))
Just in case, the AJAX function looks like this:
$.ajax({
url: formUrl,
// data: {'data': steps},
data: JSON.stringify({recipe_name, recipe_url, recipe_description,
recipe_image, is_vegan, ingredients, steps,
base_spirit, cocktail_type, flavour_profile,
author_name, recipe_rating, number_of_votes}, null, '\t'),
type: 'POST',
contentType: 'application/json;charset=UTF-8',
success: function(response) {
console.log('success');
},
error: function(error) {
console.log('error', error);
}
});
I've tried the following:
SSL for particular views as seen HERE
I tried to copy that code at the beginning of my app (including the imports) and then using the #ssl_required decorator below the #app.route like this:
#app.route('/write_to_cocktail_database', methods=['POST'])
#ssl_required
def write_to_cocktail_database():
<rest of function>
return redirect(url_for('get_my_recipes'))
Where get_my_recipes is the route I'm trying to redirect to. This didn't work
I also tried to work around it with a replace method inside of the function like this:
if request.url.startswith('http://'):
request.url = request.url.replace('http://', 'https://', 1)
That didn't work either, as I don't know how to feed the modified URL to the redirect's url_for (and simply doing redirect(modified_url_as_string) doesn't work either).
Now, I know the get_my_recipes route works in other redirects, for example:
#app.route('/delete_cocktail/<recipe_id>')
def delete_cocktail(recipe_id):
mongo.db.recipes.remove({'_id': ObjectId(recipe_id)})
return redirect(url_for('get_my_recipes'))
The above, deletes a recipe and redirects to "My Recipes" page.
I'm not sure why the POST from the AJAX function I wrote doesn't redirect me, but the POST from a regular HTML <form> does work.
I'm also not sure how to use the decorator from the snippet I found (in the link above), as I though simply adding the decorator before the route would work.
I've also tried other workarounds, such as a redirect through jQuery on the success portion of the AJAX function like this window.location.href = "https://cocktail-recipe-book-gabyguedezh.c9users.io/get_my_recipes"; (it also complained that the redirect was not secure). I tried to work around the redirect by simply doing render_template('my_recipes.html') but this didn't work either, it seems it has to be a redirect on the return for the route.
I'm new at web development and Flask, so I'm not sure how to use the snippet I found in other SO answers (such as this one where the accepted answer seems to be a general decorator I placed before all my routes, but that lead to a "too many redirects error", which was resolved vaguely in the comments and I don't know what it means).
I've been looking around for answers that I could use but I'm frustrated as most answers I've found assume working knowledge of Flask and most provide no concise examples on how to use the code (such as 1).
I would greatly appreciate some sort of direction here, I don't know how to proceed anymore.
I'm trying to get rid of a visual issue I got.
I have a ng-repeat displaying some stuff and a footer on my page.
The ng-repeat taking some time to display, I see the footer n my page before anything else and that is disturbing.
How can I force the footer to display only when something else like an ng-repeat has finish rendering on the page ?
ng-repeat is rendered with a list of value; that you propably get from a WebService.
add a $rootScope.myBool that is false at app start.
Update that valueto true within your $http call (or way to fill your ng-repeat array)
once your array is completed add a ng-show="myBool" to your footer to
prevent it from showing before your array is filled
It always better to create one service which shows loader icon full width when any ajax call or data loading is happening.
this is very normal scenario with angularJs SPA, that the page look distorted or footer coming first at page level, so better create one service which will enable full screen loader on the page when ajax call loads the data or ng-repeat is in progress and as things are completed same service will disable the full screen loader
something like this: to make loader service true before calling ajax and make it false as call finishes in success or error.
https://iamlalit.tinytake.com/sf/MTY5MDY2NF81NjM1Njgw
loaderService.toggle(true);
$http({
url: enumApp.url.apiUrl + Id,
method: "GET"
})
.success(function (data) {
loaderService.toggle(false);
})
.error(function (data, status) {
loaderService.toggle(false);
})
Environment:
Windows 8
Apache 2.4
ZF 1.12
PHP 5.4
YUI framework for the behind-the-scenes connection to the server
I am trying to carry out a very simple ajax/js combination where the user interacts with:
2 of 4 people found this review helpful. Was this review helpful to you? Yes No
When the user hits either yes/no the 2 of 4 should be updated through ajax/js. I have the following code in the init() method of my ReviewController (extends Zend_Controller_Action). Mind you, the view script that follows this action (feedbackAction) is /views/scripts/review/feedback.json.phtml
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('feedback', 'json')
->initContext();
When feedbackAction is executed an exception jumps out stating that it could not find feedback.phtml. This is telling me that AjaxContext is not, in effect, appending the "json" format. Why is this happening?
I read somewhere that the initContext() should be called inside the action. I tried it...same exception.
Then I tried using ContextSwitch, but it seems that it beats the purpose of having AjaxContext be a subclass of ContextSwitch. The code in the init() in ReviewController was replaced by:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('feedback', 'json')
->initContext();
This time, inexplicably, the exception does not occur, but instead the following is rendered: the header code (generated by my _header.phtml file called by my layout.phtml file). I don´t understand at all. I had understood (obviously not well) that "addActionContext"+initContext() DISABLED layouts if any was enabled. ¿?
EDIT
I figured out that it wasn´t html content form my _header.phtml file but from another .phtml file that was being rendered because of some actions I had added to my actionStack. Once this was taken care of, what was rendered was the following:
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Which is the variables placed in the $this->view being rendered as json thanks to ContextSwitch helper initiated at the init() method of my ReviewController(). When I say "this was rendred" is because I placed in the address bar the following url: http://localhost/PlacesforKids/public/review/feedback/format/json/id/1/helpful/1
which supposedly is the URL being sent by the YUI framework.
I say "supposedly" because in my javascript success function (being called back by the YUI framework when the ajax call is being executed successfully) I do the fowlling: alert(response), to print out the responce I am getting...and it prints out the whole shabang: html tags, headers...etc. I don´t know how that´s possible.
I thought then that I might be misusing the YUI framework, so I tried to change to jquery.js. To do so I copied the contect of this to a file named jquery.js and placed it under my /public/js directory. Here is the ajax call it´s making to the server:
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
});
Here is the HILARIOUS part of all, the action for my ReviewController is NOT being called whatsoever. Instead, the view that was last rendered is re-rendered, meaning it´s re sending the content generated by the view script called by the last action (which belongs to a different controller than ReviewController). I know it´s been re-rendered because in the action that´s the owner of that view script I added this:
if($this->getRequest()->getQuery('ajax') == 1)
throw new Exception ("WRONG controller's action being called");
But it never throws the exception.
EDIT I THINK I GOT IT but I need to know how to clean the baseUrl()
So I opened up the java console on my chrome browser so I could look up the actual http request that my reviewFeedback.js was making through the $.ajax() method. Funny thing, this is what I got:
Request URL:http://localhost/PlacesforKids/public/place/index/id/localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0
Request Method:GET
Status Code:200 OK
Accept:*/*
Referer:http://localhost/PlacesforKids/public/place/index/id/1
X-Requested-With:XMLHttpRequest
WHY in the world is $ajax() APPENDING the url I have as GET to the EXISTING url? It means that whatever url I am trying to generate through my $.ajax() is gettign APPENDED to my "referer". So, I only need to be to CLEAN it and start from zero, for the url I mean... How could I do that in zend framework? Any ideas?
Now if I enter the string in sUrl (localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0) directly onto the address bar in my broswer, it does as it is supposed to do, print out the variables in $this->view that have been set by ReviewController, and send them as json.
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Same problem I had with YUI framework. I´m going crazy.
I could really use the help, thank you.
You need to change the ajax request to asynchronous mode: async: true
Silly silly silly me. Here is the reason why $.ajax() was appending the made up url instead of sending a new one.
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
I was writing a GET without a leading "http://", which by default, caused it to append to the existing url.
sUrl was localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
and should have been http://localhost/PlacesforKids/public...
Though it still baffles me that ajaxContext did not stop layout rendering as it should have, making me use switchContext instead.
The ajax switch in zend 1.1x.x is only for the "special" html context (if memory serves) and you were trying to set it to a json context.
Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)