Passing Jquery value to PHP form - php

I have that simple form in a php page:
<form role="form" method="post" action="send-message.php">
<input type="text" id="SendTo" name="SendTo" value="">
<textarea class="form-control text-input" name="Message"></textarea>
<button type="submit" class="btn btn-primary">Send</button>
</form>
The value of SendTo input is set by a JQuery script from the same page:
$("button").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
});
Then I have PHP script in send-message.php:
<?php
$message = $_POST["Message"];
$sendTo = $_POST["SendTo"];
echo $sendTo; //nothing here!
Now, why the value of SendTo is not passing from the form to send-message.php?
It's weird because in the form, I can clearly see the value of the input but it's not passed to send-message.php.
I tried with GET method and it's the same thing...
Thank you for your help!
The missing code:
<?php foreach($mostCompatibleUsers as $otherUser => $score): ?>
<?php $compatibilityScore = getCompatibilityScore($score, $maxScore); ?>
<div class='col-sm-4 col-xs-6'>
<div class='box-info full'>
<div class='img-wrap'>
<img src='images/default-profile-pic.png' alt='Image small'>
</div>
<div class='des-thumbnail'>
<h4><b><?php echo $otherUser; ?></b> <small>Niveau de compatibilité: <b><?php echo $compatibilityScore; ?>%</b></small></h4>
<div class='progress progress-striped active'>
<div class='progress-bar progress-bar-success' role='progressbar' aria-valuenow='<?php echo $compatibilityScore; ?>' aria-valuemin='0' aria-valuemax='100' style='width: <?php echo $compatibilityScore; ?>%'></div>
</div>
<div class='row'>
<div class='col-md-6'>
<input type="hidden" class='username' value="<?php echo $otherUser;?>">
<button type='button' class='btn btn-success btn-sm btn-block' data-toggle='modal' data-target='#myModal'><i class='fa fa-envelope'></i> Send a message</button>
</div>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
More details
As you can see with the last added code, there is a foreach loop that display some users information and a button allow to send a message to that particular user.
When we press a button to send a message, it pops out a modal window containing a form where we can write and send the message. It's not a regular architecture! I think this is not simplifying the situation..

There is no .username class in your code.
By calling $(this).siblings('.username') you are basically just getting the other elements of the form as $(this) is actually the submit button.
Providing more code would be useful. Especially where the .username class is.

$("button").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
$.post( "send-message.php", $( "form" ).serialize() );
});

If you do in fact have an input with a username class, your code would not work anyway because the form will have already submitted by the time you try to read the inputs with javascript.
give your form an id
<form role="form" id="form" method="post" action="send-message.php">
and instead attach to its submit event
$("#form").submit(function(e) {
e.preventDefault(); //prevent the form from submitting
$("#SendTo").val($(this).siblings('.username').val()); //process the inputs
$(this).submit(); // then submit the form
});

First of all, in this case, You have to cancel the default submit of the form when clicking the submit button, the easiest way is to set its type to be button.
Second perform submitting manually using the Jquery as follows:
<form id="myForm" role="form" method="post" action="send-message.php">
<input type="text" id="SendTo" name="SendTo" value="">
<textarea class="form-control text-input" name="Message"></textarea>
<input type="button" id="myButton" value="send">
</form>
<script>
$("#myButton").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
$("#myForm").submit();
});
</script>

Related

Ajax Jquery Not Works On Html Form Data Insert To The Server [duplicate]

I've got a form, with 2 buttons
<button>Cancel changes</button>
<button type="submit">Submit</button>
I use jQuery UI's button on them too, simply like this
$('button').button();
However, the first button also submits the form. I would have thought that if it didn't have the type="submit", it wouldn't.
Obviously I could do this
$('button[type!=submit]').click(function(event) { event.stopPropagation(); });
But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn't work as expected (looked quite ugly!).
The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.
<button type="button">Submit</button>
In the words of the HTML Standard: "Does nothing."
The button element has a default type of submit.
You can make it do nothing by setting a type of button:
<button type="button">Cancel changes</button>
Just use good old HTML:
<input type="button" value="Submit" />
Wrap it as the subject of a link, if you so desire:
<input type="button" value="Submit" />
Or if you decide you want javascript to provide some other functionality:
<input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
<form onsubmit="return false;">
...
</form>
Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.
See here for an example (and more goodies, too). Here's the documentation, too.
in a nutshell, with your sample code, do this:
<script type="text/javascript">
$('button[type!=submit]').click(function(){
// code to cancel changes
return false;
});
</script>
<button>Cancel changes</button>
<button type="submit">Submit</button>
As an added benefit, with this, you can get rid of the anchor tag and just use the button.
Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>

Forms inside forms HTML

I know this question has been asked before, but read through to see why what I'm asking is different.
My first form is like this where newsearch.php is the name of the php file which the form is included in. I want to listen to any POST calls inside this php file since I have my if(isset($_POST code here.
<form action="newsearch.php" method="post">
So, I'm using bootstrap to layout the page, and I have another form I want to include in a <div class="row"> which is inside the form I mentioned before. What I'm asking is, can I add the form html code somewhere else in the php file and call it to appear inside the <div>?
What I want is a way to do this:
<div class="row">
<div class="col-lg-6" align="center">
<h4>Search For Galleries</h4>
<form action="newsearch.php" method="post">
<br>
<input type="text" name="valueToSearch" placeholder="Search"><br><br>
<input type="submit" name="search" value="Search"><br><br>
</div>
<div class="col-lg-6" align="center">
<h4>Create new Gallery</h4>
<!-- HOW CAN I INCLUDE A FORM HERE? -->
</div>
</div>
As you can see, the first form is not closed. That's coz it's closed way below in the file.
My second form is this:
<form action="inserttogal.php" method="post">
Gallery Name: <input type="text" name="gname" /><br><br>
Gallery Type: <input type="text" name="gtype" /><br><br>
<input type="submit" name="newgal"/>
</form>
Instead of using two <form> constructs (and nested, to boot) why not:
(1) Change the forms to ordinary DIVs
(2) Use jQuery to trap a button click
(3) Read the values into variables (this allows you to do any required field validation without negating the form's default action)
(4) Using javascript/jQuery, construct a composite HTML <form> (combining the two forms) in a variable, then
(5) Use jQuery to append() the form to the bottom of the page, and use
(6) $('form').submit() to submit the composite form.
A bit more work, but it will work. Note that Bootstrap uses/requires jQuery, so the library is already loaded. Might as well use it.
Code example:
Obviously, this example is not appropriate for your application, just showing you what you can do and how to get around your <form> problem, via jQuery/javascript.
$('#btnOne').click(function(){
var fn = $('#fn').val();
var ln = $('#ln').val();
var ag = $('#age').val();
if (ln==''){
alert('Please complete all fields');
return false;
}
var myFrm = '\
<form id="myForm" action="postFile.php" method="post">\
<input name="fname" value="' +fn+ '" />\
<input name="lname" value="' +ln+ '" />\
<input name="age" value="' +ag+ '" />\
</form>
';
$('body').append(myFrm);
$('#myForm').submit();
});
#frmOne{}
#frmTwo{background:wheat;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="frmOne">
First Name: <input id="fn" type="text" /><br>
Last Name: <input id="ln" type="text" /><br>
<div id="frmTwo">
Age: <input id="age" type="text" />
</div>
</div>
<button id="btnOne">Form One Clicker</button>
You should also look into AJAX (what it is, why use it -- it's quite simple!) and see if it could be of use. This post contains a link to another post with some simple examples that you should study. I included both posts because each has something you might find informative. Twenty minutes of poring of these examples could save you days of design frustration.
No form can having another form inside, I tried before.
Suggest apply Ajax or XMLHttpRequest (XHR)
<div class="row">
<div class="col-lg-6" align="center">
<h4>Search For Galleries</h4>
<form action="newsearch.php" method="post">
<br>
<input type="text" name="valueToSearch" placeholder="Search"><br><br>
<input type="submit" name="search" value="Search"><br><br>
</div>
<div class="col-lg-6" align="center">
<h4>Create new Gallery</h4>
<a href="#" data-toggle="modal" data-target="#new"><!--bootstrap modal-->
</div>
</form>
<form name="new_form" id="new_form" method="post" action="">
<div class="modal fade" id="new" tabindex="-1" data-backdrop="static" data-keyboard="false" role="dialog">
<div class="modal-dialog" role="document" >
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span style="font-size:21px;margin:-15px -10px 0 0;display:inline-block" aria-hidden="true">×</span></button>
<h3 style="">create gallery</h3>
<input type="button" name="create" id="create" class="btn btn-default" value="Create Gallery" />
</div>
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(function(){
$("#create").click(function(){
$.ajax({
type: "POST",
url: "new.php",
data: { data:data },
success:
function(){
alert('success');
},
error:
function(){
alert('Error!');
}
});
});
});
</script>

Pass parameter through php vaiable from form to another php file

I have next html form:
<form class="form-horizontal" action="frames1.php" method="post">
<div class="form-group">
<label for="uri1" class="control-label">URL:</label>
<div class="controls">
<input type="text" id="uri1" placeholder="www.ejemplo.com">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<input type="submit" class="btn btn-primary" id="submit" value="Visualizar" />
</div>
</form>
I want to pass the value from textbox "uri1" to a php variable.
Thats my frames1.php:
<?php
$uriValue = $_GET["uri1"];
?>
<script>
var uri = '<?php echo $uriValue;?>';
alert(uri);
</script>
But the system shows me "", not the value I put on the textbox in the form just before.
How can pass the value from the textbox to read on the php file?
Thanks!
You are using method as post in form co change this to
<?php
$uriValue = $_POST["uri1"];
?>
<script>
var uri = '<?php echo $uriValue;?>';
alert(uri);
</script>
and also add name attribute to your field. name="uri1"
that is,
<form class="form-horizontal" action="frames1.php" method="post">
<div class="form-group">
<label for="uri1" class="control-label">URL:</label>
<div class="controls">
<input type="text" id="uri1" name="uri1" placeholder="www.ejemplo.com">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<input type="submit" class="btn btn-primary" id="submit" value="Visualizar" />
</div>
</form>
Here is the working link.
You send a form by POST but in your frames1.php file, you try to get the content with $_GET. So what you have to do is just change GETto POST, so it looks like
<?php
$uriValue = $_POST["uri1"];
?>
Also a bigger problem is, that your input doesn't have a name, the parameter can only be referenced by the name, not by the ID. So your input should look like that:
<input type="text" id="uri1" name="uri1" placeholder="www.ejemplo.com">
There are one mistake in HTML as well as PHP code, You have to give name to the input field's. When form is submitted to the server then It will recognize fetch values using HTML Input Field names, and If your posted form in HTML, then you have to use same method to get the values.
Try to replace bellow code with your code:
<form class="form-horizontal" action="frames1.php" method="post">
<div class="form-group">
<label for="uri1" class="control-label">URL:</label>
<div class="controls">
<input type="text" name="uri1" id="uri1" placeholder="www.ejemplo.com">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<input type="submit" class="btn btn-primary" id="submit" value="Visualizar" />
</div>
</form>
Coming to your frames1.php:
<?php
$uriValue = $_POST["uri1"];
?>
<script>
var uri = '<?php echo $uriValue;?>';
alert(uri);
</script>
Let me know still not resolved.
Diff in HTML file is:
<input type="text" name="uri1" id="uri1" placeholder="www.ejemplo.com">
you didn't mention the name, then server will not recognize the element.
In PHP:
Your using POST method but your getting the values using _GET[], both are incompatible methods. So you will not get the values which are submitted by the form
<?php
$uriValue = $_POST["uri1"];
?>
You have set form method="post".
Therefore, after your form gets submitted, the value should be:
$uriValue = $_POST["uri1"];
Not
$uriValue = $_GET["uri1"];
Solutions:
1) Either change your form method method="post" to get your existing code working.
2) Change $uriValue = $_GET["uri1"]; to $uriValue = $_POST["uri1"];

Zend get value from textbox and add it into search url

I have question,this is the following code.
<form action="" method="post" id="search">
<div class="row collapse">
<div class="ten columns mobile-three">
<input type="text" size="25" name="search" value="<?php echo $this->search ?>"/>
</div>
<div class="two columns mobile-three">
<input type="submit" name="/search/index/keyword/" value="Search"; ?>" class="button expand postfix" id="search_button"/>
</div>
</div>
</form>
when I click the submit button,the url should be
from id/ to id/search/index/keyword/(here's the search key)
HTML
<form action="" method="post" id="search" name="search" onsubmit="submitForm();">
<div class="row collapse">
<div class="ten columns mobile-three">
<input type="text" size="25" name="search" id="search_value" value="<?php echo $this->search ?>"/>
</div>
<div class="two columns mobile-three">
<input type="hidden" value="/search/index/keyword/" id="search_url"/>
<input type="submit" name="search" class="button expand postfix" id="search_button"/>
</div>
</div>
</form>
JS
<script>
function submitForm()
{
var search_button = document.getElementById('search_url').value;
var search_text = document.getElementById('search_value').value;
document.searchForm.action = search_button + '/' + search_text;
document.searchForm.submit();
return false;
}
</script>
PHP
<?php
if (isset($_POST['search'])) {
// add action code here
}
?>
I'd use a server-side language for that. Make a process page (unless you're familiar with AJAX), get the values by $_POST and make the process page redirect.
I'm pretty sure that it's possible using JavaScript as well, but I'm really bad at it so don't count on my solution.
You can use JS to accomplish your goal.
1) make a function that runs when user clicks submit button.
2) function grabs the word from search box.
3) function changes the "action" attribute on the form element
4) form is submitted

Form Submit without Refreshing using Plugin (malsup)

I just created a form submit without refreshing using this plugin : http://malsup.github.com/jquery.form.js
The simple example can be seen at
http://jquery.malsup.com/form/
I don't what I was doing, it was worked fine before until I modified something that I don't remember.
When I click SAVE, it should be processed on the background and it should stay on the same page. But now, it doesn't and it redirect me to the action page (process-001.php)
I created another page using the same method, and it works just fine.
Can you see if I'm doing it wrong?
Here is the form :
<div id="submit-form">
<form action="web-block/forms/process-001.php" id="select-block" class="general-form" method="post" enctype="multipart/form-data">
<div class="input-wrap">
<input class="clearme" name="Headline" value="<?php echo $Headline;?>" id="headline"/>
</div>
<div class="input-wrap">
<textarea class="clearme" name="Sub-Headline" id="subheadline"><?php echo $SubHeadline ;?></textarea>
</div>
<label>Bottom Left Image</label>
<div class="up-mask">
<span class="file-wrapper">
<input type="file" name="Pics" class="photo" id="pics" />
<span class="button">
<span class="default-txt">Upload Photo</span>
</span>
</span>
</div><!-- .up-mask -->
<input type="hidden" name="Key" id="Key" value="<?php echo $Key;?>"/>
<input type="submit" class="submit-btn" value="SAVE" />
<span class="save-notice">Your changed has been saved!</span>
</form>
</div>
The Javascript :
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#select-block').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>

Categories