Updating the contents of a dropdown list Javascript/PHP - php

I'm new to Javascript/Jquery and struggling with a certain issue.
In the process of adding a job to a database, the users have an option to update the contents of dropdown lists with new options. Adding the new options is handled through a greybox which posts data with PHP through to the database.
After adding the new option it does not display in the dropdown list. As such they need to be able to click a button to refresh the contents of the dropdown list. Has anyone accomplished this before, and can show me some sample source code? Or is there a more elegant solution fo this issue?
I've been researching pretty much non-stop and cannot find a solution, any help is appreciated. n.n
Edit:
<script type="text/javascript">
function getbrands(){
new Ajax.Request('ajax/brand.php',{
method: 'get',
onSuccess: function(transport){
var response = transport.responseText;
$("brand").update(response);
}
});
}
It works... sometimes. Highly unstable. Also has a bad habit of conflicting with other scripts on the page. (mainly the greybox)
Any suggestions will be taken on board at this stage. :X

Use ajax to post the data to your php file, echo the html for the new dropdown back to the javascript, and then use jquery to put in the new contents. http://api.jquery.com/jQuery.ajax/

Assuming your using jQuery, you could do the following..
//in a php file that your gonna use to fetch new dropdown values
<?php //pathToPhpFile.php
header("Content-Type: application/json");
//here you'd perform a database query
//heres a dummy dataset
$data = array(
array( "id" => "dropdown1", "label" => "Dropdown #1"),
array( "id" => "dropdown2", "label" => "Dropdown #2"),
);
echo json_encode( $data );
exit;
?>
javascript code: sould be wrapped in $(document).ready( function(){ }); block to ensure the button is ready to accept events
//attach refresh event to button
$("#refeshButtonId").click( function() {
var dropdown = $('#idOfTheDropdown');
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ data[i].id +'">'+data[i].label+'</option>');
});
});
});
refined code :)
<script type="text/javascript">
$(document).ready( function(){
$("#refeshButtonId").click( function() {
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
var dropdown = $('#idOfTheDropdown');
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ i +'">'+ v +'</option>') );
});
});
});
});
</script>

no sample code but I guess it goes like this
after the posting, create a callback
that updates the DOM, particularly
the options for the select box
maybe it goes something like this in code
in jquery:
$.ajax({
method: 'POST',
data : $('#newjobfield').val(),
dataType: 'text'
success : function(data){
$('#selectbox').append('<option value="' + data + '">' + data + '</option>')
}
});
in php
function getNew()
{
if ($_POST)
{
// update database
// then echo the record's 'name' (or whatever field you have in there)
echo $newInsertedJobName;
}
die();
}
Now this code sucks, so just tell me if something does not work (I haven't tested it, cuz I made it a few minutes ago, while at work :P)

Related

Submit value of a checkbox via jquery/ajax to php and insert into db

I tried to find help via the search function on here but all the answers given to similar problems were too elaborate for me to understand, i.e. the example code was too complex for me to extract the parts which could have been relevant for my problem :(
I have a html form which sends userinput on a specific row in a datatable via an ajax-request to a php file, where the input gets inserted into my sqldb.
I have no problem sending the textinput entered by a user and also transferring additional infos like the specific row they were on, or the network account of the user. But i now want to add a checkbox, so the users can choose whether their comment is private or public. However i somehow cannot transmit the value from the checkbox, there is no error but also no checkboxdata inserted into the db.
Do i have to handle checkboxes differently than textareas? I'd be very grateful for help!
My code looks as follows:
Html:
function insertTextarea() {
var boardInfo = $( "<form id='boardComment'><textarea rows='2' cols='30'>Notizen? Fragen? Kommentare?</textarea>Privat:<input type='checkbox' name='privatcheckbox' value='private'><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
$( this ).parent().append(boardInfo);
$("tbody img").hide();
$("#boardComment").on( "submit", function( event ) {
event.preventDefault();
var change_id = {};
change_id['id'] = $(this).parent().attr("id");
change_id['comment'] = $(this).find("textarea").val();
change_id['privatecheckbox'] = $(this).find("checkbox").val();
if( $(this).find("textarea").val() ) {
$.ajax({
type: "POST",
url: "boardinfo.php",
cache: false,
data: change_id,
success: function( response2 ) {
alert("Your comment has been saved!");
$("tbody img").show();
$("#" + change_id['id']).find("form").remove();
}
});
};
});
and this is the php part:
$id = mysql_real_escape_string($_POST['id']);
$comment = mysql_real_escape_string($_POST['comment']);
$privatecheckbox = mysql_real_escape_string($_POST['privatecheckbox']);
$sql="INSERT INTO cerberus_board_info (BOARD_INFO_COMMENTS, BOARD_INFO_USER, BOARD_INFO_CHANGE_ID, BOARD_INFO_ENTRY_CHANNEL, BOARD_INFO_PRIVACY_LEVEL) VALUES ('$comment', '$ldapdata', '$id', 'Portal', '$privatecheckbox')";
The following line:
change_id['privatecheckbox'] = $(this).find("checkbox").val();
Searches for a element with the tagname checkbox. Such an element doesn't exist, I believe you are trying to search for an <input> element with a type of checkbox.
The following should work for you:
change_id['privatecheckbox'] = $(this).find("input[type=checkbox]").val();
Or even better, the :checkbox pseudo selector:
change_id['privatecheckbox'] = $(this).find(":checkbox").val();
On a final note: Why shouldn't I use mysql_* functions in PHP?

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

jQuery Droppable - Make an Update Statement after an element gets dropped

I want to do an update statement in my database, after an element gets dropped on a jQuery UI droppable element.
$("#pictures th div").droppable({drop: function(ev, ui) {
alert('You filled this box with a picture');
var this_id = $(ui.draggable).attr("alt");
var draggableId = ui.draggable.attr("id");
}
I know how to get the information (see the code above) I need, but how can I put them now into the database ?
Thank you !
At this point, you can use jQuery's $.post() method to post to a PHP file you've written. In the $.post(), you can pass the ids you would like to have written to your database.
So something like this:
$.post("/save.php", { imageId: this_id, draggedId: draggableId }, function (data) {
alert("success!");
});
Post the variable values to other page lyk this:
$.ajax({
type: "POST",
url: "data.php",
data: "Cat=" + id + "&Wid=" + WID
});
and then on data.php page get the values lyk this:
$Cat=$_POST['Cat'];
$WID=$_POST['Wid'];
simply store them in database by using insert query,hope it will help you.

Trying to refresh div with jQuery in MVC f/w

Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.

How to pass dynamic id text box value to another page without refreshing with jquery and php

$('.btncomment').click(function () {
var id = $(this).attr('id');
$.post('SaveTopicInformation.php', {
tid: commentform.(topic_ + id).value,
topicdetail: commentform.(topicdetail_ + id).value,
userid: commentform.(user_ + id).value
});
});
I have to pass the 3 text box value to another page. First of all, I display the all the record from database. then, I have comment link for each row. I like to give comment and save the comment for eache record. I use by jquery and php. please help me out. I can't finger out how to pass dynamic text box's value by bynamic name.
You cannot access object fields like that. You need to use the array subscript syntax:
$.post('SaveTopicInformation.php', {
tid: commentform['topic_' + id].value,
topicdetail: commentform['topicdetail_' + id].value,
userid: commentform['user_' + id].value
});
Actually, since you are using jQuery, using .val() on a jQuery object wrapping the form element would be much nicer.
Try this code sample. What it does is listen for your submit button to be pressed, then it grabs all of the content from a certain form, and submits it to a server:
//Listen for the submit button to be clicked
$('.btncomment').click(function () {
$.ajax({
'url' : 'SaveTopicInformation.php', //Processor URL
'type' : 'POST', //Send as POST-data
'data' : $('.myForm').serialize(); //Send the entire form
'success' : function(data) { //What to do when the form is submitted
if (data == 'success') {
alert('Form submitted!');
}
}
});
});
Hope that helps,
spryno724

Categories