I'm using nodejs to develop a website that extract data from an API using ajax requests. I use templates, .hbs files (index.hbs, area.hbs etc.). My problem is that I want to make a navbar (with text links), but since I use templates its not that easy. I need to use ajax. I have made all the necessary routes, but I need help with the ajax request on the links. I have searched the internet for an answer, and tried a lot of different solutions, but nothing seems to solve my problem.
My navbar code:
<div id="navbar">
<ul>
<li>Companies</li>
<li>Area</li>
</ul>
</div>
Server.js route code:
app.get('/area', routes.goToArea);
Routes.js code:
goToArea: function (req, res) {
res.render('area');
}
I think something along those lines could work:
var url = "/area";
function area() {
$.ajax({
url: url,
type: 'GET',
Any help would be greatly appreciated!
This is how you bind click event and make an ajax request
$(document).ready(function () {
$('.navbar a').click(function () {
$.ajax({
'type': 'get',
'url': '/area',
'success': function (data) {
// use the data
}
})
})
})
Conceptionally spoken I would create partial layouts (or sections of html) which renders inside the global layout. This "Partial" should represend an Area.
I would also have a variable in the html (id or data-attribute) which represents the Area Identifier.
then your could request something like
http://myserver.com/area/tab1 or
http://myserver.com/?area=tab1
(depending how you want to structure your code / routing.
Then you whould request that partial via ajax and "Success" you would insert it into the Dom.
The docs here explain how to assemble the ajax call:
http://api.jquery.com/jQuery.ajax/
Here is a good read which might also help:
Express.js hbs module - register partials from .hbs file
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.
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
Right now, I have a webapp that uses the jquery ajax to make a call (with params that change from call to call via a form) to my backend and retrieve an xml file. I want to put the xml data into a file with a different extension for a private application.
Basically I just want the user to be able to click a button, and it automatically prompts them to "open or save" a file containing the returned ajax xml data.
I've dabbled with sending a raw http header using php, but I can't figure out how to get it to work.
I'm writing all of this in javascript and jquery.
The only thing the below code does is (1)Make the Ajax Call, (2)Write the XML into an HTML page, (3) open the HTML page.
var format = function() {
$("button#format").click(function() {
$("#form").submit();
$.ajax({
url: "find",
beforeSend: function (xml) {
xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
},
data: $("form#form").serialize(),
dataType: "html",
success: function(xml) {
xmlWindow = window.open("download.ivml");
xmlWindow.document.write(xml);
xmlWindow.focus();
},
error: function(request) {
$("#webdiv").html(request.responseText);
}
});
});
};
There is no need to force something like this into the AJAX paradigm, unless you need to play around with the data you retrieve before making it available for the user, then again, that should be able to be done in php. So I would do something like this:
<form id="format" action="download.ivml" target="_blank">
...
</form>
And in jquery modify the action like this
$('#format').submit(function(){
// tweaking the post data, otherwise this whole block is not needed.
return true;
});
Finally on my server use a .htaccess file to handle that weird URL download.ivml
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$ /path/to/where/I/process/the/request
not quite sure about the syntaxis of this last .htaccess file though.
Let's say you use the Embedly API and make the call in your application.js file:
$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
alert(oembed.title);
});
Now you have the hash oembed and can call, for example, ombed.thumbnail_url or oembed.title in the callback function. I want to know how you would save one of these elements in the call back function to your database.
Would the jQuery code look something like this:
$.ajax({
type: "POST",
data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_url'}
});
It looks like you just need to post the title and thumbnail_url back to your application using AJAX - http://en.wikipedia.org/wiki/Ajax_(programming).
The jQuery ajax api is very straightforward - http://api.jquery.com/jQuery.ajax/.