Insert Data into MySQL without reloading the page (Jquery) - javascript

Here is my code:
HTML Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<script src='insert.js'></script>
Insert.JS file code:
$('.myform').submit(function(){
return false;
});
$('.insert').click(function(){
$.post(
$('#.yform').attr('action'),
$('.myform :input').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
Expected Result: When user clicks on Insert button, the code runs insert.php file in the background (No reloading of the page), and display the result inside this <p id='result'></p>
Original Result: Only the first insert button code works. The other insert button redirects the user to insert.php.
I know, This is probably because of some same classes. But I do not know, how to fix it. I would like to make changes only in my Jquery code. I do not want to add different classes for each form.

Instead of dealing with click events, you could override default forms' submit behavior and use $(this) to work only with form being submitted.
$(".myform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var resultDiv = $(this).find(".result");
$.post(url, data, function(result) {
resultDiv.html(result);
});
return false;
});
grab the forms and override their submit function
get the data from the form that is being submitted
get the url to post to from this very form
grab immediate child result (instead of all of them)
pass your own success function to do whatever you need, in this case append the result
Modify this code if you want to post data from all the forms at once.

Sir I think You need to try Just Ajax code like this.
$.ajax({
url: 'URL_OF_YOUR_PAGE',
data: $('.myform :input').serializeArray(),
type: 'POST',
dataType: 'json',
success: function (r) {
//SUCCESS CODE
}
});

There is an error in your js code. change like this:
$('.insert').click(function(){
$.post(
$('.myform').attr('action'),
$('.myform :input').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
jquery selector error

You can use jQquery AJAX method with multiple options and you need to disable the button after click, this will avoid multiple request to the server.
//button click
$(".insert").click(function(e){
//get the form data and serialize
var dataString = $(".myform").serialize();
//make the AJAX request, dataType is set to json
$.ajax({
type: "POST",
url: "SERVER_URL",
data: dataString,
dataType: "json",
//response from the server
success: function(data) {
console.log("SUCCESS");
},
//No response from the server
error: function(xhr){
console.log("ERROR :" + xhr.statusText);
},
//capture the request before it was sent to server
beforeSend: function(){
// disable the button
$(this).attr("disabled", true);
},
//after the response
complete: function(){
//enable the button
$(this).attr("disabled", false);
}
});
});

You can get a reference to the form in your click handler using closest
var theForm = $(this).closest('form');
Then you can read that form's action and serialize that forms data:
$('.insert').click(function(){
var theForm = $(this).closest('form');
$.post(
theForm.attr('action'),
theForm.serializeArray(),
function(result){
$('.result').html(result);
}
);
return false;
});
Here's a mock that outputs the forms data into a text box using the same approach:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id0'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id1'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id2'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<textarea id='out' style="width:600px;height:250px"></textarea>
<script src='insert.js'></script>
<script>
$('.myform').submit(function(){
return false;
});
$('.insert').click(function(){
var theForm = $(this).closest('form');
var mockData= {};
mockData["action"] = theForm.attr('action');
mockData["data"] = theForm.serializeArray();
$('#out').val(JSON.stringify(mockData));
/* $.post(
theForm.attr('action'),
theForm.serializeArray(),
function(result){
$('.result').html(result);
}
return false;
);
*/
});
</script>

If you want to submit of your second form then attached an id to that form, and submit your form data by that id. If your provided code fine then this code should be worked. If your three forms have same class then you can not catch that form uniquely from jquery side only.
$('.myform').on('submit',function(e){
e.preventDefault();
});
$('.insert').click(function(){
$.post(
$('.myform').attr('action'),
$('#secondForm').serializeArray(),
function(result){
$('.result').html(result);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' id="firstForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' id="secondForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' id="thirdForm" class='myform' >
<input type='hidden' name='tmdb_id'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>

Try this
HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='2'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='3'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<form action='insert.php' method='post' class='myform' >
<input type='hidden' name='tmdb_id' value='6'/>
<button class='insert'>Insert</button>
<p class='result'></p>
</form>
<script src='insert.js'></script>
insert.js code:
$('.myform').submit(function(){
return false;
});
var elements = document.getElementsByClassName("insert");
$('.insert').click(function(){
for (var i = 0, len = elements.length; i < len; i++) {
if(elements[i]===this){
var j=i;
$.post(
$(document.getElementsByClassName("myform")[j]).attr('action'),
$(document.getElementsByClassName("myform")[j]).serializeArray(),
function(data){
$(document.getElementsByClassName("result")[j]).html(data);
}
);
}
}
});
insert.php code:
var_dump($_POST);

Related

Cannot pass value to Codeigniter controller using ajax

I am having a trouble while sending a value from an input element to Codeigniter controller by using ajax.
Since I have to use WYSIWYG editor (summernote), thus I can just receive the input inside a <script>. However when I press the submit button, it just reloads the current page rather than the one in the controller.
Here is my code:
PHP view
<section id="mainContent">
<form method="post">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit" onclick="myFunction()">
</form>
</section>
<script type="text/javascript">
function myFunction() {
var markupStr = $('#textbox').summernote('code');
alert(markupStr);
$.ajax({
type : 'POST',
url : "<?= site_url().'cintern/save'; ?>",
async : false,
data : {'iDes': markupStr},
success : function(data){
alert("Success!");
}
});
return false;
};
</script>
PHP controller
public function save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $this->input->post('iDes');
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}
Please help! Thank you in advance.
You should use onsubmit of <form> tag instead.
<section id="mainContent">
<form method="post" onsubmit="myFunction()">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
The reason is, if you handle the onclick of your <input type="submit">, you can't intercept request of <form> tag after submit data.
I hope this can help you.
Since you are using JQuery for the ajax I suggest you use it to capture the submit also.
Remove the inline onclick assignment. Give the form an id attribute.
<section id="mainContent">
<form method="post" id="target">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
Turn myfunction() into a 'submit' event handler
<script type="text/javascript">
$("#target").submit(function (event) {
var markupStr = $('#textbox').summernote('code');
//stop the normal submit from happening
event.preventDefault();
$.ajax({
type: 'POST',
url: "<?= site_url().'cintern/save'; ?>",
async: false,
data: {'iDes': markupStr},
success: function (data) {
//do stuff with data then redirect to 'after_save'
console.log(data.results, data.otherstuff);
window.location.href = "http://example.com/cintern/after_save";
}
});
});
</script>
Controller:
public function save()
{
$data = $this->input->post(NULL, TRUE);
// $data is now a semi-sanitized version of $_POST
$_SESSION['iDes'] = $data['iDes'];
//do other stuff with $data
echo json_encode(['results' => "success", 'otherstuff' => $foo]);
}
public function after_save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $session_data['iDes'];
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}

Update data using AJAX and codeigniter failed

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());

How to post mutliple forms from a webpage

I want to post 2 forms using javscript, but I can't seem to figure it out. Can someone help me?
It seems like I need to submit the first form Async according to this but I don't follow their code: Submit two forms with one button
HTML
<form name="form1" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" target = "me1">
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<form name="form2" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" >
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<input name="submit" value="Submit Form" onclick="submitForms ()" type="button">
JS
function submitForms(){
document.forms["form1"].submit(); /* should be Async?*/
document.forms["form2"].submit();
}
var str1 = $( "form1" ).serialize();
var str2 = $( "form2" ).serialize();
ajaxReq(url,str1);
ajaxReq(url,str2);
function ajaxReq(url,data){
var request = $.ajax({
url: url,
type: "POST",
data: data,
dataType: "html"
});
request.done(function(html) {
console.log('SUCCESS')
});
request.fail(function( jqXHR, textStatus ) {
console.log("AJAX REQUEST FAILED" + textStatus);
});
}

How to get value from other when using ajax post?

How to get value from other when using ajax post ?
i want to get value from input type="text" class="nextpage" in demo.php
to input <input type='hidden' id='page_number' name='page' value='1'/> in index.php
i try to do like this code but not work , How can i do that ?
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ // onload page for load content //
document.getElementById('page_number').value = '1';
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx1').serialize(),
cache: false,
success: function (data) {
$("#results").append(data);
function_two();
}
}
)
});
</script>
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<script>
$(document).ready(function(){ // click button for load content //
$("#Button").click(function(e){
var page = $('#results').find('.nextpage').val();
document.getElementById('page_number').value = page++;
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx2').serialize(),
cache: false,
success: function (data) {
$("#results").append(data);
function_two();
}
}
)
});
});
</script>
<form method="post" id="xxx2" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<div id="results" style=" width: 100%; "></div>
<input type="submit" id="Button" value="OK">
demo.php
<?PHP
$page = $_POST[page];
$nextpage = ($page+1);
?>
<input type='text' class='nextpage' value='<?PHP echo $nextpage; ?>'>
OK, i get answer , cause of issue from duplicate id name page_number
just change
document.getElementById('page_number').value = '1';
to
document.getElementById('page_number_1').value = '1';
and change
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
to
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number_1' name='page' value='1'/>
</form>
it's will work.......
I modified your code little bit. Instead returning entire HTML input from the PHP page, I just return the page number and append the input from the front end using jquery.
Hope this will work for you
**index.php**
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ // onload page for load content //
document.getElementById('page_number').value = '1';
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx1').serialize(),
cache: false,
dataType:'json',
success: function (data) {
$("#results").append("<input type='text' class='nextpage' value='"+data.page_number+"'>");
function_two();
}
}
)
});
</script>
<form method="post" id="xxx1" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<script>
$(document).ready(function(){ // click button for load content //
$("#Button").click(function(e){
var page = $('#results').find('.nextpage').val();
document.getElementById('page_number').value = page++;
$.ajax
(
{
url: 'demo.php',
type: 'POST',
data: $('#xxx2').serialize(),
dataType:'json',
cache: false,
success: function (data) {
$("#results").append("<input type='text' class='nextpage' value='"+data.page_number+"'>");
function_two();
}
}
)
});
});
</script>
<form method="post" id="xxx2" action="Javascript:void(0);">
<input type='hidden' id='page_number' name='page' value='1'/>
</form>
<div id="results" style=" width: 100%; "></div>
<input type="submit" id="Button" value="OK">
**demo.php**
<?PHP
$page = $_POST[page];
$nextpage = ($page+1);
if($nextpage){
echo json_encode(array("page_number" => $nextpage));
}
?>

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

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>
<?}?>

Categories

Resources