PHP not capturing data sent on jquery submit - javascript

;;I have a form which allows users to dynamically add a new form input row. Each time a user creates a new row. The inputs are added as an array:
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year[]" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week[]" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"> </td><td colspan="2"> </td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual[]" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td></tr>';
$('#data').append(strToAdd);
});
});
Check the Fiddle
The problem I'm having is when I submit the form. I'm not able to capture any of the data through my php:
$("#upload").validate({
submitHandler: function (form) {
$.ajax({
url: '<?php echo base_url(); ?>/ajax_upload',
type: 'POST',
data: $(form).serialize(),
success: function(data) {
if(data)
{
alert("success");
} else {
alert("error");
}
},
error: function(data){
alert("error");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
When executing this code:
var_dump($_POST['year']); or echo count($_POST['year'])
I receive the following error: Message: Undefined index: year
In my firebug under the console view. POST I see the data is being posted
year%5B%5D=2012&week%5B%5D=1&actual%5B%5D=test&year%5B%5D=2011&week%5B%5D=2&actual%5B%5D=test+2&items
=3&sub=Submit+values
but it still doesn't seem to be capturing.
Any help will be appreciated

Related

Ajax post with php-mysql is not working properly

I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});

Jquery autocomplete using typeahead suggestion does not display after a successful ajax

I use typeahead.js to put tags for my multiple input. The tags input function correctly except the fact that its autocomplete suggestion does not come out. Is there any way to correct this problem?
I've tried most solution related to my problem that are already on this site but currently still not be able to display the autocomplete suggestion. I am always stuck at the successful ajax response and that's it.
my jquery:
<script>
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json){
return json.s_to;
}
});
}
}
});
</script>
my input :
<input required type="text" name="s_to" id="s_to" class="controls uk-autocomplete-results" value="<?php echo $s_client_email; ?>" autocomplete="on" data-provide="typeaheadjs" />
my related script:
<script src="<?php echo base_url(); ?>assets/bower_components/typeahead.js/typeahead.jquery.min.js"></script>
console log output screen shot
Supposedly the input able to receive multiple input and each input seleccted will be displayed inside a tag. What make it harder is that no error message displayed. Thus, I know that my ajax is done correctly.
The main issue is that you do not return the array in correct scope. Your return json.s_to; is inside the ajax success function, but you need to return the value in parent scope. So, the code should be like this:
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
var toReturn = [];
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json) {
toReturn = json.s_to;
}
});
/* This is the correct scope to return the array */
return toReturn;
}
}
});

Array Passing through javascript

Here is my view:
<div class="form-group col-md-3">
<label class="sup col-md-12 control-label">Employees</label>
<?php
if(isset($hiddenEmpArray)){
if(is_array($hiddenEmpArray)){
foreach($hiddenEmpArray as $hiddenEmpArraySingle){
echo '<input type="hidden" name="selectall[]" id="selectall" value="'. $hiddenEmpArraySingle. '">';
}
}
}
?>
</div>
Javascript:
$('#form').submit(function(e){
e.preventDefault();
var selectall =$("#selectall").val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: {selectall:selectall},
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
Here I want to Submit this form through javascript.Here selectall is an array.When I Submit the form,Only One value is received .How Can I pass this array through javascript.Please help me
The serialize() method creates a URL encoded text string by
serializing form values.
$('#form').submit(function(e){
e.preventDefault();
var formId = $(this).attr('id');//getting form id
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: $('#' + formId).serialize(),//jquery id selector for the form
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
you can just use this
var selectall = $("input[name='selectall[]']").map(function(){return $(this).val();}).get();
and then in success just do console.log(data);
you may use jquery each function to collect data
var selectall=[];
$.each($("input[name='selectall[]']"), function(){
selectall.push($(this).val());
});

AJAX .html(data) not displaying if I attempt to restore original content afterwards

I'm using the following js to handle an ajax request
$(document).ready(function() {
// Variable to hold original content
var original_content_qty = '';
$('.product-qty-<?php echo $products->fields['
products_id ']; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'html'
}).done(function(data) {
original_content_qty = $('.qty-update-<?php echo $products->fields['
products_id ']; ?>').html();
console.log(original_content_qty);
console.log(data);
$('.qty-update-<?php echo $products->fields['
products_id ']; ?>').fadeOut('slow', function() {
$('.qty-update-<?php echo $products->fields['
products_id ']; ?>').fadeIn('slow').html(data); //display a success message sent back via ajax
$('.qty-update-<?php echo $products->fields['
products_id ']; ?>').delay(1200).fadeOut('slow').html(data);
$('.qty-update-<?php echo $products->fields['
products_id ']; ?>').html(original_content_qty); // restore original content after success message
});
}).fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
If I dont have the line
$('.qty-update-<?php echo $products->fields['products_id']; ?>').html(original_content_qty);
the success message displays correctly, then fades out as required.
But as soon as I add the line to restore the original content it appears as though it displays original content, fades out, then replaces original content.
I don't see any reason why my success message isn't displayed just because I added the line to restore content.
Console log for the data from ajax show me
<style>.block .notice.invalid{display:none;}</style>
<div class="alert alert-info">
<strong>Stock updated</strong>
</div>
This is the same regardless of whether I attempt to restore content or not.
Console log for original_content_qty is
Stock: <input type="hidden" name="products_id" value="289"><input type="text" name="products-quantity" value="0" size="4" class="product_quantity_input_289">
Have I made an error in the way I'm trying to restore the content?
I fiddled something together, you need to chain the steps into their own callbacks
$(document).ready(function() {
// Variable to hold original content
var original_content_qty = '';
var form = $('.product-qty-42')
form.submit(function(e) {
e.preventDefault();
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'html'
})
.done(function(data) {
var elem = $('.qty-update-42');
var original_content_qty = elem.html();
console.log(original_content_qty);
console.log(data);
elem.fadeOut('slow', function() {
elem.html(data).fadeIn('slow', function() {
elem.delay(1200).fadeOut('slow', function() {
elem.html(original_content_qty).fadeIn('slow');
});
});
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
$.mockjax({
url: "submit.php",
responseText: '<p>Worked</p>'
});
<form class="product-qty-42">
<div class="qty-update-42">
<input type="hidden" name="products_id" value="289"><input type="text" name="products-quantity" value="0" size="4" class="product_quantity_input_289">
</div>
<input type="submit" name="send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>

PHP Serialize on ajax array Not Working

I have the following HTML fields being created inside a PHP look
<td><input type=\"checkbox\" name=\"investigator_id[]\" id=\"investigator_id\" value=\"$name_degree[$i]\">
<td><input type=text name=\"inv_rank[]\" id=inv_rank maxlength=\"2\" size=\"2\"></td>
<td><textarea name=\"inv_comm[]\" id=inv_comm rows=2 cols=20></textarea></td>
I am trying to save the data in these fields by calling a jquery function based on clicking on this button
Here is the script that is being called. I know that the js is being called because the "alert("now")" is poping up, but the dataString is not being populated correctly. I tested this on http://jsfiddle.net/ and it worked fine, but won't work on my site.
<script>
$(document).ready(function() {
$("#submit").click(function() {
alert("now");
var dataString = $("'[name=\"investigator_id\[\]\"]', '[name=\"inv_rank\[\]\"]','[name=\"inv_comm\[\]\"]'").serialize();
alert("ee"+dataString);
$.ajax({
type: "POST",
url: "save_data.php",
dataType: "json",
data: dataString,
success: function(data){
alert("sure"+data);
$("#myResponse").html(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error.");
}
});
});
});
</script>
Try this with the help of FormID like this:
<form method="post" id="yourFromID">
//Your form fields.
</form>
JS Code:
$("#yourFromID").submit(function (e){
e.preventDefault();
var dataString = $(this).serialize();
// then you can do ajax call, like this
$.ajax({
url: 'site.com',
data: dataString,
methodL 'post',
success: function(){...}
})
return false;
});

Categories