JavaScript not run on onsubmit event - javascript

To learn about web programming, I'm trying a simple html/javascript/php "product search" page. Here is the index.php file:
<html>
<head>
<title>Product Search</title>
<script type="text/javascript">
function mySubmit() {
alert("submitting...");
var product_type = $('product_type').value;
$.post('product_search.php', { product_type: product_type }, function (data) {
alert("result = " + data);
$('body').html(data);
}
return false;
}
</script>
</head>
<body id="body">
<script type="text/javascript">
mySubmit();
</script>
<form class="form" id="myform" method="post" onsubmit="javascript:return mySubmit();">
Product Type:
<input id="product_type" type="text" name="product_type"/>
<br/><br/>
<input id="submit" type="submit" value="Submit"/>
</form>
</body>
</html>
and the product_search.php file is very small:
<?php
$product_type = $_POST["product_type"];
echo "<h1>$product_type</h1>";
?>
The problem is that it seems like the onsubmit event is never called for the form. I thought it was a JavaScript problem (as in, not allowed to run), but if I run an alert instead of calling mySubmit() when the onsubmit event is called, it works!
Also, am I wrong in thinking that the JavaScript just under the <body id="body"> should be run? It is never run either.
So, for those who didn't read all that: why is my JavaScript function not being run when the onsubmit event is fired?

I get the following parsing errors when I run your code:
Uncaught SyntaxError: Unexpected token return
Uncaught ReferenceError: mySubmit is not defined
You are missing the closing ) on your $.post call, which is breaking the parser. Once you fix that, you'll get the $ is undefined error until you reference jQuery.
http://jsfiddle.net/Z6hJK/

<script type="text/javascript">
mySubmit();
</script>
above function is called but when it is called, even document.getElementById('product_type').value gives error (which might not be enabled on your browser to catch) as it product_type turn out to be null as javascript in body gets executed before browser has fully rendered the page. The moment it is getting called, product_type is not yet rendered.
On click also your function is getting called, but this time may be it is failing as you do not have reference to Jquery. include one.

Related

JS Error: Element is not attached to a Document

Am trying to convert div to image using html2canvas lib , but am keep getting that error
html2canvas.min.js:20 Uncaught (in promise) Error: Element is not attached to a Document
at html2canvas.min.js:20
at html2canvas.min.js:20
at Object.next (html2canvas.min.js:20)
at html2canvas.min.js:20
at new Promise (<anonymous>)
at a (html2canvas.min.js:20)
at Vs (html2canvas.min.js:20)
at html2canvas.min.js:20
at HTMLInputElement.<anonymous> (index4.html:18)
at HTMLInputElement.dispatch (jquery-2.2.4.min.js:3)
I not understand what's wrong with my code , when i run the code on jsfiddle it not give me any error when i run it on my local system it give me error.
code
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" ></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<div id="phone">45454565756677</div>
<div id="out_image"></div>
<input type="button" value="Data to Image" id="data_to_image_btn" >
<script>
$(function() {
$("#data_to_image_btn").click(function() {
html2canvas($("#phone"), { // no error with : document.getElementById( but nothing is rendered
onrendered: function(canvas) {
console.log('done ... ');
$("#out_image").append(canvas);
}
});
});
});
</script>
</body>
</html>
Try this:
html2canvas($("#phone")[0]).then((canvas) => {
console.log("done ... ");
$("#out_image").append(canvas);
});
The two changes are: pass the first element of the jquery selection to html2canvas, rather than the selection itself. That gets rid of the error ... but for something to happen it seems that you need to treat the call as a Promise, rather than pass an onrendered callback (that's the second change)

How to convert JavaScript variable into PHP through ajax

its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.

Browserify - Bundle loads, but doesn't work afterwards

Before you ask, yes I've been using Browserify multiple times, but for some reason it just won't work this time.
The problem:
When I load up the website, bundle.js will only be executed once, then be ignored for the rest of the time. - Require is not the problem, since I tried to Console.log some require code, which worked, but afterwards, anything done by the user won't be executed.
As you can see in my code, I'm trying to execute registerHref() onclick of my button, which works when I'm not using bundle.js, but as soon as I'm doing this with my bundle, it's like it's being completely ignored. I will get an error which says: Uncaught ReferenceError: registerHref is not defined at HTMLButtonElement.onclick - But when I try to console.log the function on window.onload - it works as it should.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="bundle.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="header" style="border-style: solid; text-align: center;">
<button id="register" onclick="registerHref()">Register</button>
</div>
</body>
</html>
My Javascript:
function registerHref() {
window.location.href = "./register.html"
}
What I did:
I made my bundle using: browserify main.js > bundle.js <- Usually works fine
The problem is that after the code gets compiled the function isn't attached to the window object but instead is executed within a different scope.
You have basically two options here:
Attach the registerHref function to the window object (not recommended):
function registerHref() {
window.location.href = "./register.html"
}
window.registerHref = registerHref;
Create an event listener in your JS code and remove the onclick attribute from your HTML (recommended):
function registerHref() {
window.location.href = "./register.html"
}
document.getElementById('register').addEventListener('click', registerHref);

Object has no method 'dialog'

I'm getting this error:
Uncaught TypeError: Object [object Object] has no method 'dialog'
This is my relevant HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/Scripts/modernizr-2.0.6-development-only.js"></script>
</head>
<body>
<div id="deleteConfirmationDialog" title="Confirm Withdrawl">
Are you sure?
</div>
<div class="appl-appliedfor">
<a class="deleteLink" href="/Applicant/WithdrawApplication/2">
<img class="appl-withdrawApplication"
src="/Content/Images/Delete.png" alt="Withdraw Application" />
</a>
</div>
<script src="/Scripts/Prime/jquery-1.8.2.min.js"></script>
<script src="/Scripts/Jqueryui/jquery-ui-1.9.2.custom.min.js"></script>
<script src="/Scripts/OnBoard/jquery-form-min.js"></script>
<script src="/Scripts/Prime/bootstrap.min.js"></script>
<script src="/Scripts/Prime/json2.js"></script>
<script src="/Scripts/Prime/selectivizr-min.js"></script>
<script src="/Scripts/Prime/jquery.cookie.js"></script>
<script src="/Scripts/Prime/jquery.maskedinput-1.3.min.js"></script>
<script src="/Scripts/OnBoard/OnBoardAll.js"></script>
<script src="/Scripts/OnBoard/ApplicantAll.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/MvcFoolproofJQueryValidation.min.js"></script>
<script src="/Scripts/mvcfoolproof.unobtrusive.min.js"></script>
<script src="/Scripts/jqueryui/jquery.ui.dialog.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#deleteConfirmationDialog').dialog({
autoOpen: false,
modal: true
});
});
$('.deleteLink').click(function(e) {
$('#deleteConfirmationDialog').dialog({
buttons: {
"Yes - Withdraw Application": function() {
$(this).dialog("close");
},
"No - Do Nothing": function() {
e.preventDefault();
$(this).dialog("close");
}
}
});
$('#deleteConfirmationDialog').dialog("open");
});
</script>
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome","requestId":"28b6a62eb1fb42829a3191b7c3e270d4"}
</script>
<script type="text/javascript"
src="http://localhost:61108/d90608e9d0044daf98eb343c1b3769d7/browserLink"
async="async"></script>
</body>
</html>
Everywhere I've searched the error is because you have to include jquery and jquery UI.
I've tried including JQuery UI with and without jquery.ui.dialog. No Luck.
What am I missing? Thanks for reading.
Edit
The error points to the this line:
$(document).ready(function() {
$('#deleteConfirmationDialog').dialog({
if I type $.dialog in the console I get undefined
If I reference jquery.ui.dialog.js there is the following error:
Uncaught TypeError: Object function (a, b) { return new p.fn.init(a, b, c) } has no method 'widget'
otherwise there is no other error.
I get 200 OK's for everything.
I've removed the displayed javascript code in to its own file and referenced it last. I have also moved the function that was outside the document.ready event function to inside this function, still getting the same error.
I can see jquery-ui and jquery in the Sources tab.
I don't understand why I can see jqueryui in the sources tab but typing $.dialog in the console results in undefined
Only code that doesn't use external libraries and code that doesn't use the DOM may be executed directly in a <script> tag.
If you search for DOM Elements directly in a <script> tag without waiting for the Document / DOM to be ready, the elements that you are searching for may not exist yet (in the DOM) or they may be incomplete.
Also using JavaScript methods directly in a <script> tag without waiting for the Document / DOM to be ready, the external files might have not been downloaded yet which means the methods from those external files might not exist yet.
In order to be sure that nothing like that occurs you need to put the code inside an event handler -- this ensures the code will be executed only after the event is triggered. The necessary event is $(document).ready(event_handler_function) also shorthanded as $(event_handler_function)..

How to execute Javascript function defined in main window from within Ajax response

I have Javascript function defined in the main index.html file. One part of this page is updated using Ajax (with prototype.js). Attempt to execute Javasript function defined in the main file from within returned AJAX code fails.
evalScripts: true option in Ajax.Updater prototype.js function does not help.
How do I fix this? Thank you in advance.
This is my index.html file:
<html>
<head>
<script src="js/lib/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function foo(x) {
alert(x);
}
function loadContent() {
new Ajax.Updater('responseArea', 'response.php' , { evalScripts: true } );
}
</script>
</head>
<body>
<div id="main">
<span style="cursor: pointer" onclick="loadContent();">Click on me to call Ajax response</span><br>
<br></br>
</div>
<div id="responseArea">
This will be replaced with Ajax response
</div>
</body>
</html>
This is response.php:
<?php
echo '<span style="cursor: pointer" onclick="foo("foo Called from within Ajax response");">
Click on me to call foo from within Ajax response</span>';
?>
Since evalScripts is true, you can put any JS snippet in your response and it will be executed when the AJAX call completes:
<script type="text/javascript">
foo("foo Called from within Ajax response");
</script>
If you don't want to execute, but just want to include more JS, you can insert a regular JS include tag:
<script type="text/javascript src="yournewcode.js"></script>
This is better than including the JS inline because it allows the browser to cache the file.

Categories