Ajax response - remove the scripts and styles - javascript

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.

Related

How to send Ajax request in pug template?

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

Cross-domain requests with jQuery Plug-In

i need to pull a small string from a diffrent site from a div with the class 'entry' (theres only one div with that class and the div doesnt have an id).
I learned about this plugin http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
But i somehow did not manage to install nor use the code to make it work.
I tried nothing but the code on the plugin page.
Where/How do i need to install the plugin? Where/How to implement the given code correctly?
Maybe a working fiddle sample would help :)
EDIT: I used this code
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
<script src="https://raw.githubusercontent.com/padolsey-archive/jquery.fn/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.ajax({
url: 'http://news.bbc.co.uk',
type: 'GET',
success: function(res) {
var headline = jQuery(res.responseText).find('a.tsh').text();
alert(headline);
}
});
});
</script>
And i use phase5 HTML editor, so theres no error thrown, any recommandation for a different editor?
The code just doesnt produce any result, the page loads and functions as normal but no alert is shown.
OK i found a solution, here is what i did:
Added header('Access-Control-Allow-Origin: *');
in die functions.php of the wordpress site i want to acess then i used the following ajax request to pull the content:
jQuery.ajax({
url: 'http://www.somesite.wordpress.com/',
type: 'GET',
success: function(res) {
var data = jQuery.parseHTML(res);
jQuery(data).find('div.class').each(function(){
jQuery('#destination').append(jQuery(this).text());
});
}
});
I tried all of this: Getting specific element from external site using jQuery / ajax and the last answer worked for me (its the same code mentoined above).
Unfortunately i dont know why or how this works and if this is the best way, probably not - still it works somehow so thats fine by me.
If anyone sees through this and knows a better/sleeker solution, it would be very welcome!

jQuery stops working after ajax loading

some info
I'm working on a webpage that can load data on multiple layouts, so user can choose which one is best. It can be loaded in a list or a cards like interface, and the data is loaded using ajax.
In this page I also have a notifier for new messages that the user received. The ajax function is new, and when page was loaded by the php scripts, the js script (that add a badge with the number of unread messages to a link on a menu item) was working ok.
I'm using HTML5, PHP, jQuery and a mySQL DB.
jQuery is imported onto the HTML using
<script src="https://code.jquery.com/jquery.js"> </script>
So it's a recent version.
the problem
Now, when I load the data onto the page using ajax, the js script won't work anymore. I had the same issue with another js script and I managed to solve it by using the delegate event binder.
But my unread messages updater runs on a time interval, using
<body onload="setInterval('unread()', 1000)">
the unread() js is quite simple:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
it calls a php script which grabs the unread msgs count from the DB and echo into a element that jQuery will point. Hope I'm being clear.
The problem is that I cannot figure out how I would call a timed event using delegate. Without much hope I've tried
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
That didn't work.
I read many posts about js stop working after changes in the DOM, but, again, I couldn't figure out a way to solve that, nor found a similar question.
Any help or tips would be highly appreciated.
EDITED to change second php script's name
2nd EDIT - trying to make things clearer
I tried the way #carter suggested
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
the ajax_countNewMsgs.php script connects to the DB, fetch the unread messages, and echoes the number of unread messages.
If I try to apply the ajax reponse to another element, say, the <body> the results are as expected: at each 1 sec , the body html is changed. So the function is working.
As I said, none of my JS changes the #menu_item. Actuallly this element is part of another php scritp (menu.php) which is imported to the top of the page.
the page structure is this way:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
Even though the elemente is not being rewritten js cannot find it to update it's value.
It's not the full code, but I think you can see what is being done.
$(document).on('ready()','#menu_item', function () {
is an invalid event listener. If you wanted to be made aware of when the DOM is ready you should do this:
$(document).ready(function () {
However I don't think that is actually what you want. Your function unread will fire repeatedly but it attaches an event listener everytime. Instead if you want to make an ajax call every so many seconds after initial page load, you should do something like this (dataType property could be html, json, etc. pick your poison):
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
remove that on your unread function:
$(document).ready(function(){
WHY?
The Document is already "ready" and this document state will only fired 1x - After that the "ready state" will never ever called. Use follwing syntax:
jQuery(function($){

Access DOM elements on HTML page loaded with AJAX

Im currently struggling with an AJAX related problem on a website.
The goal is as follows:
There is a "simple" HTML page containing some links and content.
If you click on a link I want to open the file that gets includes with the link (from href) within a new div overlayed to the page. The content from the page is of course loaded with AJAX into the new div (the overlayed one).
Within this new overlayed div I want to add some JS code which in general already works.
The problem anyway is that the DOM elements within the page loaded per AJAX cannot be accessed in a way that is comfortable to work with, in my specific case.
I got following piece of code so far:
$$('.add-exercise').addEvent('click', function(e) {
var request_exercise_add = new Request.HTML({
'method' : 'post',
'url' : e.target.get('href'),
onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I know I can access the elements returned within responseElements but the logic on the included website is somehow quite complex and therefore it should be
possible to add the JS within the HTML code in the dynamically loaded page.
Notice that the JS also cannot be added to the head section because it would not know the elements that are loaded after the dom-ready event.
have you tried iframe ?
or the website that you are trying to add does not have PPP cookie and AllowContentInIframe .. ?
If you want to add the script inside the ajax request you need evalScripts: true and you should remove the quotes around the request options.
$$('.add-exercise').addEvent('click', function (e) {
var request_exercise_add = new Request.HTML({
method: 'post',
url: e.target.get('href'),
evalScripts: true,
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I don't know what is the content of the response but you might also want to use Mootools's .set() instead of innerHTML to append new elements (if you are not doing that yet). Maybe worth to check Dimitar's answer here about that.

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