POST multiple values in jquery especially if names are the same - php

I have a table(NOT FORM), in php which I generated in a while loop.
one of the inputs is generated 20 input, with or without any data in it. I am trying to run an update/save using jquery and I need to post all the values in that input.
This is in a while loop. It is basically loops and render the data from the table into the image you can see below. If you count the input box in the image, it is 20.
webpage layout
echo '<input type="text" name="access[' . $count . '][' . $a . ']" id="access[' . $ucount . '][' . $a . ']" size="1" maxlength="2" value="' . $user_access[$a] . '" />';
In a html page you will see this
<input type="text" value="RO" maxlength="2" size="1" id="access[2][0]" name="access[2][0]">
<input type="text" value="SQ" maxlength="2" size="1" id="access[2][1]" name="access[2][1]">
and without ant data it will be the `value` will be blank.
<input type="text" value="" maxlength="2" size="1" id="access[2][2]" name="access[2][2]">
Now because I am using jQuery ajax to do an update / save. How will I sent everything in all 20 input boxes via jQuery?
I have done a normal and this is how I normally do it below.
$(document).ready(function () {
$('[name="save_record"]').unbind('click').click(function () {
var update_user = $(this).parent().parent().find('[name="user"]').val();
$.ajax({
type: 'POST';
url: 'update.php';
data: {
update_user: update_user
},
success: function (Response) {
alert(Response);
})
});
});
but I know for this method of post all values in all 20 input boxes will be different but I have try it like i did above and it only post the first value in the first input box.
question
How can I post values in all 20 input boxes? please based your answer/ example as if you the input boxes where empty as first.
NOTE
some values may be empty so i need to also check that none of the input boxes are null.
Thanks

$.post(
'/my-url',
{
data: $('#my-form').serialize()
},
function (data) {
// some processing successful result here
}
);
Using <input> tags without <form> is impropriety

Related

POST multiple AJAX data

I'm trying to POST multiple AJAX data to update.php. This is my code at the moment:
$.ajax({
url:"update.php",
method:"POST",
data: $('#update_form').serialize(),
beforeSend:function(){
$('#update').val("Geupdate!");
},
success:function(data){
$('#update_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
However I also want to sent an ID within the data. This is the form that I'm using.
<form method="post" id="update_form">
<label>Notitie:</label>
<input type="text" name="name" id="' . $row["id"] . '" class="form-control" value='.$row["name"].' width="100%">
<br />
<input type="submit" name="update" id="update" value="Opslaan" class="btn btn-success" />
</form>
How can I combine data: $('#update_form').serialize() and id="' . $row["id"] . '" together?
I tried a few combinations but I can't find the correct answer. Here is what I've tried:
data: $('#update_form').serialize(), id: <?php echo $row["id"] ?>
One simple way is add a hidden input to the form so serialize() will include the id
<form method="post" id="update_form">
<input type="hidden" name="id" value="' . $row["id"] . '" >
<label>Notitie:</label>
<input type="text" name="name" id="' . $row["id"] . '" class="form-control" value='.$row["name"].' width="100%">
<br />
<input type="submit" name="update" id="update" value="Opslaan" class="btn btn-success" />
</form>
You are serializing entire form, which includes your textbox data as well. So, you don't need to explicitly add each element of form.
The .serialize() method creates a text string in standard URL-encoded
notation. It can act on a jQuery object that has selected individual
form controls, such as <input>, <textarea>, and <select>: $("input, textarea, select" ).serialize();
So, whatever element added in form (<input>, <textarea>, and <select>) gets serialized implicitly. So, in case, you wanted to pass additional data along with form, then you can create a hidden field inside your form.
I don't use jQuery so this is a bit of a "stab in the dark" but you could alternatively use a FormData object and append a new parameter & value to it like this perhaps.
$.ajax({
var form=$('#update_form');
var fd=new FormData( form[0] );
fd.append('id', document.querySelector('input[name="name"]').id );
url:'update.php',
method:'POST',
data: fd,
beforeSend:function(){
$('#update').val('Geupdate!');
},
success:function(data){
form[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});

Retrieve and print data from mysql DB using ajax

I have the following text fields -
<input type="text" name="id" id="id" tabindex="1">
<input type="text" name="name" id="name" tabindex="1"/>
and the screenshot of mysql database is -
id name
123 John
124 Rahi
When I insert the track id in the first text field then the corresponding student name should be shown in the second field. How can it be done using ajax ?
Try this:
>> Trigger onblur event (javascript function) for the first textbox.
>> Define ajax in that function to get name.
>> Show the name in textbox.
I think this is simplest way to get this.
--
Thanks
You can call a jquery function on onblur() event of the textbox.
<input type="text" name="id" id="id" tabindex="1" onblur="getname()">
Write the ajax function for getting the name like:
<script>
function getname()
{
var id=$("#id").val(); // get the id from textbox
$.ajax({
type:"post",
dataType:"text",
data:"id="+id,
url:"page.php", // url of php page where you are writing the query
success:function(response)
{
$("#name").val(response); // setting the result from page as value of name field
}
});
}
</script>
and write the code for fetching the result in a page, say page.php
$id=$_POST['id'];
$query=mysql_query("select name from table where id=$id");
$result=mysql_fetch_row($query);
echo $result[0]; // echo the name to js function
exit;

Submit checkbox ID and textfield value without refreshing browser using Ajax

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/

How to update SESSION variable with jQuery + AJAX, is it even possible?

I would like to update session variable.
Let me introduce this in simple example. We get a div with input fields printed out by PHP script, with some values etc...
Example PHP code:
echo '
<div id="few-input-fields">
<input id="Name" size="20" value="' . $_SESSION['name'] . '" />
<br />
<input id="Lastname" size="20" value="' . $_SESSION['lastname'] . '" />
</div>
<span id="save">save</span>
</div>
';
Let's say user edit this input field (id=Name) and type name "Mark" inside it and then press save text.
On click it should save/update session variable, without reloading page AND refresh input fields.
Is that possible? Perhaps with ajax / jquery? And most importantly how ?
Yes, just do a simple AJAX request. With jQuery it would be:
$("#formid").submit(function(){
$.ajax({
type: "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(){
// Do what you want to do when the session has been updated
}
});
return false;
});
And your PHP:
<?php
session_start();
$_SESSION["name"] = $_POST["name"];
// Add the rest of the post-variables to session-variables in the same manner
?>
Note
You need to add name-attributes to your input-fields.

Several jQuery forms

I have several forms on one page, they're all the same, but have different hidden values:
<?php foreach ($results as $result): ?>
<form method="POST" action="edit.php">
<input type="hidden" name="id" value="<?php echo $result['id']; ?>">
<input type="submit" name="action" value="Edit">
</form>
<?php endforeach; ?>
I want id to be submitted using $.post when this is clicked to edit.php, however if I use $("#id").val() (I'm trying to post the hidden input which is named id), it only selects the first id value in the page, and not the one that was clicked by the submit button.
$.post("edit.php", { id: $("#id").val(), action: "Edit" },
function(data){
alert("Data Loaded: " + data); //im using fancybox here to display an inline frame
});
How can I submit the id of the current form clicked?
I assume you're binding to the submit event on the forms. Use serialize instead of querying for values:
$('form').submit(function(){
$.post('edit.php', $(this).serialize(), function(data) {
alert("Data Loaded: " + data);
});
return false;
});
Since you still need to include the submit's name/value pair, find the name="id" input within the <form> you're on, like this:
$.post("edit.php", { id: $(this).find("input[name=id]").val(), action: "Edit" },
function(data){
alert("Data Loaded: " + data);
});
id attributes should be unique in the document, since your markup in the question doesn't have an ID it looks like you fixed that issue. This finds the name="id" <input> in the <form> you're in the submit handler of.
Do you have multiple page elements with the same ID? Using $("#id").val() I believe would only retrieve the first value of an element with that ID. Having more than one would result in an array of elements. To find a specific element that is duplicated you would have to put it into context like:
$("#myform").find("#id").val()
Use the form element that is submitted as a context in your selector:
$('form').live('submit', function(e) {
var form = $(this);
var id = $('#id', form).val();
//... do your post here
});
NOTE: I used .live() to bind to the submit event in case you're adding forms dynamically.

Categories