I need some help to resolve a problem.
I'm trying to send some datas from a form ROW to a php file.
Here's the first php code (It's inside an echo and value come from a MySQLi query):
<form id=\"comedivid\" method=\"post\">
<input class=\"numer-qua\" type=\"number\" id=\"dadivid\" min=\"0\" max=".$_GET['qua']." autofocus autocomplete=\"off\" name=\"dadivid\" maxlength=\"4\" size=\"5\">
<input type=\"hidden\" value=\"".$row["id_tes"]."\" name=\"ord\" id=\"ord\">
<input type=\"hidden\" value=\"".$_GET['codice']."\" name=\"cod\" id=\"cod\">
<input type=\"hidden\" value=\"".$_GET['qua']."\" name=\"arr\" id=\"arr\">
<input type=\"hidden\" value=\"".$row['descri']."\" name=\"desc\" id=\"desc\">
<input type=\"hidden\" value=\"".$row['unimis']."\" name=\"um\" id=\"um\">
<input type=\"hidden\" value=\"".$row['quanti']."\" name=\"qua\" id=\"qua\">
<input type=\"hidden\" value=\"".$row['prelis']."\" name=\"pre\" id=\"pre\">
<input type=\"hidden\" value=\"".$row['sconto']."\" name=\"sco\" id=\"sco\">
<input type=\"hidden\" value=\"".$row['codvat']."\" name=\"cva\" id=\"cva\">
<input type=\"hidden\" value=\"".$row['pervat']."\" name=\"iva\" id=\"iva\">
<input type=\"hidden\" value=\"".$row['codric']."\" name=\"ric\" id=\"ric\">
<button id=\"dividili\" class=\"btn btn-blue\" type=\"submit\"><i class=\"fa fa-copy\"> Dividi Riga</i></button>
\n";
The form is included in a table. The query may give more as one result.
Here's my AJAX code:
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var dadivid = $("#dadivid").val();
var ord = $("#ord").val();
var cod = $("#cod").val();
var arr = $("#arr").val();
var desc = $("#desc").val();
var um = $("#um").val();
var qua = $("#qua").val();
var pre = $("#pre").val();
var sco = $("#sco").val();
var cva = $("#cva").val();
var iva = $("#iva").val();
var ric = $("#ric").val();
$.ajax({
type: "POST",
url: "../../modules/acquis/dividi.php",
data: "dadivid=" + dadivid + "&ord=" + ord + "&cod=" + cod + "&arr=" + arr + "&desc=" + desc + "&um=" + um + "&qua=" + qua + "&pre=" + pre + "&sco=" + sco + "&cva=" + cva + "&iva=" + iva + "&ric=" + ric,
success: function(){alert('success');}
});
});
});
It's not working, no data are sent to URL.
Is it because the form is in more rows?
Or is there a mistake in my code?
I tried with serialize also, with no results.
Here's the code:
$("#dividili").click(function(e){
$.ajax( {
type: "POST",
url: "../../modules/acquis/dividi.php",
data: $('#comedivid').serialize(),
success: function( response ) {}
});
});
Thank you so much for your help!
I would suggest using serialize():
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var form_data = $('form#comedivid').serialize();
// or
var form_data = $(this).serialize();
// try to output that just to make sure you are doing it right
console.log( form_data );
// or
alert( form_data );
$.ajax({
type : "POST",
url : "../../modules/acquis/dividi.php",
data : form_data,
success : function(){alert('success');}
});
});
Since you already tried that, and if the output is ok, then it's a problem with your PHP, so try to output at the beginning of your file what was received:
<?php
echo '<pre>';
print_r( $_POST );// or $_REQUEST for both $_POST and $_GET
echo '</pre>';
die;
// the rest of your code...
If everything is received well in PHP, you need to make sure you are using the right way to fetch your data, like $dadivid = $_POST["dadivid"];
jQuery 'serialize' method made data like get query form.
so, Data length would be limited in apache configuration.
Try use this custom method.
(function($) {
$.fn.serializeObject = function () {
"use strict";
var result = {};
var extend = function (i, element) {
var node = result[element.name];
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
});
How to use is same default jQuery 'serialize' method.
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 have a form created from the following action,
USER selects a link
using $('#livesearch').on('click', 'a', function(e){}); accesses and gets some information from MySQL db through .php via AJAX call
based on the response data, it populates the content div in the bootstrap 3 modal window
in the modal window populated via javascript, I have another form field for submission,
in this form field, I'm trying to do a POST/Response through AJAX call and it just takes me to the php page and not doing anything..
suppose is it not possible to AJAX on a form field dynamically generated by another AJAX call?
to explain in more detail, I've included my codes here below,
for point 3 and 4,
// AJAX call from a link selected
$('#livesearch').on('click', 'a', function(e) {
var selectedValue = $(this).attr("value");
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
// populates contents for the modal body
$.each( selectedData, function( i, val ) {
document.getElementById("measures").innerHTML+= "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td><td rowspan=\"4\">Quantity"
+ "<form role=\"form\" action=\"../../../avocado/private/functions/food_save.php\" id=\"measure_quantity\" method=\"POST\">"
+ "<div class=\"form-group\">"
+ "<label class=\"sr-only\" for=\"quantity\">quantity</label>"
+ "<input type=\"Number\" name=\"quantity\" class=\"form-control\" id=\"quantity\" placeholder=\"desc"+i+"\">"
+ "<input type=\"hidden\" id=\"food_name\" name=\"food_name\" value=\""+selectedValue+"\">"
+ "<input type=\"hidden\" name=\"food_type\" value=\"nutrients\">"
+ "<input type=\"hidden\" name=\"food_id\" value=\""+selectedData[i][0]+"\">"
+ "<input type=\"hidden\" name=\"measures_id\" value=\""+selectedData[i][4]+"\">"
+ "<input type=\"hidden\" name=\"grams\" value=\""+selectedData[i][10]+"\">"
+ "</div>"
+ "<button type=\"submit\" class=\"btn btn-default\">Save</button>"
+ "</form>"
+ "</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "<tr><th>(g)</th><td>"+selectedData[i][10]+"</td></tr>"
+ "</table>";
});
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
});
for point 5,
$('#measure_quantity').submit(function(){
postData = $(measure_quantity).serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
Try something like the below:
$( "#measure_quantity" ).on( "submit", function( event ) {
event.preventDefault();
postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
This will still work with dom elements that do not exist on the initial page load because of the .on() statement.
Also its not something silly like the typo:
postData = $(measure_quantity).serialize();
Should be...
postData = $("#measure_quantity").serialize();
I have found the problem, for dynamically loaded contents such as this case, I have to add a selector parameter otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content
$(document.body).on('submit', '#measure_quantity' ,function(e){
console.log("heeeellllo");
e.preventDefault();
var postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
But then again, I have another question... if the modal window has already been populated with the form, direct bound method should work fine right? still kind of cloudy on what direct and delegated bound means.. and what the difference between the two is,
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.
My ajax call goes and enters a record into a database (it's the first part of a form recording data) so I need it to return the id from the database entry.
Problem is, it's firing twice, so it's making 2 database entries each time.
I tried using a $count and while($count>0) in my php code to make sure that wasn't looping - and I didn't think it was, so the problem lies in my jQuery.
I tried putting the preventDefault on my submit button click function and that didn't work either.
Here's my code:
$(document).ready(function(){
$('#wpgstep1').one('click',function(){
// validate form fields are all filled in
var budget=$('#budget').val();
if(budget=='')
{
$('#budgeterror').show();
}
var yellowpages=$('#ads-yellowpages').val();
var flyers=$('#ads-flyers').val();
var brochures=$('#ads-brochures').val();
var radiotv=$('#ads-radiotv').val();
var none=$('#ads-none').val();
var other=$('ads-other').val();
var otherstatement=$('ads-other-statement').val();
var cust_id=$('#cust_id').val();
if(other !='')
{
if(otherstatement==='')
{
$('#adsothererror').show();
}
}
else
{
otherin='0';
}
if(yellowpages==="on")
{
yellowpagesin='1';
}
else{
yellowpagesin='0';
}
if(flyers==="on")
{
flyersin='1';
}
else
{
flyersin='0';
}
if(brochures==="on")
{
brochuresin='1'
}
else
{
brochuresin='0';
}
if(radiotv==="on")
{
radiotvin='1';
}
else
{
radiotvin='0';
}
if(none==="on")
{
nonein='1'
}
else
{
nonein='0';
}
var dataString='cust_id=' + cust_id + '&step=1&budget=' + budget + '&yellowpages='+yellowpagesin + '&flyers=' + flyersin + '&brochures=' + brochuresin + '&radiotv='+ radiotvin + '&none='+ nonein + '&other=' + otherstatement;
$.ajax({
type: "POST",
url: "submitwpg.php",
data: dataString,
dataType:'json',
success: function(data)
{
alert(data);
var i="";
var p=eval (data);
for (i in p)
{
$('#wpgpart2').append('<input type=hidden name=wpgid value=' + p[i] + '>');
}
$('#wpgform1').hide();
$('#wpgform2').show();
}
});
return false;
});
});
Make a global var
var form_submitting = false;
Above your ajax call
if(form_submitting == false){
form_submitting = true;
//your ajax call
}
In your success function of your ajax call
form_submitting = false;
if your submit button is inside of a form, it may be possible that your ajax function is executing and then your form is posting regularly. You could try turning your
<input type='submit' />
into
<button type='button' onclick='validateAndAjaxFunction(); return false;'></button>
What i am doing:
I am appending a div with a form and some buttons.The two buttons are save and cancel.When save is clicked,i am posting the form and getting the response.I want to replace the old div that houses the save was clicked.
This is the html and jquery http://jsfiddle.net/thiswolf/vSnJJ/1/
I am using this php but the post data is not sanitized since its an example
<?php
/**
test if replaced item can post and be deleted
#move ---->next
*/
$sliderKey = $_POST['sliderKey'];
$sliderPosition = $_POST['sliderPosition'];
$sliderTitle = $_POST['sliderTitle'];
$sliderLocation = $_POST['sliderLocation'];
$sliderDescription = $_POST['sliderDescription'];
$uniqid = uniqid();
echo "<div class='krudItem' id='$uniqid'><form class='aj' name='itemForm' method='post'action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='$sliderKey'/><input type='hidden' name='sliderPosition' value='$sliderPosition'/><input type='text' name='sliderTitle' value='$sliderTitle'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='$sliderLocation'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>THIS IS THE REPLACEMENT</textarea></section><button name='saveNew' class='saveNew' id='$uniqid'>save</button><button name='newCancel'>delete</button></form></div>";
?>
This is the entire jquery i am using
jQuery(function() {
function randString(n)
{
if(!n)
{
n = 5;
}
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0; i < n; i++)
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
$("#button").click(function () {
$("<div class='krudItem' id='xxx'><form class='aj' name='itemForm' method='post' action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='16'/><input type='hidden' name='sliderPosition' value='12'/><input type='hidden' name='clickedButton' value='initial'/><input type='text' name='sliderTitle' value='lorem'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='ipsum'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>hello world</textarea></section><button name='saveNew' class='saveNew' id='buttonId' value='saveNew'>save</button><button name='newCancel'>cancel</button></form></div>").appendTo('.krudSpace');
});
//save new
jQuery('.saveNew').live("click",function(event)
{
jQuery(this).attr("id",randString(7));
event.preventDefault();
var contentPanelId = jQuery(this).attr("id");
jQuery.ajax({
type: "POST",
url: "insert.php",
data: jQuery(".aj").serialize(),
success: function(data){
var quoted = "#"+contentPanelId;
jQuery(quoted).replaceWith(data)
}
});
return false;
});
});
It works to some extent but the old div is not replaced at all but the response is appended below the old.
You're making things difficult. Just save the parent itself:
var $p = jQuery(this).parent();
and do:
$p.replaceWith(data)
Here's an updated jsFiddle (it uses error rather than success because there is no PHP): http://jsfiddle.net/vSnJJ/2/.