Jquery script doesn't work in jquery loaded page - javascript

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!

Related

How to get a DIV element from an external webpage in HTML file?

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.

Redirecting form submission to URL after sending the details to database

I am working on a popup newsletter signup. I already have the similar signup form in another page. I used the exact code and it works great. Once I submit the form, two actions has to happen.
Sending the form details to database
Redirecting to thank you page.
With the existing code(this is from a ecommerce website, I cannot manipulate the code), I can send the details to database - perfectly works fine, but
it is not redirecting to Thank You page, instead redirecting to the page hardcoded in the database(assigned to "action". Is there a way out?
This is the code.
<form name="MailingList" method="post" action="http://www.mywebsite.com/MailingList_subscribe.asp">
<input type="text" name="emailaddress" placeholder="Email Address" maxlength="100" size="28"> <br>
<input type="submit" name="Submit" value="Submit" width="260px">
</form>
Instead of this - http://www.mywebsite.com/MailingList_subscribe.asp, I would like to redirect to "www.mywebsite/thankyou.html" . If I assign www.mywebsite.com/ThankYou.html to "action" , then the form is getting redirected to Thank you page, but not sending the information to the database. I have to use HTML, I cannot call from outside file. I guess I need to use PHP, but I am unclear with the code.
Sorry my mind is all over the place, I guess I explained it clearly. Apologies if my question is unclear. Thanks
Give id to your form like formId and you can do this using jQuery,
Download the jQuery latest version from JQuery repo and then place the jquery.min.js file in your resources folder.
Updated
<script src="yourResourcesFolderPath/jquery.min.js"></script>
// above code will use the jQuery plugin online
// chances are that the file path might be wrong according to where you put the js file
// A simple way to try this is put your file in the same folder of your html file and then change above code to
// <script src="jquery.min.js"></script> change file name according to downloaded file name.
<script>
$(document).ready(function(){ // will run the below code after all html loaded
$('#formId').submit(function(){ // will be called upon form submission
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/MailingList_subscribe.asp",
context: document.body
}).success(function() {
// this will be called when you return from your server submit code
location.href = "www.mywebsite.com/ThankYou.html";
});
});
)};
</script>

Problems with event binding on dynamically created elements

I have code that is behaving one way on jsfiddle, one way on localhost, and another when uploaded to my website. I've been wrestling with the problem for a few days now. I don't know what tests or trial and errors I can run at this point.
This jsfiddle is working exactly as I want it to work.
http://jsfiddle.net/2ZLse/10/
When I insert this code into my project, and run it on localhost with WAMP, the javascript for the page does not work. The javascript is valid when run through jslint.
Stranger still, when I upload the exactly same files to my website, the javascript is functional, and I can even click on the watch button and render the form, but the nevermind button does not return me to the original state. I'm not receiving any errors on my cPanel.
When I replace
$(document).on('click', '.nevermind', function() {
$('#imagebox').html(imagebox);
});
with
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
The localhost will function the same as the website functions, with functioning javascript, but without a functioning nevermind button.
Below is the code, but let me tell you more about the rest of the page incase it's relevant. I'm using php. It's a .php file, bootstrap is loaded and working, jquery is loaded, and the javascript is run at the bottom of the page, not the header. There is ajax running elsewhere on the page, which works on the website but not the localhost, and I have the correct connect.php file for each. My best guess is that ajax has something to do with it.
What is the problem, or what tests can I run?
Here is the HTML
<div id="inputbox">
<form><button type="button" id="watchcontrol" class="btn btn-default">Watch</button>
</form>
<br>
</div>
<!-- images and continued input extension-->
<!-- imagebox also acts as control panel -->
<div id="imagebox">
ORIGINAL STATE
</div>
Here is the javascript.
var imagebox = 'ORIGINAL STATE';
var watchform = '<form action="post/watchpost.php" method="post">' +
'<input type="text" name="watchid" /><br>' +
'<input type="submit" class="btn btn-default" value="Contribute" />' +
'</form>' +
'<br><br><button type="button" class="btn btn-default nevermind">nevermind</button>';
$(document).ready(function(){
//control functionality
$(document).on('click', '.nevermind', function() {
$('#imagebox').html(imagebox);
});
$('#watchcontrol').click(function(){
$('#imagebox').html(watchform);
});
});
Event binding on dynamically created elements?
This question, while helpful, did not solve my issue. I believe my issue is separate from that one.
The following only binds event handler to the EXISTING DOM element:
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
which does not include what you append after clicking on #watchcontrol.
The following would work though, binding the event everytime when you create the dynamic element (even though I suggest that you free the element before removing it from the DOM):
$('#watchcontrol').click(function(){
$('#imagebox').html(watchform);
$('.nevermind').click(function(){
$('#imagebox').html(imagebox);
});
});
http://jsfiddle.net/2ZLse/11/

How to clear a server-side html file's content, from input type button

I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}

jquery form submit

I have a jquery fancyzoom box. In that box ,I have a contact form which sends an email on submission. But I am not able to call form submit function due to fancyzoom.
Code is like :
("req_quote.php")
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/fancyzoom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#popup1_link').fancyZoom({width:610});
$("#submit").css('cursor', 'pointer');
$('.reqfrm').submit( function(){
alert("hell");
});
});
</script>
<body>
<form class="reqfrm" id="frm">
<input type="text" name="name" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Above file is included in "index.php" which contains the actual link to open the form in fancyzoom box.
(index.php)
< a href="#popup1" id="popup1_link">< div class="blink">Request a Quote< /a>"
If I remove $('#popup1_link').fancyZoom({width:610}); then i get alert on submission otherwise it goes on form action directly.
Are you getting any JavaScript errors with the fancyZoom call in? Are you including the script file you need to use it? It's hard to say without seeing some more data, or a jsbin / jsfiddle.
The form is submitted in the fancybox js file.
As mentioned by Raul, you need to provide more info for us to help out. You could try any of these things:
See if you can reproduce this issue within a simple html file, that doesn't have any of the extra stuff that your current page may have. If the issue still persists, put it into jsFiddle and post the link here.
If you haven't already, install the Firebug addon for Firefox, and use it's console to check for any JS errors.
Have a look at the jsFiddle that I've created. Is this similar to what you are doing? Mine works wihtout any issues.

Categories