How to send Ajax request in pug template? - javascript

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).

Related

Ajax Not Loading PHP

I'm trying to load a PHP file into another PHP file on a click event through Ajax. I'm trying to do this to eliminate loading several modals I have on the page. It seems the PHP file is loading (in the console), but nothing is showing up.
Here's my javascript:
$("a#lightbox-open").click(function(e){
e.preventDefault();
$("body").addClass("noscroll");
$('section#lightbox').addClass("open");
$.ajax({
context: '#lightbox-holder',
url: '/template/lightbox.inc.php',
type: 'POST',
dataType: "json",
success: function(html){
alert("works");
}
});
});
In my main PHP file, I have a div #lightbox-holder that lightbox.inc.php is supposed to load into it.
context expects a (Plain)Object (as you can read in the api doc). Replacing '#lightbox-holder' by $('#lightbox-holder') will do the trick.
Working fiddle with the $() added versus non working fiddle representing your current code.

Ajax response - remove the scripts and styles

I have to make an AJAX call where I retrieve another page, completely. Then I would trim the html received to what I would like to see (styling wise) by removing or adding different stuff. As below:
$.ajax({
type: "GET",
url: "/booking-standard-mykad.html",
dataType: "html",
ifModified: true,
asnyc: true,
error: function() {
alert("Error");
},
success: function(data) {
data = $(data);
data.find(".somecssclass").remove();
//lots of other modifications
$('.book-now').html(data); //then I would display it here
}
});
Now the problem is, I don't seem to be able to remove the styles and scripts that are as well fetched in the head. I would like to keep some of the content in the head, what's below the head, in the body and in the footer.
What I have tried and failed:
data.find("title").nextUntil("script[src='http://thedomain.com/skin/frontend/smartwave/porto/js/porto.js']").andSelf().remove();
//removing whatever there is from <title> to a certain <script> fetched
As well, I have tried the load() function in jQuery, but since I have lots of JS functions in the footer and body that I would need, it didn't quite work. Hence I used Ajax.
Any thoughts on how to remove certain <scripts> , <meta> and <link> tags being fetched?
I solved this problem by fetching data to a third page using jQuery load(), removing whatever styles that I want, and then using an iframe to pull the data from that third page to my destination. All good and fast.

how to run javascript code that included through ajax process

I have a php page which has lot's of code of html and javascript inside it.Ihe other page use ajax to send an id to the first page and get the results and put it inside a div element. Now I want to run those returned codes which contains javascript and html codes.
How should that be done?
This is my ajax request to the first page:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "showing.php",
data: "s_id="+s_id+"&submit=true",
success: function(msg){
str=$.trim(msg)
document.getElementById('tabs-2').innerHTML = str;
document.getElementById("ui-id-2").click();
}
})
I think event delegation can solve your problem.
Like below:
Use $.on(). Instead of registering events on the element you register on a parent which will not be removed
Ex:
$('#tabs-2').on('click', '#ui-id-2', function(){
//do something
})

Is it possible to update jquery tab set

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.

How to open an html page in and html div?

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.

Categories

Resources