Ajax - How to submit one by one input value - Codeigniter - javascript

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}

because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Related

PHP Submitting a form without refreshing the page and call a function

We have created a feedback form and once a user submits the feedback, we want to run the function that submits it to Airtable and then show the Next button.
Problem: The jQuery is working, showing the button after submit, but the function in (isset($_POST['submit']) isn't saving at all.
I've read through many posts but can't find the answer. Any help would be great!
Here is our current code
public function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&comments='+comments+'&reason='+reason,
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason2</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
if (isset($_POST['submit'])){
$reason = $_POST['reason'];
$comments = $_POST['comments'];
save($reason, $comments);
}
?>
<?php
}
I assume you want to transfer the entries "reason" and "comment" to the page "requests.php". Then you don't need the second post request because you use ajax:
<?php
function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'get',
data: { 'result' : comments +'*'+reason, 'feedback' : 'true' },
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason3</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
}
The "request.php" looks like this:
<?php
if(isset($_GET['feedback']))
{
$result = $_GET['result'];
$parts = explode("*", $result);
print "reason: ".$parts[1]."<br>";
print "comments: ".$parts[0]."<br>";
}
?>
What I can see from the snippet is that:
if (isset($_POST['submit'])){
While the submit button is:
<input type="submit" value="submit" name="subbtn" >
Just fix this line:
isset($_POST['submit'] to isset($_POST['subbtn']
Hope this helps.

Ajax is not working when I fetch data from MySQL

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>
Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>
NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

Inserting through AJAX page is refreshing [duplicate]

This question already has answers here:
insert query with ajax without reloading whole page
(2 answers)
Closed 4 years ago.
Inserting the data through AJAX it's working but pages refreshing, why is that give a feedback to fix this issues.
This is my ajax code
<script>
$(document).ready(function(){
$("#button").click(function(){
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
Here I'm using HTML
<form>
<input type="hidden" id="postId" name="postId" value="<?php echo $_GET["postId"]; ?>">
<input type="hidden" id="userId" name="userId" value="<?php echo $_SESSION["u_id"]; ?>">
<textarea placeholder="Post your comment" id="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>
You are facing it due to the button having input type “Submit”
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
Just change it to normal “button”
<button type="button " id="button"><i class="fa fa-paper-plane"></i></button>
Easy fix: Add a preventDefault(). Notice the 'e' I added to your click function.
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
You can prevent the default submit button behavior - submitting the form - with event.preventDefault();
<script>
$(document).ready(function(){
$("#button").click(function(event){
// prevent the default submit button behaviour
event.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
another ajax i'm using but some issue is coming page is refreshing.
<script>
function inspire(x){
var insPer =$("#insPer"+x).val();
var insPos =$("#insPos"+x).val();
$.ajax({
url:'../validate/inspire.php',
method:'POST',
data:{
u_id:insPer,
p_id:insPos
},
success:function(data){
//alert(data);
}
});
}
</script>
this is html code
<input type="hidden" id="insPer<?php echo $p_id; ?>" name="insPer" value="<?php echo $_SESSION["u_id"]; ?>">
<input type="hidden" id="insPos<?php echo $p_id; ?>" name="insPos" value="<?php echo $p_id; ?>">
<a href="#" onclick="inspire(<?php echo $p_id; ?>);">
Better do this
$(document).ready(function(){
$("form#comment").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
// console.log(formData);
$.ajax({
url: '../validate/inserPostComm.php',
type: 'POST',
data: formData, //The Form data contain array (postId,userId,postComments)
success: function (data) {
// do something if success
},
error: function(xhr, ajaxOptions, thrownError) {
//If error thrown here
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="comment" method="post" enctype="multipart/form-data">
<input type="hidden" id="postId" name="postId" value="...">
<input type="hidden" id="userId" name="userId" value="...">
<textarea placeholder="Post your comment" id="postComments" name="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>

Update query insert if I want to edit row in PHP

I created a page, where I can easily update or insert data. It actually works, but if I click on the edit button, then I close the modal, then I add new data, it updates the previous data instead of inserting a new row. But if I refresh a page, then I update a row, it works. How can I solve this problem?
index.php:
<form method="post" id="insert_form">
<label><b>Name:</b></label>
<input type="text" name="name" id="name" class="form-control" readonly required />
<br />
<label><b>Description:</b></label>
<input type="text" name="hu" id="hu" class="form-control"></textarea>
<br />
<label><b>Cégek:</b></label>
<select name="company[]" id="company" multiple>
<?php
while($row = $huResult2->fetch_array()) {
?>
<option value="<?php echo $row['company_id'];?>"><?php echo $row['company_name'];?></option>
<?php
}
?>
</select>
<br/><br/>
<input type="hidden" name="data_id" id="data_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
<script>
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$('#name').removeAttr('readonly');
});
// Edit roles
$(document).on('click', '.edit_data', function() {
$("#company option").prop("selected", false);
$("#name").attr('readonly', true);
var data_id = $(this).attr("id");
// Receive the current datas for the roles
$.ajax({
url: "fetchRole.php",
method: "POST",
data: {
'data_id': data_id
},
dataType: "json",
success: function(data) {
$('#name').val(data.name);
$('#hu').val(data.hu);
$.each(data.companies, function(i, e) {
$("#company option[value='" + e + "']").prop("selected", true);
});
$('#company').multiselect('refresh');
$('#data_id').val(data.id);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
$('#insert_form').on("submit", function(e) {
e.preventDefault();
// Update and insert
$.ajax({
url: "insertRole.php",
method: "POST",
data: $('#insert_form').serialize(),
beforeSend: function() {
$('#insert').val("Updating...");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#role_table').html(data);
location.reload();
}
});
});
</script>
Do one thing make data_id field value blank when you are closing the modal
$('#myModal').on('hidden.bs.modal', function () {
$("#data_id").val("");
})
Maybe it will help
or on click of add new button do the same
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$("#data_id").val("");
$('#name').removeAttr('readonly');
});

Ajax form submit without page refresh

I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}

Categories

Resources