I have some question. I have the html form with one hidden input element. And I have an array in my javascript code. I want to catch pressing submit button event (by using jquery) and push the array data in the hidden input.
The question is - what happens first: form date will flow to .php script or javascript's array will be pushed into hidden input and afterwords .php script will be called? And why it is so?
TIA!
upd (code sample):
...
// process $_POST['domains']
...
<form action="registration?id=reg" method="post" enctype="multipart/form-data" id="reg_form">
...
<input type="hidden" id="domains" name="domains[]" value=""/>
...
<input type="submit" name="go" value="Register"/>
</form>
<script type="text/javascript">
var domainlist = [];
Array.prototype.indexOf = function (name) {
var ind = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].name == name) {
ind = i;
break;
}
}
return ind;
}
$(document).ready(function() {
...
});
function checkDomain() {
...
req = $.ajax({
type: 'post',
cache: false,
url: 'ajax.php',
data: ...,
success: function(data) {
$('#domain_list_wrap').delegate('input:checkbox', 'click', function () {
var dmnName = $(this).attr('name');
domainlist.push({name: dmnName, cost: domainsArr[dmnName.split('.')[1]]});
...
});
$('#domain_cart').delegate('input:checkbox', 'click', function () {
domainlist.splice(domainlist.indexOf($(this).attr('name')), 1);
...
});
}
});
...
}
</script>
The JavaScript submit event is fired when the form is submitted, but before the request is made to the server (as JavaScript runs on the client side this makes perfect sense). Therefore, the way you have imagined it working should be fine, and you can bind to the form submit event using jQuery as follows:
$("#yourForm").submit(function() {
//Submit event handler will run on form submit
});
The submit event handler can also be used to cancel form submission (for example, if some validation fails) by returning false. It wouldn't really work if the data was sent to the server first!
Put this in your body
<form id="frm" method="post" action="/">
<input type="hidden" id="txtHidden" />
<input type="submit" id="btnSubmit" value="submit" />
</form>
And this in your head:
<script type="text/javascript">
var arr = [ "hello", "there", "world" ];
$(document).ready( function() {
$("#btnSubmit").click( function(event) {
var str = arr.join(",");
$("#txtHidden").val(str);
// make sure the value is in the field
alert($("#txtHidden").val());
});
});
</script>
When you click on btnSubmit, the array will be joined with commas, you'll see the alert, then the form will be submitted.
Related
I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}