I am trying to create a method that posts data to mysql when called. The only problem is I can't figure out how to pass it the correct information from the fields as their IDs are created at runtime.
The fields are created using a while loop and on double click they become editable then on blur they are supposed to revert to their previous state and post any changes made to the database.
(this is my first time writing one of these I hope I'm clear!)
My JS
function disablefarm(farmid) {
$(function() {
var farmstr = farmid.replace(/[^0-9\.]+/g, ""),
farmID = $("#farm" + farmstr + "").val(),
farmName = $("#farmn" + farmstr + "").val(),
fieldarray = $([]).add(farmName).add(farmID);
$("input:text[id=" + farmid + "]").attr('readonly', 'readonly');
$("input:text[id=" + farmid + "]").addClass("noshow");
var epost_url = "editfarm.php";
var epost_data = fieldarray.serialize();
$.post(epost_url, epost_data, function(response) {
alert(response);
});
});
}
The html elements are created in a while loop that outputs
echo "<td name='farmL' ><input type='hidden' value='$id' id='farm$id' /> <input type='text' id='farmn$id' value='$fname' readonly='readonly' class='noshow' size='33' ondblclick='enablefarm(this.id)' onblur='disablefarm(this.id)' />";
And finally editfarm.php looks like
if (filled_out($_POST)){
$efarmID = check_input ($_POST['farmID']);
$efarmName = check_input ($_POST['farmName']);
}
else{
echo "not committed";
}
$query = "UPDATE farm_name
SET farmName='".$efarmName."'
WHERE farmID=".$efarmID.";";
$result = mysql_query($query);
if(!$result)
{
echo"".stripslashes($efarmName)." not updated";}
else{
echo"".stripslashes($efarmName)." updated";
}
The HTML output looks like this
<tr id='row27'>
<td name='farmL'>
<input type='hidden' value='27' id='farmid27' />
<input type='text'
id='farmn27'
value='111 Gary farms'
readonly='readonly'
class='noshow'
size='33'
ondblclick='enablefarm(this.id)'
onblur='disablefarm(this.id)' />
</td>
</tr>
Thanks!
Reducing js to minimum, I would have done this by introducing an extra attribute to your dynamically generating inputs.
<td><input type="text"
data-id="27"
name="farmid27"
value="111 Gary Farms"
class="farmEdit" /></td>
Now simply update your js to:
$(document).on("blur", "input.farmEdit", function() {
$.post("editfarm.php",
{
farmID : $(this).attr('data-id'),
farmName : $(this).val()
},
function(response) {
alert(response);
});
});
Here you can see the 'data-id' attribute removed the dependency on input name, and I would suggest why to introduce input name when you are posting it individually using ajax(atleast for these types of cases).
You may find it easier if you refactor your code somewhat. If you modify your PHP code to output the table content to look something like this:
<td>
<input type="text"
name="farmid27"
value="111 Gary Farms"
class="farmEdit" />
</td>
(The indentation is just to make it readable.)
Then you can rewrite your JavaScript to something like:
$(document).ready(function() {
$(document).on("blur", "input.farmEdit", function() {
var $inputElement = $(this),
inputName = $inputElement.attr("name"),
inputValue = $inputElement.attr("value")
curFarmId = inputName.substr(6); // Strip off the "farmid.." prefix
$.post(
"editfarm.php",
{
farmID : curFarmId,
farmName : inputValue
},
function(response) {
alert(response);
});
});
});
This takes advantage of jQuery delegated events and the fact that the this object in a click handler refers to the page element that was clicked (the <input> in this case).
Related
I have dynamic text field at Demo JSFiddle and I have done the autocomplete part for my item part no.
$ (document).ready(function() {
$("#addField").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div id=\"field" + intId + "\"/>");
var fpartNo = $("<input type=\"text\" name=\"erfq_partNo[]\" class=\"partNumber\"/>");
var fDescription = $("<input type=\"text\" name=\"erfq_desc[]\" disabled/>");
var fPrice = $("<input type=\"text\" name=\"erfq_price[]\" disabled style=\"width:80px\"/>");
// remove textboxes and dropdown boxes
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fpartNo);
fieldWrapper.append(fDescription);
fieldWrapper.append(fPrice);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
$(".partNumber").autocomplete({
minLength:1,
source: 'readPart.php',
select: function(event, ui){
var selected = ui.item.value;
}
});
});
});
readPart.php
$searchTerm = $_GET['term'];
$getPartSQL = base_executeSQL("SELECT * FROM eitem_item where eitem_item_part_no LIKE '%".$searchTerm."%' ORDER BY eitem_item_part_no" );
while($Partdata_row = base_fetch_array($getPartSQL))
if (base_num_rows($getPartSQL)!= 0)
{
$data[] = $Partdata_row['eitem_item_part_no'];
}
echo json_encode($data);
The first text field is uses for entering the part No.
My question is once the part no has been entered, the other relevant information (description and price) will be displayed at the other readonly text fields which the data are extract from my database. I have no idea what to continue with this select: function(event, ui){. Any help will be appreciated.
well, if you want to get the data on the basis of part # from database you can trigger an ajax call on blur of text box part number.
you can do something like this
$("#partNum").blur(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part, //url to your database fetcher code.
complete: function (response) { //response contains what you got from pap page
$('textarea#des').val(response.responseText); //set textarea and textbox value popping out from db file
}
});
});
Here is HTML snippet to this request.
<input type = 'text' id = 'partNum' name = 'parts' />
<textarea id = "des" name = 'description' disabled></textarea>
FIDDLE
this will work on blur means when clicked outside the textbox. But if you want to get real time data(while user is typing) then you've to bombard the ajax requests on keyup event.
something like this:
$("#partNum").keyup(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part,
complete: function (response) {
$('textarea#des').val(response.responseText);
}
});
});
FIDDLE here
Hope this will help.
I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");
foreach ($faq as $i) {
echo
'<div>
<a id="'.$i->ID.'" class="question" href="#">'.$i->q.'</a>
</div>
<div id="a'.$i->ID.'" class="answer">
<p>'.$i->a.'</p>
<form method="POST" id="form'.$i->ID.'">
<input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
<input type="hidden" name="action" value="ce_faq_quality"/>'
.wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
'<p><b> Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input> </b></p>
</form>
</div>';
}
echo '<div id="feedback">feedback</div>';
I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%). I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
function(){
var id = this.id;
jQuery('#a'+id).slideToggle(350);
});
jQuery('.quality_radio').click(
function(){
var formid = jQuery(this).closest('form').attr('id');
var formid = '#'+formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formid){
var qu = jQuery(formid).serialize();
console.log(qu);
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success:function(data){
jQuery("#feedback").html(data);
alert('this is working');
}
});
return false;
}
This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');
function ce_faq_quality(){
$quality = 1; //$_POST['quality'];
$faq_id = 1; //$_POST['faq_id'];
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));
echo 'succes php function ';
die();
}
Your formid variable falls out of scope in the ajaxSubmit function. You should instead try:
jQuery('.quality_radio').click(
function() {
var formid = jQuery(this).closest('form').attr('id')
var formid = '#' + formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formId) {
var qu = jQuery(formid).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
So that you pass the formid to the ajaxSubmit function.
I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.
sample ajax:
function MyFunction(){
var i = 1;
var x = $('#num_to_enter').val();
while (i <= x){
var name = $('#fname[i]').val();
var lname = $('#lname[i]').val();
var email = $('#Email[i]').val();
i++;
}
$('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
$.ajax({url : 'process.php',
type:"POST",
while (i <= x){
data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
i++;
}
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
}
A sample of form :
<?php
echo "<form method='post'>";
$i=1;
while($i <= $num_to_enter){
$form_output .= "First Name:
<input id='fname' type='text' name='fname[$i]'><br />
Last Name:
<input id='lname' type='text' name='lname[$i]'><br />
Email:
<input id='Email' type='text' name='Email[$i]'><br />
$i++;
}
echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";
?>
Then DB MySQL Sample
<?php
while ($i <= $x){
$x = $_POST['num_to_enter'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['email[$i]'];
$sql = "INSERT INTO `mytable`
(`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";
$i++;
}
?>
Here is a simple demo of AJAX:
HTML
<form method="POST" action="process.php" id="my_form">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[custom1]">
<input type="text" name="firstname[custom2]">
<br><br>
<input type="submit" value="Submit">
</form>
jQuery
// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){
// do not allow native browser submit process to proceed
e.preventDefault();
// AJAX yay!
$.ajax({
url: $(this).attr('action') // <- find process.php from action attribute
,async: true // <- don't hold things up
,cache: false // <- don't let cache issues haunt you
,type: $(this).attr('method') // <- find POST from method attribute
,data: $(this).serialize() // <- create the object to be POSTed to process.php
,dataType: 'json' // <- we expect JSON from the PHP file
,success: function(data){
// Server responded with a 200 code
// data is a JSON object so treat it as such
// un-comment below for debuggin goodness
// console.log(data);
if(data.success == 'yes'){
alert('yay!');
}
else{
alert('insert failed!');
}
}
,error: function(){
// There was an error such as the server returning a 404 or 500
// or maybe the URL is not reachable
}
,complete: function(){
// Always perform this action after success() and error()
// have been called
}
});
});
PHP process.php
<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */
// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';
// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];
/**************************************************/
// some logic for sql insert, you can do this part
if($sql_logic == 'success'){
// give JSON back to AJAX call
echo json_encode(array('success'=>'yes'));
}
else{
// give JSON back to AJAX call
echo json_encode(array('success'=>'no'));
}
?>
var postdata={};
postdata['num']=x;
while (i <= x){
postdata['fname'+i]= name[i];
postdata['lname'+i]= lname[i];
postdata['email'+i]= email[i];
i++;
}
$.ajax({url : 'process.php',
type:"POST",
data:postdata,
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
PHP
$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
echo $_POST['fname'.$i];
echo $_POST['lname'.$i];
echo $_POST['email'.$i];
}
I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.
Below is the code for the ajax call.
$.ajax({
url: 'php/update_group_list.php',
data: '',
dataType: 'json',
success: function(data) {
var id = data.instructor_id;
group_cnt = data.group_cnt,
group_name = data.group_name,
group_code = data.group_code;
for (i = current_row; i < group_cnt; i++)
{
//setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);
$('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
$('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
"<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
"<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
"</fieldset>");
}
current_row = i;
$('#group-list').listview('refresh');
$('#delete-group-list').trigger('create');
}
});
Now I am having two problems
FIRST PROBLEM:
When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.
$(".view-group-btns").click(function()
{
alert("check");
});
SECOND PROBLEM:
Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <
What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.
Here is extra code relating to the SECOND problem
HTML:
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
<h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
<div style='margin-top: 20px;'></div>
<div id='delete-group-list'>
</div>
<div style='margin-top: 20px;'></div>
<input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>
</form>
JS Code
$('#delete-group-form').submit(function(e)
{
e.preventDefault();
alert($('#delete-group-form').serialize());
if ($('#delete-group-form').serialize() == "")
{
alert('No groups selected to be deleted.')
return false;
}
else
if ($('#delete-groups-form').serialize() == null)
{
alert('No groups selected to be deleted.')
return false;
}
else
{
$.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data)
{
obj = jQuery.parseJSON(data);
var group_codes = obj.group_list;
alert(group_codes);
alert("The selected groups have been deleted");
window.setTimeout(2000);
return false;
});
}
return false;
});
delete_groups.php
<?php
$group_codes = $_POST['groups'];
$items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
echo json_encode($items); //sending data back through json encoding
?>
I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.
You need to use event delegation to make your newly-created elements function properly:
$("#group-list").on("click", ".view-group-btns", function() {
alert("check");
});
I noticed you have 3 single quotes on this line... missed one after controlgroup
$('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
That would explain the unexpected token <
You have to use the jquery on event.
$(".view-group-btns").on("click", function(event)
{
alert("check");
});
Why?
Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.
When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.
on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.
You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.
$.ajax({
success : function(res){
//bind your click function after you update your html dom.
}
})
I am building a review system with php jquery and ajax. I have written the following code already for the 'Was this review helpful?' button:
<input type='button' value='Yes' onClick = 'myCall()'
style='background-color:#556B2F;color:white;padding:2px; cursor:pointer'
name='help' />
<input type='hidden' id='randomdirectory' value='$g' name='ids'/>
$g is the variable I assigned to the id of the review which is stored in a database. The ajax script is this:
<script>
function myCall() {
var ids = $('#randomdirectory').val();
var self = this;
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('#ques1').hide();
}
});
}
and the code in the "rev.php" file is this:
<?php
include 'includes/db.php';
$q = $_POST['ids'];
if ($q != ""){
$result = mysql_query("SELECT * FROM table where id='$q'");
while($row = mysql_fetch_array($result))
{
$finalproduct = $row['numberofhelpfulvotes'];
$finalproduct1 = $finalproduct + 1;
}
mysql_query("UPDATE table SET numberofhelpfulvotes='$finalproduct1' WHERE id ='$q'");
}
?>
The problem is when I have multiple reviews on the page. When you click any of the "Yes" buttons on any of the reviews, the first review displayed gets the vote added to it, not the actual review where the button was clicked. Also when the button and text is hidden after the ajax call, the first review button and text is hidden, not the review where the button was clicked. Also a black line appears on the bottom of the page.
Any solutions to these problems will be greatly appreciated.
Thanks for all reply's. I ended up doing this which works perfectly for me:
<script>
$(function() {
$(".button").click(function() {
var ids = (this.id);
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('.' + ids).hide();
}
});
});
});
</script>
and this as the html:
<div class='$g'><font size='2' color='black'>Was this review helpful?</font> <input type='submit' value='Yes' onClick = 'myCall()' style='background-color:#556B2F;color:white;padding:2px; cursor:pointer' name='help' id='$g' class='button' /><input type='hidden' id='randomdirectory' value='$g' name='ids'/>
The php stayed the same, but I am going to update it to make it more secure.