I have created a simple page with a button on the center.
Now I want that when I click the button then the current page is completly rewritten with new HTML and Javascript code loaded from the server.
How can I do this with ajax ?
Suggestion: post with a normal form and reload the page. If you're reloading the entire page anyway, you're doing away with all the benefits of AJAX anyway, best to reload the entire page, for example:
<form action="otherpagr.html">
<input type="submit" value="Click me" />
</form>
AJAX is for replacing part of a page to reduce the overhead...but if you're replacing say the entire <body> it's easier to just load the page you're going to.
Nick is right with what he says, but if there's no other way:
$('a').click(function() {
$('body').load("test.html");
});
EDIT: Making sure load only fetches content inside the <body> Tag from the remote adress. For me it didn't work to fetch only the <body> tag by defining body => load('test.html body')
To animate the page you could do something like this:
$('a').click(function() {
$('body').load("test.html", function() {
$(this).hide().fadeIn(2000);
});
});
but then I suggest to implement at least one wrapper-element.
Related
Apologies in advance if this question has been asked earlier. I did find some similar questions on web but I couldn't figure out the answer still. You can say I have never dealt with anything beyond basic HTML. So any help would be appreciated.
I have a HTML file (Say text.html) only for personal use. In the file, there will be an input box for entering text and a submit button. I want that if I clicks on submit, it opens a particular hyperlink from an external webpage based on the input text. I guess it's like "I am feeling Lucky" of Google.
Example: If the user enters "Test" and clicks on Submit, it should open the second result from the page "https://www.google.com/search?q=test"
Here is my HTML:
<!DOCTYPE html>
<html>
<body style="background-color:beige">
<h1 style="text-align:center"><font size="14">Test</font></h1>
<style type="text/css">
</style>
<form id="form">
<div align="center" style="vertical-align:bottom">
<input type="text"
value="Test"
id="input"
style="height:50px;width:200px;font-size:14pt;">
</div>
</form>
<TABLE BORDER="0">
<TD><button class="button" id="button01">SUBMIT</button></TD>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
</script>
Also, here is the example of the div element from the page on which the hyperlink I want to open is on:
<div id="XYZ" class="contentEditValue" style="float:left;width:180px;">
2nd Result
</div>
I have read that it can be achieved with PHP or Jquery and all but they are not something I have ever worked on. Thank you very much in advance for any help!
Appreciate any other alternatives as well.
You shouldn't be able to do that because of security. If that (reading content from iframes, other browser windows...) would be possible, an attacker could add JS keylogger to your internet banking login or read your messages on Facebook. CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is used to block these requests and if the website doesn't say explicitly that you are allowed to do something with its content, most browsers won't allow you that.
You have are missing a }); to close the ready() function
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
});
</script>
Here's a basic example of how to do this in PHP.
Taking JavaScript/JQuery out of the picture, let's just say you have a basic form:
<form>
<input type="text" value="Test" name="input">
<input type="submit">
</form>
Without specifying action or method attributes on the <form> tag, the form will make an HTTP GET request to the URL of the page it is on, so for this example the PHP code will be on the same page as the form. Here's a more detailed description of sending form data if you're interested.
Now that you have a way to pass the input to the PHP script*, there are three basic parts to this problem.
Make a request to the page you want with a query string including your input
http_build_query is an easy way to construct a properly encoded query string to use with your request. For this example we'll use file_get_contents to make the request. There are other ways to do it, including cURL, but let's keep it simple.
$query = http_build_query(['q' => $_GET['input']]);
$page = file_get_contents('http://www.example.com/?' . $query);
I'm not using Google for this example because it's a bit more complicated to find the right links in the response and follow them. (Partially because they don't really want you to do it that way.)
Find the link you want in the response
Don't try to find the link in the response with regex. You'll have problems with it, come back to Stack Overflow to try to solve them, and people will tell you that you shouldn't be using regex, so just skip that part and use a DOM parser.
$doc = new DomDocument;
$doc->loadHTML($page);
$links = $doc->getElementsByTagName('a');
$url = $links[0]->getAttribute('href');
I used getElementsByTagName() to find links, but if the page is more complex an xpath query will work better. Also, I used the first link ($links[0]) because example.com only has one link. $links[1] would get you the second link if it existed.
Follow the link
header("Location: $url");
exit;
If everything goes well, you'll end up where you want to be. But there are a lot of things that can go wrong. If you're requesting a resource that you have no control over, it can change at any time without any advance warning to you, so your code that finds the link may stop working. You may get blocked from making requests. Scraping links from sites like this violates the terms of service on many sites, so check that out beforehand. You may find that the site offers a web API, which should be a much better way to access its content than this.
*You don't really need a form for this; you can just pass the input parameter in the URL to your page.
I have tried to search for similar questions, but I could not find anything, so if you know any similar question please let me know.
Let me explain what Im doing:
I have a script that validates forms in a js file, It works fine in any page with a form I have, the problem is that when I load a form using jquery it just doesn't work, I have tried using the next line in different places: Header, footer, etc
<script src='myFile.js'></script>
By far the only thing that has worked for is writing the line of code above inside the form itself.
I think it has something to do with the form that the DOM works, I have also tried using and not using it.
$(document).ready(function (){ //code});
It only will work when I add the script tag with the src attribute inside the form itself.
It would not represent a big problem for me to add the script tag to any form I load using jquery but it's a little bit more of work an unefficient, and also when I add the script tag to any form and load it using ajax I get the next console warning that only goes away when I remove the script tag from the form file:
jquery-3.2.1.min.js:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Here is a part of my code:
<!--home.html-->
<div id='formFrame'>
</div>
<script>
$("#formFrame").load("html/loginForm.html");
</script>
<!--end of home.html-->
<!--loginForm.html-->
<form action='somePage.php' method='post' id='loginForm'>
<input type='email' name='email' placeholder='email'>
<input type='password' name='password' placeholder='password'>
<input type='submit' name='submit' value='Login'>
</form>
<script src='js/validate.js'></script>
<!--end of loginForm.html-->
<!--validation script (validate.js)-->
$(document).ready(function (){
$("#loginForm").submit(function (e){
e.preventDefault();
alert("Working");
});
});
Thanks for spending some of your valuable time on reading this, I appreciate it a lot!
As I can't comment, putting my comment in answer!
I am not sure what you have written in validate.js, but if you are using jQuery unobtrusive validation, then you must rebind the validators to the form if you are loading it dynamically.
I was facing same issue in ASP.NET MVC while loading forms using AJAX. I am not sure will it help you or not but below is the code.
$("#formFrame").load("html/loginForm.html", function(){
var $form = $("formSelector");
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
});
Well guys I found a solution:
As there seems to be a conflict when loading an external page using ajax (.load) I opted to use php instead of javascript which worked fine:
I removed the next code
<script>
$("#formFrame").load("html/loginForm.html");
</script>
And added the next to the div where I want to load my content:
<!--home.php (changed html to php)-->
<div id='formFrame'>
<?php
require 'html/loginForm.html';
?>
</div>
I would have prefered to use the load method from ajax to avoid loading the content befere the user could request it, but by far that's the only solution I have been able to think about.
Thanks to everybody for your help it was really helpful!
I've got a javascript for drawing a chart. I get my information out of my MySQL base. And I got 3 different buttons to get the different information out of the database.
My problem now is, I get the information out of my database, it shows it in the chart but when it shows the information it refreshes the page.
Is there a way to show the information after my page is refreshed? I actually tried to use the window.onload but that doesn't give me the wanted result.
in php I use the following code to get the info from my MySQL DB:
if(isset($_POST['btnProduct']))
{
....
}
in html it's like this:
<div class="content">
<form action="" method="post" enctype="multipart/form-data">
<input type="submit" name="btnProduct" id="btnFilterProduct">
</form>
</div>
And in JS I use this code:
<script type="text/javascript">
window.onload = function()
{
document.getElementById('btnFilterProduct').onclick = function()
{
....
}
}
I know the PHP needs to refresh to get the data. and Javascript doesn't. But can I change the order? Or is there a way to change my JS to let it load AFTER the page is refreshed?
To stop the page reload, modify your onclick function to be:
document.getElementById('btnFilterProduct').onclick = function(event) {
event.preventDefault();
...
}
event.preventDefault stops the default behavior of the event, which in this case is to refresh the page since you have an empty action. Another option would be to not use a form. Just use the <button> element instead.
Really unsure about the title question. Feel free to suggest. :)
Hi guys! I created a very simple code, that would represent my web.
Here is my home page:
<html>
<script type="text/javascript">
function getPage(linkPage,variables,divName){
$.get(linkPage + "?" + variables,function(data){$(divName).html(data);});
}
function show(){
//functionName("path","data","idName");
getPage("AjaxPages/hi.php","","#container");
}
</script>
<body>
<div id="container">
First Name<input type="text" />
<input type="button" value="next" onClick="show();"/>
</div>
</body>
</html>
Basically, it ask for information, Name for example. When the button NEXT is click it will call a javascript function that will call a certain page or the NEXT PAGE that will load on the div with the Id Container.
NEXT PAGE
On the next page, it will then ask another question, like Last Name for example. But then, I want to go back to the previous page to make same changes.
HERE is the code:
<script type="text/javascript">
function show(){
ajaxgetdata("index.php","","#container1");
}
</script>
<div id="container">
Last Name<input type="text" />
what to make changes on the previous page?<input type="button" value="back" onClick="show();"/>
</div>
When button back is clicked, it will just call the previous page, but will not include the text that you input on the textbox.
I know that it happens because it just call the page..
Is there a way? that when back button is clicked, it will reload the previous page, with all the contents/inputs.
:) :( :'( :/ :|
Don't load any additional pages. Do everything with AJAX.
If you don't want, some server-side script may help :D
If you can use HTML5 in your site, you can take a look at the History API which can handle navigation and fires a "popstate" event, to which you can pass data.
There's a good example here:
http://diveintohtml5.info/history.html
You could do something like this:
window.addEventListener("popstate", function(e) {
if(!e.state || !e.state.firstName) {
return;
}
document.getElementById('firstName').value = e.state.firstName;
});
That even will trigger everytime you go back or forward, and you could just organize some function or array with the information you need.
Hope it helps.
When I click the #screenrId, it submits the default data without having time to add the new data the user inputs. How to wait to append the data until after the form input field data has been added?
http://jsfiddle.net/XVCVE/1/
<script type="text/javascript">
$(document).ready(function() {
Screenr.Recorder( { subject:""}).appendTo("screenrId");
});
</script>
<form>
<h4>Subject <input name="subject" id='subject' type="text" ></h4>
</form>
<div id="screenrId" ></div>
I am trying to add the form data to the screen.recorder function before it appends it? Screenr.Recorder( { subject:""}).
Pretty sure I just fixed it: http://jsfiddle.net/XVCVE/3/
The problems:
The "javascript" section in jsfiddle assumes raw javascript, no <script> tags, so I moved that code to the top.
You had a very strange way to make sure the correct HTTP protocol (HTTP or HTTPS) was used to load the 3rd party library, when the browser will do that automatically if you just don't write the http: or https:.
After that, the button appeared after a slight delay.