Update data using AJAX and codeigniter failed - javascript

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

Related

Confirmation Message not working Using Ajax Codeigniter

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

Ajax submit doesn't work (can't read $_POST in php)

I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php
$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])
test.php
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
}
?>
<html>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>
test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = "textbox=" + inputText;
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
There're more of problems here
In test.php
how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad
Scripts should be on the <head></head> or before </body>
while you using just button click why you're using <form>
your code should be something like that
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
return false;
}
?>
<html>
<head>
</head>
<body>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</body>
</div>
</html>
On test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs
If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault(); // to prevent form reload
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
});
});
you never test if you see the reponse from echo - hence you don't alert the response from php at all.
To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:
....
success: function (response) {
alert(response);
console.log(response);
},
....
Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.
Also follow #Mohammed-Yousef's instructions for the other issues!!
you will get the desired results in the response.
function hit() {
var inputText = $("#input").val();
$.ajax({
type: 'post',
url: 'test.php',
data: {textbox : inputText},
success: function (res) {
alert(res);
}
});
}
And you need to change in your test.php file.
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];exit;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="test2.js"> </script>
</head>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Insert Data into MySQL without reloading the page (Jquery)

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

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');
}

Categories

Resources