I posted a smaller to this yesterday and was shown how to do this but it doesn't work and the user never got back to me and I have been working on the same problem for hours.
I am trying to post a checkbox array from jQuery to php, when I run my code nothing seems to happen and when I try var_dump($_POST) this is all I get
Using this question as a reference, it seems that jQuery doesn't handle arrays too well. You can use to snippet from the accepted answer and it should work just fine.
serialize().replace(/%5B%5D/g, '[]')
Change the submit to a button or better use the form's submit event
why data-type html?
Your php does not seem to react to the serialised data but returns a button...
try my code here: http://plungjan.name/SO/sport.php
I am not unravelling the check box array - that is up to you
<?PHP
if (isset($_POST['saved'])) {
echo "saved"; exit(0);
}
else if (isset($_POST['Submit'])) {
echo var_dump($_POST["sport"]); exit(0);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sports quiz</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('#myForm').on("submit", function(ev) {
ev.preventDefault(); // cancel submit
var $form = $(this);
if ($("[type=checkbox]:checked").length ==0) {
alert("Please check one or more");
return false;
}
var formData = $form.serializeArray();
formData.push({name:"Submit",value:"submit"}); // note I changed the name from submit to Submit
$.post('sport.php',formData, function(data) {
console.log("Data",data);
if (confirm('You want to save \n' + data + ' as your sport?')) {
formData = $form.serializeArray();
formData.push({name:"saved",value:"saved"});
$.post('sport.php',formData,function(data) {
console.log("Saved Data",data);
});
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="submit" class="btn btn-info" name="Submit" value="submit">
</form>
</body>
</html>
Related
Hi iam learning jquery with php. I created very small php and jquery code to getting value but it's not working. I check console but not giving any information i have referred jquery api documentation same process i followed but no use. How can i solve this.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
("#container").html(data);
});
});
});
</script>
<body>
<form class="" action="" method="post">
<input type="text" name="" value="" id="sterm">
<input type="submit" name="" value="Search term" id="submit">
</form>
<div id="container">olddata</div>
PHP Code
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request received This is the new data"
} else {
echo "no data received;"
}
?>
There are few issues with your code, such as:
You need to prevent your form from being submitted in the first place. Use jQuery's .preventDefault()
Missing $ before ("#container").html(data);
Based on the above two points, your jQuery code should be like this:
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
$("#container").html(data);
});
});
});
There are two syntax errors in your PHP code. Missing ; in both your echo statements.
So based on the above point, your PHP code should be like this:
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request recieved This is the new data";
}else{
echo "no data recieved";
}
?>
<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".
Full page is at http://f14.co/auto-search/reno
I have the following checkbox set up outside a form:
<div class='span5' style='margin-left:0px !important;'>
<label for='model0'>
<input type="checkbox" name="model0x" id="model0x"
value="Accord" style='margin-top:-5px !important;'> Accord</label>
</div>
I have this javascript between the checkbox and the form:
<script>
if($("#model0x").is(':checked')){
$("#model0_is_checked").val($("#model0x").val());
}else{
$("#model0_is_checked").val("Not Checked");
}
</script>
Finally, I have this hidden input to call that value inside the form when the item is checked or not:
<form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
<input type="hidden" id="model0_is_checked" name="model0_is_checked">
MORE FORM STUFF AND SUBMIT BUTTON
</form>
No matter what I'm getting no value in the send_mail.php ....what am I doing wrong?
$('#model0x').click(function(){
var self=this;
$("#model0_is_checked").val($(self).is(':checked')?self.value:'Not Checked');
// do something
});
// or use submit ()
Bind the function to the form submit.
<script>
$('#final_form').on('submit',function(){
if($("#model0x").is(':checked')){
$("#model0_is_checked").val($("#model0x").val()); }
else { $("#model0_is_checked").val("Not Checked");}
});
</script>
jsFiddle example http://jsfiddle.net/KZrLp/
Your Javascript runs once, when the page (or more accurately, the <script> tag) is loaded. You have to make it run when the form is submitted instead:
<script type="text/javascript">
function updateHidden() { // Find a better name ;)
if($("#model0x").is(':checked'))
$("#model0_is_checked").val($("#model0x").val());
else
$("#model0_is_checked").val("Not Checked");
}
$(document).ready(function() { $('#final_form').submit(updateHidden); });
</script>
P.S. : not tested code
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
I am posting a form in an expressionengine (1.6.8) template. I'm doing it using jquery but have tried an HTML form too - same result. The PHP superglobal $_POST is empty after posting the form, even though I have PHP enabled on my templates (on input for the template containing the form and output on the processing template) and can see the POST variables in firebug.
Can anyone suggest what might cause this?
<html>
<head>
<script type="text/javascript" src="/_scripts/jquery-1.6.1.min.js"></script>
</head>
<body>
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(e){
e.preventDefault();
var path = "/select-locale/processing"
var form = $('<form/>');
form.attr("method", "post");
form.attr("action", path);
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", 'locale');
field.attr("value", 'NZ');
form.append(field);
$('body').append(form);
form.submit();
});
});
</script>
</body>
</html>
server-side code (inherited, not my own) :
<?php
var_dump($_POST);
var_dump($_GET);exit;
if ( ! isset($_POST['locale']))
{
$locale = FALSE;
$returnPage = "/";
}
else
{
$locale = $_POST['locale'];
$returnPage = $_POST['returnPage'];
}
if (isset($_GET['locale'])) {
$locale = $_GET['locale'];
$returnPage = "/";
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"} <?php
}
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"}
{exp:session_variables:get name="testSession"}
{if '{exp:session_variables:get name="testSession"}'=='yes' }
{redirect="<?php echo $returnPage;?>"}
{if:else}
{redirect="/nocookies/"}
{/if}
check the network tab if the parameters you want are really sent out
check the url if it's correct
if you use any sort of routing mechanism or url rewrite, you might wanna review it also
check your validation and XSS rules (if any) as it may reject the whole array once hints of XSS is found.
happened to me a while ago (CI) and i was sending it to the wrong url
You might want to re-check the action attribute, are u sure you're sending the data to the right url? I doubt that anything could be filtered.
it seems like form is getting submitted twice because of either action attribute of form tag or oath value in jquery function
It may be useful
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body name="test">
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(){
var form ='<form action="/select-locale/processing" name="newform" method="POST"><input type="hidden1" name="locale" value="NZ"></form>';
$('body').append(form);
alert('added');
document.newform.submit();
});
});
</script>`