Script not executed after FORM element - javascript

I have an .aspx page. I populate a public variable in the code behind (.cs) page and then access that variable in JS on client side. I have the script declared after the FORM tag as below :-
<body>
<form>
...
</form>
<script language="javascript" type="text/javascript">
debugger;
var data = "<%=cSharpData%>";
</script>
</body>
After postback this script does not get executed first time, but when I click on any other server button on the page, then it gets executed.
Any idea why?

Is your postback done with ajax?
If so then only part of the page is refreshed and the script is not executed again.
You can wrap it in a function and add that function to the postback callback handler.
This is how I did it on one site:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { edit.update(); });

Putting some Javascript after a <FORM> element does not mean it will get processed after the form has been submitted. It gets processed as the HTML is rendered, which is what you are seeing.
If you want to run some Javascript after POSTing a form then you need to use a onClick handler, something like this:
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="dosomejavascriptstuff()">
</FORM>

have you tried to execute it with jquery $(document).ready()?
something like:
<script language="javascript" type="text/javascript">
$(document).ready(function(){....});
</scrip>
updated
without jquery
/* registr event on document load */
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", log4link, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {log4link();}
});}

Thanks for your replies. I got closer to the issue but I do not know the solution :(
The C# variable contains a path info as "D:\" and when I set this on a JS variable I get the error as "Unterminated String Constant".
How do I overcome this.
Actually this was the problem, why the script was not getting executed. As soon as I removed the "\", it worked !

Related

Jquery (ajax) load function not working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am fairly new to JQuery and Ajax functions, and I cannot figure out why my script keeps breaking. I basically have a form where a user inputs their name and location. When the user submits the form, the script uses JQuery's $.post() function to send the user values to "locationHandler.php", which takes the user information(name and location) and stores it in a mysql database. After the $.post request succeeds, I want to use JQuery's .load() function to update the html inside an arbitrary div tag. Every time the form is submitted the script stores the data into the mysql database, as it is intended to do so, however the script fails to .load() my php file.
Here's the code for my index.php page:
<?php ?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locationForm").submit(function() {
var unameVal = $("#locationForm input[name='uname']").val();
var locationVal = $("#locationForm select[name='location']").val();
$.post("locationHandler.php", {uname: unameVal, location: locationVal}, function() {
$("#display").load("defaultPhp.php");
});
});
});
</script>
</head>
<body>
<form id="locationForm" method="post">
<label>Name:</label>
<input type="text" name="uname" />
<label>Location:</label>
<select name="location">
<option value="uncc">UNC Charlotte</option>
<option value="ncsu">NC State</option>
</select>
<input type="submit" value="Submit" />
</form>
<div id="display"></div>
</body>
</html>
Here is the code for my defaultPhp.php page, which is located in the same directory as my index.php page:
<?php
echo "<p>This is some arbitrary text</p>";
?>
I have tried removing the $(document).ready(function(e) { ... }); and putting the script tags directly under the closing </form> tag, but then script stops storing the data into mysql database.
So first of all, why if I remove the $(document).ready(function(){...}); from the above script, will it stop storing values into mysql database?
And second, why won't the script load the content of my defaultPhp.php page into the div tag?
Please use return false before the end of submit function.
So first of all, why if I remove the $(document).ready(function(){...}); from the above script, will it stop storing values into mysql database?
Because javascript does not know your form, until the document is ready
Ajax request via $.post do not prevent sending page to server by native browser behavior. You must use event preventDefault function to cancel it:
$(document).ready(function() {
$("#locationForm").submit(function(e) {
e.preventDefault();//stop form submiting
var unameVal = $("#locationForm input[name='uname']").val();
var locationVal = $("#locationForm select[name='location']").val();
$.post("locationHandler.php", {uname: unameVal, location: locationVal}, function() {
$("#display").load("defaultPhp.php");
});
});
});
More info about preventDefault here.
First of all..yoyu need not to remove $(document).ready(function(){...}); from your script...also do not remove script tag otherwise your script will stop work...In case of load...Please check wethet the path you given is correct...
e.g. $( "#display" ).load( "ajax/test.php");

Rails App Javascript Unobtrusive

I'm having trouble with javascript in my rails app. I want to run a simple multiplication function on click when myButton is clicked and return it in an alert. Right now, I can't even get the JS to talk, and it's reloading the page, despite the code I have...
<script>
$(function() {
$('#myButton').click(function(e) {
e.preventDefault();
alert("hello")
})
})
</script>
<form>
$<input id="dataToPass"type="text"></input> <input id="myButton "type="submit" value="Invest"> </input>
</form>
If I add inline JS, I can get the alert to work, but when I move the code outside of the html, it's not working. Anyone know why? I'm not adept with jQuery or JavaScript.
change
id="myButton "
with
id="myButton"

Post a form and put results in a div

I can't get my form to submit correctly using jquery. I have tried using the tips here: https://api.jquery.com/jQuery.post/ and http://api.jquery.com/submit/ but can't figure out what I am missing to have the form submit and return the results to the div instead of reloading the page. It is supposed to call an external php page to get processed and return the results.
<script>
// On click "button.submit"
$("input[id^=formsubmit]").submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
$.get( "functions.php?do=adminmenu", function( data ) {
$( \".contentarea\" ).html( data );
});
return false;
});
</script>
<form action="#" name="submitForm">
<input type="textbox" name="test">
<input type="submit" value="Save Settings" id="formsubmit">
</form>
<div class="contentarea"></div>
Try to wrap your code inside DOM ready handler $(function() {...}); to make sure your DOM elements have been properly loaded.
Also, you can remove return false here as well as there's no need to escape the $(".contentarea" ) using \. So try this code:
$(function () {
$("input[id^=formsubmit]").submit(function (event) {
// Stop form from submitting normally
event.preventDefault();
$.get("functions.php?do=adminmenu", function (data) {
$(".contentarea").html(data);
});
});
});
The problem is that you're not passing the data to the php file. Furthermore you have not specified the type of data handled. And if you want to use POST you should use $.post(); and not $.get();
Try it like this: I've changed the function from .get to .post, added the data you want to send to the php file and specified a data type.
<script>
$(document).ready(function () {
$('#formsubmit').click(function () {
$.post("functions.php?do=adminmenu",{test_val:$('#test_input').value},function (data) {
$('.contentarea').html(data);
},"json");
});
});
</script>
<input id="test_input" type="text" value="">
<input id="formsubmit" type="submit" value="Save Settings">
<div class="contentarea"></div>
Last point: What is the php file returning? Is it only a string or what? Depending on this you need to modify the function writing the returned content in the '.contentarea'.
And by the way: When submitting the information via AJAX you don't need a form around it, as it just creates the need to escape the default behaviour when submitting a form.
If it still doesn't work let me know, I'll help you.

Javascript form.submit() works only when debugging

I have a weird problem when I try to submit a form. My page contains a html table and one column has a link that deletes the line from the DB calling a js function.
The html/php line is the following one:
<input type="hidden" name="deleteid" value=0>
print ", delete";
The javascript function is the following one:
function delete_line(team_id) {
if (confirm('<?php echo $txt_confirm_del_team;?>')){
document.formName.elements.deleteid.value = team_id;
document.formName.submit();
}
}
If I put a breakpoint on the line "document.formName.submit();", the called page can read the parameter "deletedid". If not, the parameters are not passed to the page called by the submit.
Btw, I have another issue if I use getElementById() to retrieve the element or the form in the javascript function: it says the getelementbyid is null (and it's not because I can retreive it using the syntax document.formName.elements.deleteid)
thanks
There may be some other event handlers there, you can open the page in Chrome and right click the anchor, then choose "inspect element" and then check out the event handlers in the "event listeners" tab.
As far as the code you posted; there is nothing wrong with it. The following works just fine for me:
<html>
<head>
<title>test</title>
</head>
<body>
<a onclick="javascript:delete_line(22);">delete</a>
<script>
function delete_line(nr){
console.log(nr);
}
</script>
</body>
</html>

Calling function from <form>

I am aware that you are not able to use the onLoad attribute in a <form> like <form id"form" onload="javascript:test()">, you can only do this in a <body>
My question is, is there any attribute that you can put in the to call a function when the form is loaded or is there a different way to do this?
EDIT:
So like this is it
<form jwcid="form">
<script>
function checkForChange() {
var approvalStatus = document.getElementById('licensingStatus').value;
if(approvalStatus == "Pass"){
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday,required");
} else {
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday");
}
}
</script>
.....
Forms don't use external data to build them (the body can load images, iframes can load external documents, etc).
So:
</form>
<script> /* The form has loaded. Do your stuff */ </script>
What do you mean with "form is loaded"? I think you mean "when the form is submited". The attribute is "onsubmit": <form id="form" onsubmit="javascript:test()">
Your funktion has to return either true or false whether the form shall be submitted or not.

Categories