jQuery trigger click via $.post - php

I'm submitting data from pagex.php to pagey.php via jQuery post.
pagex.php contains
$('#btn').click(function(e) {
e.preventDefault();
var x = 'variable1';
var y = 'variable2';
$.post("/pagey.php", { var1: x, var2: y}, function(data) {});
});
pagey.php contains
<form action=....>
<input type="text" name="x" value="<?php echo $_POST['var1'] ?>" />
<input type="text" name="y" value="<?php echo $_POST['var2'] ?>" />
<input id="submit" type="submit" value="submit" />
<script type="text/javascript">$('#submit').trigger('click')</script>
So basically when i post the values from pagex.php to pagey.php, i want to automatically submit the form on pagey.php . The jQuery line at the end of pagey.php will trigger an automatic click to the submit button. However jQuery is not triggering the submit click. it works if i access paygey.php directly (i tried it with pre defined variables) but not by doing $.post from pagex. I was assuming that by using $.post from pagex, pagey should automatically get the values and run the jQuery submit. What is the problem here.

JavaScript (which powers jQuery) is not run on the server, it's run from your users browser. So from my understanding, in order to run that little bit of script you will have to actually send your users to pagey.php

<input type="text" name="x" value="<?php echo $_POST[var1] ?>" />
<input type="text" name="y" value="<?php echo $_POST[var2] ?>" />
should be
<input type="text" name="x" value="<?php echo $_POST['var1'] ?>" />
<input type="text" name="y" value="<?php echo $_POST['var2'] ?>" />
You need to fix your array indices.

you should post directly to the action url on pagey... what is the value of pagey if its a simple form that auto posts.
simple answer is to do a form post on document.ready in pagey...

I think the bigger question is why are you posting data to pagey if you just re-post it to another page using your form action?
Try posting the data directly to the action page and let us know if that works.

I bet this will be useful to some of you. Regards.
<?php
echo
"<script type='text/javascript'>
$(document).ready(function() {
$('#submit').trigger('click');
});
</script>";
?>

Related

Given the results of a POST, how can I change a value and resubmit it?

Say I have a HTML form that lets you input a name and age and returns with a list of people with that name and age.
<form method="post" action="/search_results">
<input type="text" name="personName">
<input type="text" name="personAge">
<input type="submit" value="Submit!">
</form>
And on the search results page I have a list of the results, but I only display 50 at a time and allow users to go forwards/backwards between the page with buttons. So the results page would also look for a POSTed 'pageNumber' value and default to 0 if there is none.
When they click a button, how would I resubmit the age and name and also submit the corresponding pageNumber from the button?
I'm using PHP
Add a hidden field to the form:
<form name=search"" method="post" action="/search_results">
<input type="hidden" name="pageNumber"
value="<?php echo isset($_POST['pageNumber']) ? (int) $_POST['pageNumber'] : 0; ?>">
<input type="text" name="personName">
<input type="text" name="personAge">
<input type="submit" value="Submit!">
</form>
Add a JavaScript function to modify the hidden field value:
<script>
function search(pageNumber) {
var form = document.forms.search;
if (!form) return;
form.elements.pageNumber.value = pageNumber;
form.submit();
}
</script>
Apply the JavaScript function for the page buttons:
<span onclick="search(1)">1</span>
<span onclick="search(2)">2</span>
Obviously, the buttons should be generated with PHP in the following manner:
<?php
for ($p = 0; $p < $pagesNum; ++$p) {
echo "<span onclick='search($p)'>$p</span>";
}
?>
<form method="post" action="/search_results">
<input type="text" name="personName" value="<?php echo (isset($formdata['personName'])?$formdata['psersonName']:"") ?>">
<input type="text" name="personAge" value="<?php echo (isset($formdata['personAge'])?$formdata['personAge']:"") ?>">
<input type="hidden" name="currentPage" value="<?php echo (isset($formdata['currentPage'])?$formdata['currentPage']:"0") ?>">
<input type="submit" value="Submit!">
</form>
formdata are the data which are the inputs of the previous submit. These data should be returned by the search_results page along with the view.
Below is the js
<script>
$(document).ready(function(){
$(".paginationBtns").click(function(){
var page = $(this).attr('pageValue');
$("input[name='current']").val(page);
$("form").submit();
});
});
</script>
Assumptions of the forward and backward button
<a href="#" pageValue=0>Back</a><a href="#" pageValue=50>Next</a>
You have to append the back and next pageValue while loading each page.
The best practice in pagination to use a simple link that contains the parameres (GET) and not (POST). That way, when you have the parameters in the url you can cache it, add to favorites, get indexed by google, share your page in email/facebook etc.
<a href='http://example.com/?personName=<?=$_POST['personName']?>&personAge=<?=$_POST['personAge']?>&page=<?=$next_page_number?>'>Next</a>
If for some reason you must or really want to use POST you can save the values in hidden inputs within a form in the page and then sumbit it when clicking on "next page" button.
Form example:
notice its just an example you should sanitize the variables and not put them directly from the $_POST
<form name="pagination" method="post" action="/search_results">
<input type="hidden" name="page" id="page" value="2">
<input type="hidden" name="personName" value='<?=$_POST['personName'];?>'>
<input type="hidden" name="personAge" value='<?=$_POST['personAge'];?>'>
</form>
notice that we set the next page numbers & do submit by using a command from the form of:
<button onclick='document.getElementById("page").value= "2";document.pagination.submit();'>Next page</button>

Form submit is not sending any POST data

On my web page, when I press the "Add Customer" link, the following happens:
the onclick handler is called, which
sets values into the forms two text fields
displays an alert (at this point you can see the new values in the text fields on the screen)
calls the form's submit button (Note: the form submits back to it's own PHP file)
The same php file is called, but there are no POST values received
I've verified this with
the code in the first line that counts the values in $_POST then displays later
using fiddler to look at the request sent to the page
I've done this type of thing numerous times before with no problems. I've copied this code to two different web servers (linux, apache) with the same result. It's probably a minor problem but I can't find it.
I've stripped out a whole bunch of code to get down to this little bit, but haven't figured out why no POST values are being sent.
You can see a working copy of this at http://www.daleann.org/dla.php. The only thing need besides the code below is /js/jquery.min.js.
Thanks for your help.
<?php
$pc=count($_POST)."<br />".date("H:i:s");
?>
<html>
<head>
<script src="/js/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
alert("inside docReady");
$(document).on('click', "a.menuBillingOwner", function() {
$("#selectedBillingOwner").val("11");
$("#lastCustomNavSelected").val("selectedBillingOwner");
alert("selectedBillingOwner = "+document.forms['formBillingOwner'].elements['selectedBillingOwner'].value);
document.forms['formBillingOwner'].submit();
});
});
</script>
</head>
<body>
<ul id="menuBillingOwner">
<li><a href='#' id='menuBillingOwnerAdd' class='menuBillingOwner'>Add Customer</a></li>
</ul>
<?php
$lastCustomNavSelected = $selectedBillingOwner = "";
if (count($_POST) > 0 && isset($_POST['selectedBillingOwner'])) {
$lastCustomNavSelected = "selectedBillingOwner";
$selectedBillingOwner = $_POST['selectedBillingOwner'];
}
?>
<?php echo "pc = ".$pc."<br />\n"; ?>
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
</body>
</html>
Simple, because your form fields don't have name attributes, see below
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
Add names to them, for example:
<form name="formBillingOwner" id="formBillingOwner" method="POST" action="/dla.php">
<input type="text" id="lastCustomNavSelected" name="lastCustomNavSelected" value="<?php echo $lastCustomNavSelected; ?>" />
<input type="text" id="selectedBillingOwner" name="selectedBillingOwner" value="<?php echo $selectedBillingOwner; ?>" />
</form>
Note: Probably your jQuery assignments need to be fixed too but if that was the only issue then atleast a wrong value should have been POSTed to PHP, hence that is not the issue.
Delete these 2 lines of your jQuery.
$("#selectedBillingOwner").val("11");
$("#lastCustomNavSelected").val("selectedBillingOwner");
because that will change the value of textfield before your submit the form

Post variables from js to form and then to php file

first of all, greetings and excuse my English...
I explain my problem:
I have some JS functions that generate some variables, I would like to send these variables via the POST method to a php file to be consulted in a database...
I have read that the best way to do this is sending the variables to the respective values ​​about inputs within a form, Below I show the variables and the form:
Javascript variables:
On click in "Buscar"
$('#Buscar').on('click', function () {
document.getElementById("tipo").value=TipoDeInmuebleDATA.selectedData.value;
document.getElementById("operacion").value=TipoDeOperacionDATA.selectedData.value;
document.getElementById("habitaciones").value=HabitacionesDATA.selectedData.value;
document.getElementById("MetrosCuadrados").value=MetrosCuadrados;
document.getElementById("banos").value=BanosDATA.selectedData.value;
document.getElementById("precio").value=Precio;
});
The Form:
<form name="FormBuscar" method="post" action="consulta.php">
<input id="tipo" name="tipo" type="hidden" />
<input id="operacion" name="operacion" type="hidden" />
<input id="MetrosCuadrados" name="MetrosCuadrados" type="hidden" />
<input id="habitaciones" name="habitaciones" type="hidden" />
<input id="banos" name="banos" type="hidden" />
<input id="precio" name="precio" type="hidden" />
<input type="submit" name="Buscar" class="BotonBuscar">
</form>
I suspect that something is wrong, in the sense that I think the variables are not being sent to consultation
In consultation, if I do the following:
$tipo=$_POST['tipo'];
echo $tipo;
No result :-(
Greetings, I will await your answers in!
The event is wrong. You want to change the values right before submitting. So also add id="buscar-form" to the form tag. Then you can change the jQuery to this:
$('#buscar-form').on('submit', function () {
$('#tipo').val(TipoDeInmuebleDATA.selectedData.value);
$('#operacion').val(TipoDeInmuebleDATA.selectedData.value);
...
});
Forget about the #buscar button. When you click the button, the form is going to submit. So that's the event captured above. Careful with your typing, there are a lot of typos!

Javascript and Php (MVC)

i'm creating my own MVC Framework.
I have a basic form in my view
<form action="?" method="post" >
<input type="hidden" name="envoie" value="envoie" />
<?php dico('INSCRIPTION_NOM'); ?><input id="name" type="text" name="name" /><br />
<?php dico('INSCRIPTION_EMAIL'); ?><input id="email" type="text" name="email" /><br />
<?php dico('INSCRIPTION_PWD'); ?><input id="pwd" type="password" name="pwd" /><br />
<input type="button" value="<?php dico('INSCRIPTION_SINSCRIRE'); ?>" onclick="verifForm(document.getElementById('email').value);"/>
</form>
when I clock on the button they have a javascript function like that :
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
alert('resultat == '+data);
});
}
Inscription was my controllers and VerifForm an method of the controller. email was the value of a input.
The Php function was :
public function actionVerifForm() {
echo "OK";
}
When i click on the button i have all the code of the page on my alert but i only want the message "OK".
Thanks for helping me
what you are doing is AJAX, am i right? the data parameter IS your result. AJAX returns the echo-ed page as a string. if you mean to place it in the page, try jQuery .html() or .text() for a text only, escaped version.
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
$('#container-id-here').html(data); //html insert
$('#container-id-here').text(data); //text insert
});
}
and in your PHP, since you are doing AJAX, you should only echo what you need returned, and not the whole HTML mark-up (which means no <html><head>...</head></html>

How to capture a form element and use dynamically in the post url?

I'm trying to build a form which submits a URL which contains a lon/lat that has been passed over from Google Maps. I have managed to get it so the lon/lat is passed into input fields in the form, how would I go about using these values dynamically in the post URL, i.e.:
action="search.asp?[lon][lat]
If you want to get the values from the form into the URL, set the method attribute to get:
<form method="search.asp" action="get">
. This will put the values of the lon and lat fields of the form in the URL. Example:
search.asp?lat=[lat value]&lon=[lon value]
For more information, read this page. Excerpt:
If the processing of a form is
idempotent (i.e. it has no lasting
observable effect on the state of the
world), then the form method should be
GET. Many database searches have no
visible side-effects and make ideal
applications of query forms.
Using javascript you can change the action attribute of the form. So, create a form..
<form name="myForm">
<input type="hidden" name="lon" value="123" />
<input type="hidden" name="lat" value="321" />
...
<button onclick="setAction();">Submit</button>
</form>
Then in the head of the page add the setAction function..
<script type="text/javascript">
function setAction()
{
var lon = document.myForm.lon.value;
var lat = document.myForm.lat.value;
document.myForm.action = "search.php?["+lat+"]["+lon+"]"';
document.myForm.submit();
}
</script>
Hope this helps, it's how I have done this in the past!
Try using:
<form action="search.php" method="get">
<input type="hidden" name="lon" value="<?php echo $lon_fromGoogleMaps; ?>" />
<input type="hidden" name="lat" value="<?php echo $lat_fromGoogleMaps; ?>" />
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
Or if you want to use the form as post:
<form action="search.php?lon=<?php echo $lon_fromGoogleMaps; ?>&lat=<?php echo $lat_fromGoogleMaps; ?>" method="post">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
I see you tagged this as Javascript as well, and as Google Maps relies heavily on Javascript, you may have the Lon and the Lat passed as Javascript variables...
<script type="text/javascript">
// Obviously, execute this code after the DOM has loaded...
var formAction = document.searchForm.action;
formAction = formAction + '?lon=' + lon_fromGoogleMaps + '&lat=' + lat_fromGoogleMaps;
document.searchForm.action = formAction;
</script>
<form action="search.php" method="post" name="searchForm">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>

Categories