I have a jquery tab set:
<div id="tabs">
<ul>
<li>Mileage Log</li>
<li>Trips</li>
</ul>
<div id="tabs-1">something</div>
<div-id="tabs-2">something</div>
</div>
My content on my tabs fires some javascript code that posts form data (I included that code). The problem is that I would like the tab element to refresh so any new content can be shown. Is there a built-in way to refresh the tabs using the "success:" option. I am currently using "location.reload();" but it just refreshes the whole page. Not ideal.
Thanks.
My Javascript
<script>
$(document).ready(function () {
//Submit form to add record.
$('#addmileage').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $('#addmileage').serialize(),
type:'POST',
url:'actionpages/add_trip.cfm?ticketid=<cfoutput>#url.ticketid#</cfoutput>',
success: function(){
$('.success').fadeIn(200).show();
location.reload();
$('.error').fadeOut(200).hide();
}
});
});
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'POST',
url:'actionpages/delete_trip.cfm',
success: function () {
$('.successTab2').fadeIn(200).show();
location.reload();
$('.errorTab2', $row).fadeOut(200).hide();
}
});
});
});
</script>
The only way I think you could achieve this, is to have the server-side functions you're calling in AJAX, return a block of HTML which you could inject into the of the tab you want to reload. And if you're going to do that, you'll need to put the functions in a CFC instead of the CFM page you're calling now.
So, you would generate the way you're doing now to build the initial page, but save the generated HTML as a string and then return it to the jQuery AJAX call.
As just a really bare-bones example:
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'post',
dataType: 'json',
url:'actionpages/actions.cfc?method=deleteTrip&returnformat=json',
success: function (result) {
$('.successTab2').fadeIn(200).show();
$('.errorTab2', $row).fadeOut(200).hide();
$('#tab2').html(result);
}
});
Then on the server you'll need an actions.cfc with remotely accessible functions:
<component>
<cffunction name="deleteTrip" access="remote">
<cfset newHTML = "<h1>This is new HTML!</h1>">
<cfreturn newHTML>
</cffunction>
</component>
I've put everything into JSON format, just because I always use JSON. :)
Not sure how familiar you are with CFCs, returnformats, etc. But hopefully this is a push in the right direction.
You need to refresh the tabs in the success function using DOM Manipulation. It may be the case, that your scripts like actionpages/delete_trip.cfm have to return new information which you need to refresh the tabs (for example in the JSON format).
Some notes:
The function location.reload(); may reload the page from the browser cache. Use location.reload(true); if you do not want this behavior.
$('.successTab2').fadeIn(200) should be enough (.show() is not needed). You also do not need the .hide() function.
Related
I would like to send Ajax request in pug template file.
form#payment-form()
section
label(for="amount")
input#amount(name="amount" type="tel" min="1" placeholder="Amount" value="10")
script(src="scripts/jquery.js")
script.
(function () {
var amount = $('#amount').val();
$.ajax({
type: "POST",
url: "/posturl",
data: {'amount':amount},
success: function(){},
dataType: 'json'
});
})()
But it doesn't work, how to do it?
I want to know how to send ajax request in embeded javascript of pug file
To me there seems to be two issues
You have put unnecessary tabs in your function under (function (){
You need to use document.ready to ensure that HTML content is
ready. You can avoid this if you don't really care for DOM once you have the response
check a working example below
doctype html
html
head
script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
script.
$(document).ready(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
body
#div1
h2 Let jQuery AJAX Change This Text
Here there is no problem with your pug template (maybe just you can remove ()after #payment-form() because it is empty and it's not a mixin). But with your JS, you send the AJAX request immediatly, you should bind it to an event (click on a button, keypress on an input, etc.). Then you have to be sure you put your lib jquery.js in a directory you can access from your browser with scripts/jquery.js. If it's still not work after this change please report more precisely your error (open the console to get the messages, get us the behavior you expect and the behavior you get).
I have a cshtml page that has a link, and a div to display some content.
<a href="#" onclick="Show_New_Page('#First_Div')>My Link</a>
<div id="First_Div">
#Html.Partial("General_Page") <- This is the default page that gets displayed on load.
</div>
When you click on the link, the javascript function Show_New_Page gets called and the string '#First_Div' gets passed as a parameter. I pass the name of the div I wish for the ajax in Show_New_Page to put its success value. That function looks like this:
function Show_New_Page(div) {
$.ajax(
{
type: "POST",
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
success: function (result) {
$(div).html(result);
}
});
}
When you click on this link in Internet Explorer, the new page gets displayed fine with no issues. However, when you click on this link in FireFox, the entire page turns white and never successfully loads.
There are plenty of posts about issues with Ajax and different browsers, but I was unable to see one that helped me. Any hints or tips I can try are much appreciated. I am very unsure of why this is happening, so if I have left out any information I will certainly do my best to provide it.
There seems to be a missing closing ) when you are calling the Show_New_Page function. Also it's recommended to return false from click handlers to cancel default action:
My Link
Also you might prefer to give this anchor an id:
My Link
and then unobtrusively AJAXify it in a separate file to avoid mixing markup with javascript:
$(function() {
$('#myLink').click(function() {
$.ajax({
type: 'POST',
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
context: { id: $(this).data('id') },
success: function (result) {
$(this.id).html(result);
}
});
return false;
});
});
The issue here was the fact that my ajax views that were being passed down after clicking on a link were using document.write() statements. I have learned that this is strange to do after the page has already loaded. I've moved these statements up to the files that were not being loaded with ajax, and that fixed the problem. Thank you to everyone who commented and suggested ideas to me. It was the investigation of these ideas that lead me to the core issue!
The lesson: be careful with excessive document.write() statements in firefox!
So I use the following code to manipulate my 'login' form so that it submits it, to the url of action="" and the data responded goes into id specified by target="". The submit method is specified by method=""
I like this. It's neat. But I was wondering if there was a way of having a script that meant that all forms were submitted through Jquery, without having to re-write this code for every form every time. That's just messy.
Much appreciated!
<script type="text/javascript">
$(document).ready(function(){
$("#login").submit(function(){
var thistarget = this.target;
$(thistarget).html('Submitting...');
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
error: function() {
$(thistarget).html("Form failed to submit");
},
success: function(results) {
$(thistarget).html(results);
}
})
return false;
}
);
});
</script>
Sure, just replace "#login" with "form". It will then affect all forms that currently exist on the page (but not future forms).
$("#login").submit(function(){...
For future forms AND current forms, you would need event delegation.
$(document).on("submit","form",function(){...
If I were you I'd use the $.post method of Jquery. http://api.jquery.com/jQuery.post/
But answering your question and as Kevin B said: change #login by form
The question might be a little misleading as I don't want to know how to open a html document in a div ,but I asked the question as I am currently facing a problem where I can't replace the html file which I have already placed in a div
I have already placed a html file in a div using ajax like this:
$.ajax({
url: 'calender.aspx',//this is html.aspx file
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);//mainBar is the div
}
});
this file gets placed on page load i.e document.ready function ,till here everything is fine.....my trouble starts when I want to replace the file,what I do is call a javascript function say replaceFile() on button click and write the same code to replace the file (changing the url of course)
like this
function replaceFile()
{
$.ajax({
url: 'Another.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
}
but this doesn't work,please help me out!
I guess your binding is not working when you try to click on the content you loaded via ajax . So you might want to change the binding of onclick from
$("#someButtonId").click(function(){
replaceFile();
});
to
$(document).on("click","#someButtonId",function(){
replaceFile();
});
jQuery on works with current and future elements.
with this function you will load the page into the element named result
.load( url , data, complete(responseText, textStatus, XMLHttpRequest)] )
function replaceFile(url)
{
$('#result').load(url, function() {
alert('Load was performed.');
});
}
replaceFile('htmlfile.html');
You can load this in Firebug and set a break point at $(".mainBar").html(data); to make sure it's being called. You don't have a failure handler, so it's possible that it's actually receiving an HTTP failure code, not a success code.
I'd also look at the network traffic under the Net tab to see what the request/response looks like. That's an easy way to find out what is really going on with most AJAX calls. IE9 has similar developer tools if you want to use it and not Firefox or Chrome.
I was wondering what the best way was the handle creating a generic javascript function that makes an AJAX request and calling it with 'onclick', keeping in mind I need the loaded ajax results to still work with this function. Also, I'm using JQuery and PHP. Something along the lines of:
Like Post
<script>
function postLike(post_id){
$.ajax({
async:true,
dataType:"html",
position:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain\/likes\/like\/"+post_id
});
return false;
}
</script>
Doesn't seem to work for me though.
Thanks!
I'm not sure what your problem is, but this is how I would handle it. Note that this avoids the issue when the post id is alphanumeric since it appends it to the href and extracts it from there. Note that the it starts hidden and is displayed only if javascript is enabled (which is required to make it work anyway).
To find your problem you should consider adding an error handler and using Firefox/Firebug to view the requests (and responses) as they are made.
<a class="like" href="#<?php echo $post_id; ?>");" style="display: none'">Like Post</a>
<script type="text/javascript">
$(function() {
$('.like').show().click( function() {
var post_id = $(this).attr('href').replace(/^#/,'');
$.ajax({
async:true,
dataType:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain/likes/like/"+post_id
});
return false;
}
</script>
An alternative to support both javascript/non-javascript enabled browsers
Note: your backend code needs to be able to distinguish between AJAX and non-AJAX requests. Note you can do this using the X_REQUESTED_WITH header (HTTP_X_REQUESTED_WITH) added by jQuery when making AJAX calls. It is possible to spoof so be careful how you use this check -- like not basing any authentication or authorization decisions on it. When you get an AJAX request, just return the HTML snippet. For non-AJAX you'll need to render the entire page again.
<a class="like" href="/domain/likes/like/<?php echo $post_id; ?>");">Like Post</a>
<script type="text/javascript">
$(function() {
$('.like').show().click( function() {
var url = $(this).attr('href');
$.ajax({
async:true,
type: 'post', // technically it changes data so post is RESTful
dataType:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: url
});
// cancel the default link action so we don't get two like's
return false;
}
</script>
The best way is binding functions to onclick (or .click in jQuery) event by jQuery .bind, .live or .delegate functions.
First of all if you are using jQuery, you don't need to use onclick attribute of anchor tag(it feels very obtrusive). try this syntax:
<a href="#" id="postLike" <other attributes>>Like Post</a>
<script type="text/javascript">
$('#posLike').click(function(){
$.ajax({
async:true,
dataType:"html",
position:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain\/likes\/like\/"+post_id
});
return false;
});
</script>
Here is what I normally do to fix this problem:
In your PHP, when you need to loop out the posts and generate the links, assign unique ids for the anchors, like this:
foreach ($posts as $post) {
echo "<a href='javascript://' class='like-anchors' id='like-post-{$post['id']}'>Like Post</a>";
}
Then in your JS code, you can do this:
$(document).ready(function() {
$('.like-anchors').click(function() {
var id = $(this).attr('id').substring(10);
$.get("domain/likes/like/"+id, function(data) {
$('#post-'+id+'-like').html(data);
});
});
});
Note
You are not making use of post or any advance Ajax functions. $.get should be enough. Feel free to comment on this.
Using href="javascript://" because I don't want the browser to scroll to top
Even better, you can just assign a global id to the wrapper div, so you won't exhaust your ids. Says if I have post, content, and like button, I would do this:
PHP
<?php foreach($posts as $post): ?>
<div class="post-body" id="post-<?php echo $post['id'] ?>">
<div class="post-content"></div>
<div class="post-controls">
Like This Post
</div>
</div>
<?php endforeach; ?>
JS
$(document).ready(function() {
$('.post-like').click(function() {
var parent = $(this).parent().parent();
var id = parent.attr('id').substring(5);
$.get("domain/likes/like/"+id, function(data) {
parent.children('.post-content').html(data);
});
});
});
There are many ways to complete the task. These are just my 2 cents
Cheers