Attach all fields form a from to ajax request - javascript

I have a HTML form with various different types of fields. Input, select, hidden and textarea. I have tried attaching all the form data to the ajax request but the POST data isn't sending. The reason for getting all form data rather than just naming the individual fields is the user can add more fields if the need to.
function saveProductEdits(f){
var url = 'func/editProduct.php?func=saveEdits';
$.ajax({
url:url,
data:$('#edit_form').serialize(),
type:'POST',
beforeSend:function(){
},
success:function(e){
alert(e);
}
});
}
PHP:
if(isset($_GET['func'])){
if($_GET['func'] == 'saveEdits'){
if(!empty($_POST)){
}else{
echo 'Post data not sent';
}
}else{
echo 'unknown function';
}
print_r($_POST); //shows empty array
}else{
}
HTML:
<form id="edit_form">
//various inputs generated at run time
<input type="button" value="Save Changes" onclick="saveProductEdits(this)" /> //button to submit
</form>
I keep getting 'Post data not sent'.
UPDATE:
screen shot of network tab
Im entirly sure but I presume by that the data isn't sending.
UPDATE FORM
<p>
<label for="product_name">Product Name: </label>
<input id="product_name" type="text" placeholder="Product Name" class="basic_field" value="Product Name PHP" />
</p>
<label for="main_cat">Main Catagory: </label>
<select id="main_cat">
php generated options
</select>
<div id="cats_list">
<p>
<label for="sub_cat_1">Sub Catagory 1: </label>
php generated options
</select>
</p>
</div>
<br/>
<a onclick="newCatField('2','Hair Pieces','6')">Add another Catagory</a>
<input type="hidden" id="count_cats" value="2" />
<div id="sizes">
<p>
<label>Size: </label>
<input type="text" id="size_1" value="1" />
<label>Quantity: </label>
<input type="number" id="quant_1" value="100" />
</p>
</div>
<a onclick="newSizeField('1')">Add another Size</a>
<input type="hidden" id="size_count" value="1" />
<p>
<label for="keywords">Keywords: </label>
Link a catagory:
<select onChange="addCatToKeywords(this,'keywords')" class="basic_field">
<option>Add...</option>
php generated options
</select>
<textarea id="keywords" class="basic_field">php content</textarea>
</p>
<p>
<label for="desc">Description: </label>
<textarea id="desc" style="">php content</textarea>
</p>
example of adding fields at runtime:
this does work and adds 1 to the id of each on and to a hidden value that counts the added fields.
function newCatField(c,u,m){
$.ajax({
url:'func/getCats.php',
type:'POST',
data:{used:u},
success:function(e){
if(count === parseInt(m)){
}else{
document.getElementById('cats_list').innerHTML += '<p><label for="sub_cat_'+count+'">Sub Catagory '+count+': </label><select id="sub_cat_'+count+'"><option>Please Select</option>'+e+'</select></p>';
count++;
document.getElementById('count_cats').value = parseInt($('#count_cats').val()) + 1;
}
}
});
}

$.serialize()
Probably this function is what you're looking for.
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});

Related

Change field value before submit

I want to convert the text from the textarea of form with js markdown converter before post
Now I have this code:
var message_textarea = $("#message_text");
...
$('#message-form').submit(function()
{
message_textarea.val(converter.makeHtml(message_textarea.val()));
})
It works, but I would like to change it so that the form isn't display changes in the text box before sending.
How can I do it?
Add a new input of hidden type to your form :
<input type='hidden' id='hidden_message_text' />
Then on submit fill it with converted data :
var hidden_message_textarea = $("#hidden_message_text");
hidden_message_textarea.val(converter.makeHtml(message_textarea.val()));
Hope this helps.
Changing the content of a textarea will display it on the DOM. You could try to use a separate hidden textarea. Meaning the displayed area contains the normal text and the hidden area contains the markdown.
You also could try to serialize the form, change the content and submit it using ajax all inside the submit event.
You can avoid Form submission and send data to server via AJAX call.
Here is example from Jquery docs
<pre>
<form>
<div><input type="text" name="a" value="1" id="a"></div>
<div><input type="text" name="b" value="2" id="b"></div>
<div><input type="hidden" name="c" value="3" id="c"></div>
<div>
<textarea name="d" rows="8" cols="40">4</textarea>
</div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div>
<input type="checkbox" name="f" value="8" id="f">
</div>
<div>
<input type="submit" name="g" value="Submit" id="g">
</div>
</form>
<script>
$( "form" ).submit(function( event ) {
var data = $( this ).serializeArray() ;
event.preventDefault();
$.ajax({
type: "POST",
url: '--some-url--',
data: data,
success: function(){/* callback*/}
});
});
</script>
</pre>

Form elements added after AJAX and php script not transfered to $_POST

I am using AJAX to get the value of the element chosen in a select input and to launch a PHP script that returns some input checkboxes fields.
Here is what it looks like :
HTML
<form method="post" action="liens_chra.php" name="Form" id="Form">
<label for="id_turbo">Turbo</label>
<select name="id_turbo" size="1" id="id_turbo">
<option value="10970">TM1761178</option>
<!-- and more -->
</select>
<div id="choix_reffab">
<!-- checkboxes appear here -->
</div>
<p class="form ">
<input type="submit" name="valider" value="Enregistrer">
</p>
<!-- something I tried too
<input type="button" id="submitevent" value="Enregister">
<script type="text/javascript" >
$('#submitevent').click(function() {
$("#Form").submit();
});
</script> -->
</form>
JQuery/AJAX
$("#id_turbo").change(function(){
var id_turbo = $("#id_turbo").val();
$.ajax({type: "POST",
url: "<?=URLSITEWEB;?>admin/outils/ajax/liste_Reffab.php",
data: "id_turbo="+id_turbo+"",
error: function(){
/*alert(id_famille+" \n ne passent pas.");*/
},
success: function(data){
$("#choix_reffab").html(data);
}
});
});
PHP
/* things */
foreach ($fabTab as $fab) {
$chaine .= '<input type="checkbox" "name=tabreffab[]" id="'.$fab.'" value="'.$fab.'" /><label for="'.$fab.'">'.$fab.'</label>';
}
echo $chaine;
So, when the user selects a value, some checkboxes appears.
My problem is that the data I want is not transfered to $_POST, and here is the result :
var_dump($_POST['tabreffab']) // is NULL, others values are ok
I'm fairly new to AJAX & JQuery, so I have no idea what to do. I tried submitting the form using JQuery, made no changes.
I got your issues when you return your checkbox your mistake is at name property of element.
In your code "name=tabreffab[]" Replace with name = "tabreffab[]"
$chaine .= ''.$fab.'';
Insted of above write like below code
$chaine .= '<input type="checkbox" name = "tabreffab[]" id="'.$fab.'" value="'.$fab.'" /><label for="'.$fab.'">'.$fab.'</label>';
checkboxes value will display in $_POST[] only on selecting a value
try in a editor
<?php
echo "<pre>";
print_r($_POST);
?>
<form id="sampleName" name ="sampleName" method="post" action="">
<textarea id="testID" name="textAreaName"></textarea>
<input type="text" name="text1" />
<input type="checkbox" name="check" value="1"/>
<input type="checkbox" name="check" value="2"/>
<input type="checkbox" name="check" value="3"/>
<input type="submit" value="submit">
</form>
The problem is in your Ajax call, specifically in the data part. It takes a json formatted object. The right way to write this is data:{id_turbo:"id_turbo_value"} not as what you used - data: "id_turbo="+id_turbo+""

I need click twice for submit my form with ajax

I have one form for validating a user, now I'm testing and need give 2 clicks for send, I read in many forums but can not find the solution to my problem.
This is the script code:
<script>
$(function () {
$('#enviar').click( function() {
if($('#correo').val().length > 0 && $('#pwd').val().length > 0){
var pwd2 = MD5($('#pwd').val());
var myData = "correo="+$('#correo').val()+"&pwd="+pwd2;
$.ajax({
type: "POST",
url:"http://myurlthatisworkingfine/registro/login",
data: myData,
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function(data) {
alert(data.message);
}
},
error:function(){
alert("Error");
}
});
} else {
alert('Por favor, rellena los dos campos');
}
return false;
});
});
</script>
The form:
<form id="check-user" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label> Usuario </label>
<input type="text" id="correo" name="correo">
</div>
<div data-role="fieldcontain">
<label> Contraseña </label>
<input type="password" id="pwd" name="pwd" >
</div>
<input type="submit" data-role="button" value="Acceder" name="enviar" id="enviar">
He olvidado mi contraseña
</fieldset>
</form>
All works very fine the only problem it´s with submit , i need 2 times for send the form finally. How can I fix this?
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<input type="radio" name="" id="inputID1" value="" />
<label for="inputID1">LabelText...</label>
<input type="radio" name="" id="inputID2" value="" />
<label for="inputIDd">LabelText2...</label>
<!-- .. more inputs maybe ..-->
</fieldset>
</div>
I am pretty sure your div data-role="fieldcontain" && fieldset data-role="controlgroup" is the wrong way around. Try to do your html part as shown in my example above. So dont give every input a data-role="fieldcontain" itself..
Jquery mobile has some problem to get the clicks on a inputs especially radio buttons. But if you mark it this way, it should work just fine. ( it did on my project )
Hope that helped...

Particular div to refresh onsumbit using ajax or jquery

I want a particular div on a page that contains database field to refresh itself to bring out the currenty entry onsubmit of a form. the div that contains the record is called #new_entry
<div id="new_entry"></div>
<script>
$(document).ready(function(){
$("#form3").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "../calls/insert_call_love.asp",
data: data
}).success(function() {
$("#feedback").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your have loved this photo </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
this is what i'm posting to the insert_call_love.asp
<form action="<%=MM_editAction%>" method="post" name="form3" id="form2">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="../imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="5" />
<input name="MM_insert" type="hidden" id="MM_insert" value="form2" />
</form>
In your code, you have to add a variable to success(function()) function
success(function(msg)
**"msg"**will contain data which you want to return from below url:-
url: "../calls/insert_call_love.asp",
then you can assign this data to any div
}).success(function(msg) {
$('#new_entry').html(msg);
}
Note: variable "msg" will contain all the data which you have printed on the page "insert_call_love.asp"
Well depending on what you are doing on the server side with this post...You would need to query the DB and retrieve the latest item, and send it back/echo it out as JSON.
So in pseudocode steps...
Process posted variables...
Query DB for latest entry..
Echo out as JSON...
Then do something like ...
.success(function(data) {
$('#new_entry').html(data);

Submit 2 forms at once

I want to submit both forms after click 2nd form's submit button.
The hardest part is that action is pointing to a php file with which send an e-mail to the client. I do not want to get 2 e-mails.
Both form data should reach that php file at the same time.
this is 1st form:
<form class="generalForm" id="form1" action="reservationSend.php" method="post">
<input id="datepicker-example3" type="text" name="datepicker-example3" value="Check In">
<input id="datepicker-example2" type="text" name="check_out" value="Choose Out">
<select name="RoomType">
<option selected="selected" value="0">Room Type</option>
<option value="Deluxe">Deluxe</option>
<option value="Family">Executive</option>
<option value="Conference">Conference</option>
</select>
</form>
This is the second form:
<form id="form2" class="generalForm" method="post" action="reservationSend.php" onsubmit="return submitForm()">
<input type="text" name="name" placeholder="Your Name" />
<input type="text" name="email" placeholder="Your email" />
<input type="text" name="tp" placeholder="Your Phone Number" />
<input type="text" name="Country" placeholder="Your Country" />
<textarea name="message" placeholder="Your Message"></textarea>
<input type="submit" name="submit" value="submit">
</form>
My javascript, myjscript.js:
function submitForm() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
Example submitting a form with AJAX & jQuery.
$('#formID')
.on('submit', function(e){
e.preventDefault(); //disable default submit action
var postData = {
'name' : $('input[name="name"]').val(),
'email' : $('input[name="email"]').val()
//etcetera
};
$.post(
'reservationSend.php',
postData,
callBack(returnData){
doStuffWith(returnData);
//add callback functionality
},
'json' //or any other datatype. In this case postData is a JS object, which gets submitted as JSON string
);
//You could even trigger the submission of another form here:
$('#otherForm')
.trigger('submit');
//This will trigger the submission of #otherForm
});
$('#otherForm')
.on('submit', function(e){
e.preventDefault();
//logic for form submission.
});
You can find documentation on the jQuery AJAX methods here. You'll also find serialize() and serializeArray() there. 2 Methods which can turn a form into a JSON string.

Categories

Resources