I use jquery to post data to mysql.
**In settings.php i have this short JS code:**
$("form#submit").submit(function() {
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "settings.php",
data: "fname="+ fname +"& lname="+ lname,
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
return false;
});
**And this short php:**
if (isset($_POST['fname'])){
$fname = htmlspecialchars(trim($_POST['fname']));
DO SOMETHING....
}
This is the code where the FNAME comes from: (after hit ADD image-button then posted the fname value..)
echo "......
<form id='submit$i' method='post'><input type='hidden' name='fname' id='fname' class='text' value='$fm_linkaz'></div><input name='add'type='image' id='add' value='$fm_linkaz' src='s.png'/></form>..........";
This is work well. But i need a SELECT element, so i changed the code to:
......
echo "<select name=dropdown_list id='**ONAME**'><option value''>test</option>";
for($i=0; $i < count($myarray); $i++){
echo "<option value='$myarray[$i]'>$myarray[$i]</option>";}echo "</select>";
......</form>";
This is work well, but i dont know how can i modify the JS code, to post the selected value too.
Thank u for your help.
First of all the javascript code needs a few updates:
$('#fname').val() is better than $('#fname').attr('value') -- .val() will work on selects/checkboxes as well - where .attr('value') won't be reliable.
Second: the data parameter to your $.ajax() call can take a json object (which it will convert to the form string)
$.ajax({
type: "POST",
url: "settings.php",
data: {
'fname': $('#fname').val(),
'lname': $('#lname').val(),
'oname': $('#oname').val()
},
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
There is a plugin that makes this much easier:
$("form").ajaxForm({
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
UPDATED:
Also - the <select> element was named "dropdown_list" - perhaps you wanted it to be submitting data as "oname" instead. Form elements use the "name" property to submit, the id property only makes css/js selectors easier to code.
To get a selected value for use
jQuery('#**ONAME**').val();
Although I'm not sure if **ONAME** is valid ID, try removing the **
To get the value use the
$('select[name=dropdown_list]').val();
You could also use and ID, but I think you have some invalid chars in it and I doubt this will work:
$('select#**ONAME**').val();
Anyway .val() is what you are looking for. I also suggest using val() instead of attr('value').
Related
I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?
From the code below the data gets entered like this: DATA1|DATA2|DATA3|
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + "|";
}
});
Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
Here is how I'm getting other data and re-displaying it from normal input text boxes:
$.ajax({
url: 'ajax/example/example.php',
data: "findval="+carrier+"&column="+column,
dataType: 'json',
success: function(data)
{
var auto_id = data['id'];
var auto_name = data['name'];
var auto_address = data['address'];
var auto_trailer_types = data['trailer_types'];
$('#output_autocomplete_forms').html("<form id='example' class='form-horizontal'><input type='hidden' name='auto_id' id='auto_id' class='form-control' value="+auto_id+">......<div class='form-group'>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA1'>DATA1</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA2'>DATA2</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA3'>DATA3</label></div>
var auto_trailer_types = data['trailer_types'];
Now how do I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
So, I am guessing that the string stored in the database is something like 0|0|1|0, and you need to restore the checkboxes to that state.
As has been said, you can use AJAX for that. First, you need a trigger to launch the AJAX routine -- a button click, usually:
<button id="mybutt">Update Checkboxes</button>
Your AJAX routine will look something like this:
var rowID = $(this).closest('tr').attr('id');
alert(rowID); //this datum must allow you to identify the row in the database
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'id=' +rowID,
success: function(recd){
var arrCB = recd.split('|');
for (var n=0; n<arrCB.length; n++){
var z = n+1;
$('#cb'+ z).val( arrCB[n] );
}
}
});
another_php_file.php:
<?php
$id = $_POST['id'];
$pseudo_query = "SELECT `field_name` FROM `table_name` WHERE `id` = '$id' ";
echo $pseudo_query_result;
The pseudo_query_result that you echo should be your original 0|0|1|0. The PHP echo sends that datum back to the jQuery AJAX routine's success function. Important: the received data is not available outside that success function. You must do what you want with that data inside the success function, as shown in above example.
In above code, .split() was used to turn the 0|0|1|0 string into an array, and then we use a for loop (or even just manually code each checkbox update individually).
Use ajax to resolve this issue. But before try to encode your php query response in JSON
$.ajax({
url: "test.php" //Your request URI
}).done(function(data) {
//data (you can name it whatever you want) is the data that you get from your request.
//eg. if(data.checkbock){ //do something }
});
More informations here
I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();
I want to create script to edit photos in galery. I have there textbox to insert title of photo and after insert title in it and leave textbox it'll update in database.
It works ok, when I change title by only one photo, but when I change more titles and then I reload page, all changed photos have the same title (which was insert last).
Can somebody help me please what is wrong?
There is code which I using now:
function UpdateTitle(idPhoto) {
var id = idPhoto;
$(document).ready(function(){
$('textarea').live('blur',function () {
var titleVal = $(this).val();
$.ajax({
type: "POST",
url: "changeTitle.php",
data: {title:titleVal , id:id},
success: function(msg) {
$('.'+id).html(msg);
}
})
});
});
}
<textarea name='title' id='title' onchange='UpdateTitle($idPhoto);' rows='2' cols='22'>$title</textarea>
More of a good programming tip rather than answering the question since it has already been answered but this would be cleaner:
$('textarea').on('blur',function () {
var titleVal = $(this).val(), id = $(this).data('id');
$.ajax({
type: "POST",
url: "changeTitle.php",
data: {title:titleVal , id:id},
success: function(msg) {
$('#'+id).html(msg);
}
})
});
With this HTML:
<textarea name='title' id='title' data-id='$idPhoto' rows='2' cols='22'>$title</textarea>
Will work much better and will be less confusing.
Use $('#'+id) instead of $('.'+id)
And use val instead of html to fill a textarea.
So basically you should have
$('#'+id).val(msg);
(supposing the msg is directly the intended content)
But live is now deprecated. It's suggested you use on, like this :
$(document).on('blur', 'textarea',function () { // something more precise than "document" would be better
JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.
Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.
Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.
The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()
there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name
I have a while loop in my PHP page where I look the following...
print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id='vote_$row->id' class='getPoint'>Get " .$row->coff. "<input type='hidden' value='$row->coff' id='credoff'/> credit(s)</a><br /></div>$clearDiv</div></div>";
I have a value set in my hidden field which I then call in my javascript...
{
var theid = $(this).attr("id");
var onlyID = theid.split("_");
var onlyID = onlyID[1];
credoff = $("#credoff").val();
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: function(data) {
if(data != "success1" && data != "success5") {
$("#" + theid).text(data);
}else{
$("#thediv_" + onlyID).fadeOut("slow");
$('#creditsBalance').fadeOut("slow");
newbalance = parseInt($('#creditsBalance').text());
if(data != "success5") {
alert('Credits offered = '+credoff);
The only thing is in my javascript its grabbing the highest 'credoff' variable value on the page, not the one clicked on, does this make sense?
First off, $('#credoff') is an id... and IDs are unique to a page. Secondly, if there were more than one (and built properly through a CSS selector), the way you're calling $('#credoff') would only give you the value of the first one, since you're not associating it with the event target.
Since it looks structurally like the input is a child of the (which is odd, too, btw), you'll need to use a selector like this to get credOff:
$('.getPoint').click(function(){
// properly associated with the event target.
var credOff = $(this).find('input').val();
// etc.
}
Element IDs must be unique throughout the page; if they are not, then attempting to select by ID is undefined. Your best bet is to use something like this:
<input type="hidden" ... class="credoff" />
And then in the javascript something like this:
credoff = $(this).children('input.credoff:hidden').val()