I have the following script:
if( condition ){
echo '<form action="url" name="myForm" method="post">';
echo '<input type="hidden" name="val" value="yes">';
echo '<input type="submit" name="Ok" value="Ok">';
echo '</form>';
}
When the condition is met,the submit button will show up,and i want it to be clicked with javascript,so the form will be submitted and i can use the hidden post value on the page from the action url."
I tried to add an id for the submit button and then use click(); but is not working.I also tried to create a function and use this.form.submit but it doesnt work because the action take place before the hidden value can be send.Any ideas?
2 Answers 2
So the problem is that on submitting you are not getting hidden fields
Check the fiddle .I have just changed post request to get in order to see if parameters are passed and you can change it post later
Set form id to myForm and button id to ok
$(document).ready(function () {
if ($("#myForm").length) {
$("#ok").trigger('click');
var url = window.location.href;
console.log(url);
}
});
what I am doing is printing the url on console .So go to you browser console to see the url and I am getting the url with parameters url?val=yes&Ok=Ok
2 Comments
$("#myForm").length return 1 when that id is in the html page and return 0 if id not in page .So if your php if condition is true then the form with that id is placed in the html page which returns 1( as jquery will only search in html page) and if php condition is false it will not place the form in html page returning 0.Try removing id of form in fiddle and check it would have same effect if your php condition is falseTry this it may work.
First add a id in your submit button
echo '<input type="submit" id="submit" name="Ok" value="Ok">';
Then you can use trigger in here like bellow code
$('#submit').trigger(submit);
Copy this bellow code this is working for me
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<?php
$con=4;
if( $con==4 ){
echo '<form name="myForm">';
echo '<input class="a" type="hidden" name="val" value="yes">';
echo '<input id="submit" type="submit" name="Ok" value="Ok">';
echo '</form>';
echo "<script>
jQuery('form').submit(function(e){
e.preventDefault();
var data=$('.a').val();
$.post(
'page2.php',
{value:data},
function(data){
alert(data);
}
);
});
jQuery('form').trigger('submit');
</script>
";
}
?>
includea script with the functions you need and then call them directly.