Codeigniter + Ajax, can't submit form multiple times without page refresh - javascript

I'm trying to do simple task in one page and avoiding page refresh on every form submit using ajax.
The problem is I can only submit update to database one time and the rest is only console log success without updating database.
Controller
function index() {
$data['process'] = $this->Debug_model->getProcess();
$this->load->view('debug', $data);
}
function nextLine() {
$this->form_validation->set_rules('id', 'ID', 'required');
if ($this->form_validation->run() == FALSE)
{
redirect('debug','refresh');
} else {
$data = array(
'currentLine' => $this->input->post('currentLine'),
'nextLine' => $this->input->post('nextLine')
);
$id = $this->input->post('id');
$this->Debug_model->goNext($data, $id);
}
}
Model
function goNext($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('tbl_process', $data);
}
Javascript
$(document).ready(function() {
finish();
});
function finish() {
setTimeout(function() {
update();
finish();
}, 200);
}
function update() {
$.getJSON("apitest", function(data) {
$("#currentLine").empty();
$("#nextLine").empty();
$.each(data.result, function() {
$("#currentLine").append(
"" + this['currentLine'] + "-" + this['deskNo'] + ""
);
$("#nextLine").append(
"" + this['nextLine'] + "-" + this['deskNo'] + ""
);
});
});
}
//btn save
$("#btnSave").click(function(e){
e.preventDefault();
var data = $('#callLine').serialize();
$.ajax({
type: 'POST',
url: "<?php echo base_url('debug/nextLine'); ?>",
data: data,
success: function() {
console.log('success');
}
});
});
View
<h1>Current: <span id="currentLine"></span></h1>
<h2>Next: <span id="nextLine"></span></h2>
<?php foreach ($process->result() as $singleProcess) :
$tobeCurrent = $singleProcess->currentLine + 1;
$tobeNext = $tobeCurrent + 1;
?>
<form action="" method="post" enctype="multipart/form-data" id="callLine">
<input type="hidden" name="id" value="<?php echo $singleProcess->id ?>" />
<input type="hidden" name="currentLine" value="<?php echo $tobeCurrent ?>" />
<input type="hidden" name="nextLine" value="<?php echo $tobeNext ?>" />
<button id="btnSave" class="btn-a" type="btn">NEXT LINE</button>
</form>
<?php endforeach; ?>
The goal is no page refresh when submitting form and can be done multiple times, still without refreshing the page.

Instead of detecting the event on button click,
detect it on the form submit event.
$("#callLine").submit(function(e){
e.preventDefault();
var data = $('#callLine').serialize();
$.ajax({
type: 'POST',
url: "<?php echo base_url('debug/nextLine'); ?>",
data: data,
success: function() {
console.log('success');
}
});
});
also change the button type to submit instead of btn
<button id="btnSave" class="btn-a" type="submit">NEXT LINE</button>

Related

php query not being processed that has been delivered by ajax post

I got two pages:
Page 1:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$('#mR-RateableFramePicture').dblclick(function () {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
}
});
});
</script>
Page 2:
<?php
session_start();
$userID = $_SESSION["ID"];
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
include '../../scriptMysqli.php';
$sql = $conn->query("UPDATE styles SET savedByUser = '$userID' WHERE userID = '$ratedUserID' AND pictureID = '$ratedPictureID'");
?>
<script>alert("success");</script>
But the $sql variable never gets executed and the part with the alert is not being shown on the original page (page 1) eiher :/
What am I doing wrong here?
From the comments the changed code:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
$('#mR-RateableFramePicture').dblclick(function () {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function(scriptCode) { $('body').append(scriptCode); }
});
});
</script>
The important line is the success handler. It takes the response from your ajax call (echoed by your php script) and add it to the DOM, so it will executed in case of javascript code.

clearing form fields after submitting via ajax not working

I am trying to clear form fields after submitting via ajax but it does not work. Someone please help check my codes and give me some good suggestions. Below is my code:
jQuery(document).on('click', '.um-message-send:not(.disabled)',function(e){
e.preventDefault();
jQuery('.um-message-send:visible').addClass('disabled');
var message_to = jQuery('.um-message-body:visible').attr('data-message_to');
var content = jQuery('.um-message-textarea textarea:visible').val();
jQuery.ajax({
url: um_scripts.ajaxurl,
type: 'post',
dataType: 'json',
data: { action: 'um_messaging_send', message_to: message_to, content: content },
success: function(data){
jQuery('.um-message-textarea textarea:visible').val('');
jQuery('.um-message-body:visible').find('.um-message-ajax:visible').html( data.messages );
if ( data.limit_hit ) {
jQuery('.um-message-footer:visible').html( jQuery('.um-message-footer:visible').attr('data-limit_hit') );
}
jQuery('.um-popup-autogrow:visible').mCustomScrollbar('update').mCustomScrollbar("scrollTo", "bottom",{ scrollInertia:0});
}
});
return false;
});
Html
<div class="um-message-textarea">
<?php echo $this->emoji(); ?>
<textarea name="um_message_text" id="um_message_text" data-maxchar="<?php echo $limit; ?>" placeholder="<?php _e('Type your message...','um-messaging'); ?>"></textarea>
</div>
<div class="um-message-buttons">
<span class="um-message-limit"><?php echo $limit; ?></span>
<i class="um-faicon-envelope-o"></i><?php _e('Send message','um-messaging'); ?>
</div>
The answer was simply to replace success with complete as such...
success: function(data) {
// [...]
=>
complete: function(data) {
// [...]

Edit button inside table row only works in consecutive order

I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>

How to define an element with a a sql row id usng JSON encoded data

I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});

pass javascript array to PHP script using ajax

I am passing an array from javascript to PHP using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<head>
<script>
var parms = [];
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function () {
parms.push($(this).text());
});
function loadXMLDoc(parms) {
$.ajax({
type: "POST",
url: "update.php",
data: {
value: $(parms).serializeArray()
},
success: function (data) {
alert(data);
}
});
}
$("button").on('click', function () {
loadXMLDoc(parms);
});
alert(parms);
</script>
</head>
On click of button, I am trying to call the PHP script to edit the display of my web page. However, the ajax call to the below PHP statement alerts only the "Am I printed" line.
<?php
$uid = $_POST['value'];
echo "Am I printed";
echo $uid;
// Do whatever you want with the $uid
?>
Why is the $uid value not returned to my javascript? Is there something am doing wrong?

Categories

Resources