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>
Related
I want to add have a form in my Wordpress dashboard that work with ajax but my request response is 400 Bad request
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
?>
I also add:
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
and
function submit_vitrin_pm() {
echo 'ssss';
die();
}
I checked, your ajax response is working, you didn't share your html form, i added a form for check.
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<form action="#" method="POST" class="vitrin-private-message-form">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input
type="text"
class="form-control"
id="pmcontent"
name="name"
placeholder="Full Name"
/>
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input
type="text"
class="form-control"
id="pmusers"
name="email"
placeholder="email#example.com"
/>
</div>
<button type="submit" class="btn btn-success">
Submit
</button>
</form>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
console.log('working')
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
function submit_vitrin_pm() {
echo 'ssss';
die();
}
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
}
I am fetching data from database using ajax in codeigniter and now i am trying to put "delete confirmation box"
in controller but that button is not working,
Here is controller file/code
$user['result']=$this->crud->AddMember($data);
foreach($user['result'] as $row) {
echo "<td>";
<input type="hidden" name="id" value="'.$id.'">
<input type="submit" class="btn btn-danger btn-sm" value="Delete" name="delete" onclick="return confirm('Are you sure you want to delete this item')">
</form>';
echo "</td>";
}
Here is view file
<form method="post" name="myForm" class="form-horizontal" id="user_form" enctype="multipart/form-data">
<input type="text" class="form-control" id="FlatNumber" name="FlatNumber" placeholder="">
<button type="submit" class="btn btn-primary btn-lg" id="butsave">Add Details</button>
</form>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
event.preventDefault();
var FlatNumber = $('#FlatNumber').val();
if(FlatNumber == '') {
alert("Please enter Flat Number");
}else{
$.ajax({
url:"<?php echo base_url() . 'index.php/Member/AddRecord'?>",
type: "POST",
data: {FlatNumber : FlatNumber},
dataType: "html",
success: function(msg){
alert(msg);
if (msg == 'exist') {
$("#successs").hide();
}else{
$("#errorr").hide();
}
}
});
}
});
});
</script>
It is because onclick works only for elements who already on this page. after ajax response it will not work so you need to use code like this.
$(document).on("click",".btn-danger", function(){
});
I want to update my data using Codeigniter and AJAX for submit response..
This is my View
<form id="form_update" action="<?php echo base_url() ?>admin/update_derap_info" method="POST" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" >
</textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan">
</form>
My Controller
$data = array
(
'isi'=> ltrim(rtrim($this->input->post('isi')))
);
$this->info_derap->update($this->input->post('id_info'),$data);
echo'<div class="alert alert-success">Terimakasih, pesan anda sudah kami terima. Pemberitahuan selanjutnya kami beritahunak lewat email.</div>';
exit;
My Model
function update($id,$data){
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
And here is my AJAX
<script type="text/javascript">
$("#form_update").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:$("#form_update").serialize(),
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
</script>
I can update My data if I press click submit 2 times, but when I submit just 1 time , it cannot update.
What's wrong?
You cant update with form. Use this
<form action="" method="" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" ></textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan" id="form_update">
</form>
in AJAX
<script type="text/javascript">
$(function(){
$("#form_update").click(function(event){
event.preventDefault();
$("#loader").show();
var editor1= $("#editor1").val();
$.ajax(
{
type:'post',
url:"<?php echo base_url() ?>admin/update_derap_info",
data:{editor1:editor1},
success:function($data)
{
$("#response").html(data);
$("#loader").hide();
fillgrid();
}
});
});
});
</script>
in Controller
$text_area = $this->input->post('editor1')
So in $text_area Contain text which you input in your form
You should use the following code on your controller:
$this->info_derap->update($this->input->post('id_info'),$data);
Also, make sure there's a field called id_info in the corresponding view.
what a message if you using debug, you can inspect request...
you can insert or adding some javascript function "espace" your request form for example
escape($("editor1").val());
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>
<?}?>