js/jquery Async Content Overwrites Page - javascript

ive ran into the following Problem and maybe someone can give me a little advice or a way around this. I have the following Problem:
A Partner of my Page provided me with a Code that i should use on my Page, which writes some Content to my Page that i really want.
Unfortunately this Content is only relevant to People living in a certain region.
So i am using the service of an ip-api which returns the region the current user is in and lets me work with that. This is done with a jsonp ajax call.
If the Person is in the right Region the Code should be executed, if he is not, it shouldnt.
The Problem is that the code to be executed contains a document.write. So if i call that code inside of the ip-api callback the document is allready loaded and the document.write will overwrite my page.
So the big Question is: Is there a way to capture the document.write output into a variable like with PHPs output buffer? Or maybe some way to overwrite the content of an iframe instead of the whole Page? Anything that prevents the document.write from overwriting the page and redirects its output into a part of my page would be sufficient.
Thanks for your time :)
PS: this is the code im talking about:
$.ajax({
url: "http://ip-api.com/json/",
dataType: "jsonp",
success: function( response ) {
if(
response["city"]=="Hamburg" ||
response["region"]=="SH" ||
response["region"]=="NW"
){
document.write("Some Content here");
}
}
});

Replace
document.write("Some Content here");
with
$('#my-container').html('Some content here');

Related

redirect to other html file with parameters

I want to redirect from a.html to b.html with a parameter for example array c[],i used something like location.href = "b.html"; but when i write something like console.log(c[0].name); in my .js i got nothing after the redirection to b.html!
thanks in advance for your help :)
$(".btn").click(function(){
location.href = "b.html";
//.. push of some elemts to the array elements
// .. try to show elements in b.html with console.log() for example
});
As commented before, once you are redirected, you are literally on a new page. So everything you had before is unloaded. ( And your script which is supposed to execute after setting the location.href is stopped )
There are several ways to handle data into the next page, but by far the most easiest one would be to use query-parameter in your URI. Check that out:
https://en.wikipedia.org/wiki/Query_string
You are limited by the size of data, the data is somehow visible, and it could be easily hacked, though - but it seems you are quite at the start of something anyway.(?)

Commenting System - Showing posted comment without page reload

working on a commenting system using PHP.
Everything works, the insert, the validation and also the ajax call.
Currently i am doing a .load() on the container that holds the page content.
However, this causes issues when trying to post comments again. The javascript doesnt work, some of the javascript functions linked with the comments also dont work and little things like that.
How should i be dealing with comments, every time a user posts one.
Like on facebook for example, you post a comment and the new one is just placed underneath the last.
The only thing i can think of i using .append() and appending the new comment to the list.
In my PHP page i could set a JSON return of the username, the comment, the users profile picture etc and then append all of that data back?
Otherwise is there a better method of simply 're-loading' the div container after the success ajax call?
Thanks, what i have works... but i want to be learning things the CORRECT way.
Craig.
You can use $.ajax to load new comments and use .append() or prepend() to insert the new comments in the container. If you wrap the call in a function you can call the function over and over (for instance every 2 seconds) to check for new comments.
If I remember correctly .load() will only execute when the element is ready after browser refresh.
What things are not working? Remember that events and data must be bound after succesful AJAX call. Meaning if you bound events to links when the page loaded they are obviously still in effect. But if you insert a link later on it does not have any events.
What I would normally do is something like this:
$.ajax({
url: 'ajax.php',
data: { 'parameters': 'yada yada' },
dataType: 'json',
success: function( data ) {
$('.links').unbind().click(function() { alert('hello!'); });
}
});
The reason for the .unbind() is that you will otherwise bind several events on the existing links - and you don't want that ;-)

Get text from body tag of another page hosted on another domain - javascript / Jquery

Suppose a webpage www.example.com/some.html hosed on server. Now I want to get the content inside body tag of that page from another domain. How can I do it? I tried to find solution, but no luck with that yet.
Here are some ways that I thought and found.
First one can get content of a tag from same site.
$.get("link.html", function(data) {
var html = $('<div>').html(data);
var content = html.find("div#some_div_id").html();
//do something
$("#Container").html(content);
});
use .get() to get html of a div in another page
I tried, but doesn't work for me. I think it's because of my cross domain request.
Second idea is using iframe. Wanna load the page into iframe and extract body tag. But can't find any solution regarding how can I detect the event that iframe completed loading the page? Or how can I get the content from an iframe loaded page?
Can anyone please tell me how can I get those content from the body tag in a simple way?? Is there any solution just like my first example? Please help...
This works.
var bodycontent;
$("<div>").load("link.html body", function (data) {
bodycontent = data;
});
If I was you, though, I would do it using something server-side. This is because many websites use Access-Control-Allow-Origin to block the files, and make you unable to access it. This is also a form of impersonation and hacking, so use it in moderation.
This is not possible without a server-side proxy to request the other site's content; Javascript is not capable of making cross domain requests due to the same origin policy. You can't do this with an iframe or AJAX, server-side proxy only.
try this
$.ajax({
url: "your_url",
data: dataToSubmit,
async: false,
success: function(response) {
$('.your_div').html(response);
}
});
you may also use load
$('body').load("your_url");
$.get("URL", function(data) {
data = data.replace(/\n|\r|\t/gmi,'');
/<body>(.*)<\/body>/i.test(data);
data = RegExp.$1;
});
If you want parse HTML,using regular expressions is better

Finding actual URL from <a href="#"

A page source snippet has the HTML:
Next
I know that the "#" is a placeholder that is handled by Javascript on the page. I believe the relevant Javascript snippet is:
function changepage(start) {
makerequest('/ajax/inventory_search.php', collectformvalues(start));
}
// do not flash the search options when using next/prev - just when the search is changed
function changepageforpagerlink(start) {
doEffectOnAjax = false;
changepage(start);
return false;
}
I need to know if there is a way that I can submit a URL and have the next page's page source returned. Is there a URL that is submitted at all in the above example?
My environment is VBA. I'm not using a browser, just communicating with the server. One thing I thought of is to mimic the "makerequest" function, but I don't know how to do that or if would even work. I know at the heart it's all just sending text to the server and receiving text back so I would think there is a way. . .
Bottom line is that I need to access the page source from the next page via VBA and not using a browser.
you can use JQuery to achieve this:
function changepage(start) {
makerequest('/ajax/inventory_search.php', collectformvalues(start));
}
changes to
function changepage(start) {
$.ajax({
type:POST,
url:"/ajax/inventory_search.php",
}).done(function(){
//do anything when it's done.
});
}

Alternative of this script in jQuery?

I use the following script to get the content of the remaining.php.
The drawback is that sometimes it doesn't work or it is kinda slow to display the text. Is there any other way of doing this ?
Thank you
$(document).ready(function(){
$("#SubmitButton").click(function (){
$('#remaining').load('remaining.php');
});
});
You could directly include the contents of remaining.php into the initial markup but make it hidden by applying display:none; style to the #remaining element. Then when the button is clicked simply show it:
$(function() {
$('#SubmitButton').click(function () {
$('#remaining').show();
});
});
Of course if you need to pass some parameters to the script which will depend on some javascript variables that are known only at the moment the button is clicked you will need to use AJAX as you are currently doing.
If "sometimes it doesn't work or it is kinda slow", the problem is probably the server you are using, not your javascript code.
The javascript code you're showing us here doesn't really do anything that could be slow, it only binds an event on a submit button. However, what could be slow is waiting for the answer from your web server when sending a request for remaining.php
From there, there is a thousand of reasons why your web server could be slow. Maybe you could post the content of your remaining.php file so we can see what is going on in there.
This isn't really a fault of jQuery, but the speed of return from your server. Perhaps there's a better way to handle it instead of fetching a full page?
For example, if your content request was only retrieving a message, you could return JSON from your server and have jQuery handle the data:
$(document).ready(function(){
$("#SubmitButton").click(function (){
$.post('remaining.php',
null,
function(data) {
// do stuff with your JSON result
});
});
});
When you're using .load(), you're sending a request to the server to get your content, which is why it can seem slow. I'm not sure why it sometimes won't work , but I would venture to guess that you may be clicking $("#SubmitButton") before $(document).ready fires.
Depending on your implementation, you may be able to refactor your application so that the text you want to display is pre-loaded on the page.

Categories

Resources