I am try to post a data from a from I have this code on my html.
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: {survey:testData}
});
});
})
</javascript>
and my form
<form id="test" name="test" method="POST">
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
and my php page
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES (????????)');
}
Now how can I deserialize $myDate which is look like below
surveyperiod=2014-02-25&deadline=2014-02-18
Tricky method is use parse_str()
// Access as Variable
if( isset($_POST['survey']) ){
// surveyperiod=2014-02-25&deadline=2014-02-18
parse_str($_POST['survey']);
$S_Period = $surveyperiod;
$S_Deadline = $deadline;
// do whatever you want
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ( "'.$S_Period.'", "'.$S_Deadline.'" )');
}
Explanation:
In you Ajax Request you send the data via POST method( data: {survey:testData} ) and assigned a POST variable that is survey and this POST variables contains the data string surveyperiod=2014-02-25&deadline=2014-02-18 as you assigned in your javascript testData. Now what we have to do is, Now we have to parse string into variables and parse_str() inbuilt function do it for you. That's it :)
You do not need to deserialize, you can do that in different way by putting hidden field like;
HTML:
<form id="test" name="test" method="POST">
<input name="survey" type="hidden" value="true"/>
<input name="surveyperiod" id="surveyperiod" type="date">
<input name="deadline" id="deadline" type="date" >
<input type="submit" id="btnsubmit"name="btnsubmit" value=" Update ">
</form>
PHP:
if(isset($_POST['survey']){
$myDate = $_POST['survey'];
mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ($_POST["surveyperiod"], $_POST["deadline"])');
}
JS:
<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
e.preventDefault();
var testData = $("#test").serialize();
$.ajax({
type: "POST",
url: "ajaxSurvey.php",
data: testData
});
});
})
</javascript>
By doing this, you dont neede to post data like {survey:testData}. Simply add,
<input name="survey" type="hidden" value="true"/>
html and check hidden field on php side. If a field with name survey exists, then run your code
Related
Given is:
<input type='text' name='firstname' id='firstname'>
<input type='text' name='lastname' id='lastname'>
<input type='text' name='username' id='username'>
<input id='pw' name='pw' type='password'>
I try to submit the data with an ajax-post-request like this:
var myData = "firstname="+ $('#firstname').val() + "&lastname="+ $('#lastname').val() + "&username="+ $('#username').val() + "&pw="+ $('#pw').val();
$.ajax({
type: "POST",
url: "php/register.php",
dataType:"text",
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
}
How to submit this data in a kind of this way correctly tho the php-file which corresponds to the database? Is a <form> needed for submitting with a button?
There are many solutions to this problem as many have mentioned. Easiest from my point of view is to wrap the fields in a form.
Bind a submit event which fires a callback when your form is submitted.
Serialize the form using .serialize() creating a text string in standard URL-encoded notation of all valid input fields and their values (so you don't have to build this query string yourself)
Post your data using $.post and handle the response using the success callback
Below is a fully functional snippet. You can see the data sent to PostBin here.
// PostBin CORS
$.ajaxSetup({crossDomain:true})
// Submit handler
$('form').on('submit', function(event) {
event.preventDefault();
var $form = $(this)
$.post(
'http://postb.in/ADC3a3Vm',// replace with php/register.php
$(this).serialize(),
function(response){
$("#response").append(response);
$form[0].reset()
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="firstname" placeholder="First Name">
<input type="text" name="lastname" placeholder="Last Name">
<input type="text" name="username" placeholder="Username">
<input type="password" name="pw" placeholder="Password">
<button type="submit">Submit</button>
</form>
<div id="response"></div>
you can use serialize() jQuery function
var myData = $("form").serialize();
in this case <form> is required
Read here
i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/
I have a problem, and i don't know how to get an id of a specific form when in the same page there is several form. Each form has a different id :
HTML :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
And this is the ajax
Jquery :
$('[id^=acheter]').submit(function() {
var CurrenID = $(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: $('#'+CurrenID).serialize(),
success: function(data) {
Method();
}
});
return false;
});
$('[id^=acheter]').submit(function() {
var data = $(this).serialize()+"&form_id="+$(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: data,
success: function(data) {
Method();
}
});
return false;
});
That will add your ID to the form post data?
in this line:
$('[id^=acheter]').submit(function() {
change to
$('#acheter').submit(function() {
Note that the id must be unique if you want to get more than one value from diferent tags use name or class.
to check the forms using the id just make a input button instead input submit, each one with a diferent variable to the jquery and submit .
example :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="button" id="addToCart1" name="addToCart" onclick="submitF('1')">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="button" id="addToCart2" name="addToCart" onclick="submitF('2')">Add</button>
</form>
Then use jquery/javascript to check what button was clicked
function submitF(var)
{
if (var == 1)
{
...
/*do what you want knowing that the first form was clicked,
submit form with jquery if you want*/
...
}
if (var == 2)
{
...
/*do what you want knowing that the second form was clicked,
submit form with jquery if you want*/
...
}
}
I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });
I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements