jQuery autosave not working as it should - php

I have a couple of scripts i have written below that work great seperately, but together they don't work as they should. Let me post the code and then explain the issue:
Autosave function:
<script>
function autosave() {
$('form').each(function() {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
}
setInterval(autosave, 10 * 1000);
</script>
AJAX post and return script:
<script>
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
});
$(document).ready(function(){
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
</script>
Form:
<form method="post" action="add_room.php">
<label for="itemName[]">Item</label>
<input type="text" name="itemName[]">
<label for="itemPhoto[]">Item</label>
<input type="text" name="itemPhoto[]">
<input type="hidden" name="itemId[]" value="">
<input type="hidden" name="itemParent[]" value="<?=$_GET['room']?>">
<div class="saveIcon" style="display: none; color: green;">SAVED!</div>
<div class="save">Save Item</div>
</form>
PHP:
<?PHP
require_once('dbConfig.php');
$item = $_POST['itemName'];
$photo = $_POST['itemPhoto'];
$id = $_POST['itemId'];
$parentId = $_POST['itemParent'];
foreach($item as $key => $val) {
if(!$id[$key]) {
if ($stmt = $db->prepare("INSERT test (test_title, test_desc, test_parent) VALUES (?, ?, ?)"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $parentId[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Insert SQL statement.";
}
}
else
{
if ($stmt = $db->prepare("UPDATE test SET test_title = ?, test_desc = ? WHERE test_id = ?"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $id[$key]);
$stmt->execute();
$stmt->close();
echo $id[$key];
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Update SQL statement.";
}
}
}
?>
Now, what happens with the second script is, when used on its own without the autosave, when you fill out the form and click save it takes that forms data and saves it to the necessary rows in a database, and then returns the id of what was just saved and puts that data in a hidden field so that the php script can work out if an insert query is needed or an update query is needed(when the returned id is present). There is also a clickable div called addForm which then appends another form set below the one(s) present and again, when it's save button is clicked ONLY this form is saved/updated in the database. When i trigger the autosave like i have in my code, the autosave literally takes ALL the forms and saves them as new entries but doesn't return the id/update the hidden field to trigger the update sequence. Can you shed ANY light on this at all? It's really bugging me. Have tried explaining this as best i can, sorry it's so long. It's a bit of a complicated one! haha

I'd suggest a few changes to the organization of the code, which then leads to making it easier to identify the errors.
http://pastebin.com/0QTZzX6X
function postForm(form) {
var $this = $(form);
var string = $this.serialize();
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.find('.saveIcon');
$this.find('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
}
function autosave() {
$('form').each(function() {
postForm(this);
});
}
setInterval(autosave, 10 * 1000);
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
postForm($(this).closest('form').get(0));
});
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
Basically i took logic that was duplicated and placed it into a more generic function.

Related

How to add a member and task allocated if not found in dynamically populated dropdownlst

I have reviewed suggested solutions but did not find any matching my issue.
We have a SELECT list that is dynamically populated from the database.
Each time a staff wishes to create a task and allocate time to complete the task, s/he selects the member who would handle that task and then allocates time to complete the task. This works fine.
//JS
function populateMember() {
$.ajax({
type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/getMember.php?mode=edited&rowId=' + $.urlParam('id'), // the url where we want to POST
dataType: 'html', // what type of data do we expect back from the server
encode: true
})
.done(function (data) {
var returnedData = JSON.parse(data);
var newRows = (returnedData.length - 3);
if (returnedData.length > 3){
var x = 0;
for (x=0; x < newRows; x++){
$( "#newMember" ).trigger( "click" );
}
}
var i=0;
for (i in returnedData){
$('#member' + i).val(returnedData[i][0]);
$('#task_time_alocatted' + i).val(returnedData[i][1]);
}
})
.error(function () {});
}
//PHP
<?php
//Connect to server
///Connection info goes here
}
//These are parameters from the POST request
$mode = $_GET[ 'mode' ];
$rowId = (int) $_GET[ 'rowId' ];
$sql = "SELECT member, task_time_allocated FROM TaskAllocations WHERE parent_task_id = $rowId;";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
$theErrors = sqlsrv_errors();
array_push($messages, 0, $sql, $theErrors);
echo json_encode($messages);
die();
} else {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
array_push($messages, [$row['member'], $row['task_time_allocated']]);
}
echo json_encode($messages);
}
?>
However, if the member that a staff is trying to select from the SELECT list is not on that list, we would like two text boxes, one for the member and one for task to be allocated to that member.
How do we handle this?
We have created this on the HTML form:
//JS
<script type="text/javascript">
$(function () {
$("#btnstaff").click(function () {
if ($(this).val().toLowerCase() == "amend") {
$.each($('.dvstaff'), function(i, item){
$(this).show();
});
$(this).val("Cancel");
} else {
$.each($('.dvstaff'), function(i, item){
$(this).hide();
});
$(this).val("Amend");
}
});
});
</script>
//HTML
<input id="btnstaff" type="button" value="Amend" name="btnstaff" />
<tr>
<td></td>
<td><div class="dvstaff" style="display: none"><input id="amendmember" class="shortText" style="width:242px;" name="amendmember"></div></td>
<td>
<div class="dvstaff" style="display: none"><input id="amendtime" class="shortText" placeholder="0" name="amendtime"> %</div></td>
</tr>
You click Amend and it creates two blank textboxes, one for new member and the other for task_time_allocated.
We would prefer to handle this Amend bit on the JS that invokes the getMember method since the HTML is generated from the JS.
Is this possible?

jquery Ajax not saving to mysql

I have a php file that has jquery ajax on it to submit a form and save its contents into a mysql without doing a page refresh.
My issue is if I load the file that the ajax call does the contents are saved into the database however if I try to use the form nothing gets saved to the database even though I get a success message.
Here is my code
The HTML file
<div id='backinstock-form'>
<form>
<input id='instockemailadr'>
<input id='instockpid' value='5' type='hidden'>
<input name='submit' class='submitbackinstock' type='button' value='Submit'>
</form>
<span class='error' style='display:none'> Please Enter A Valid Email</span>
<span class='success' style='display:none'> Email Submitted Success</span>
</div>
require(['jquery'], function($)
{
$(".submitbackinstock").click(function()
{
var instockemailadr = $("#instockemailadr").val();
var instockpid = $("#instockpid").val();
var dataString = 'usereaddr='+ instockemailadr + '&sku=' + instockpid;
if(instockemailadr =='' || instockpid =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//console.log(dataString);
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
$.ajax({
type: "POST",
url: "<?php echo $block->getBaseUrl(); ?>/pub/media/theme_customization/backin-stock-email-code/backinstock_process_email.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
The PHP File
<?php
// MySQL portion
$conn = mysqli_connect("localhost", "root", "root");
mysqli_select_db($conn,"multisitedb");
$usereaddr = mysqli_real_escape_string($conn, $_POST['usereaddr']);
$stockproductid = mysqli_real_escape_string($conn, $_POST['sku']);
$created_on = date('Y-m-d h:i:s');
$result = mysqli_query($conn, "INSERT INTO multisitedb.backinstock_email_addresses(email_addr, product_sku, created_on)
VALUES ('$usereaddr','$stockproductid','$created_on')");
if($result) {
echo $result; // or whatever you want
} else {
echo "Something went wrong.";
}
?>
First, you didn't specify a Database in your php script. The format is mysqli_connect(host, username, password, database);
Secondly, your ajax code seems wrong. You're making a post request. The data should be an instance of formData(). You can modify this way:
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
//...
data: dataString,
success: function(){
Also, your PHP script is not doing security checks. You need to validate user inputs as well as use prepared statements to prevent against SQL injection attack.

Display the JSON data returned from PHP in the Datatable format

I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>

ajax and php to enter multiple forms input to database

I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.
sample ajax:
function MyFunction(){
var i = 1;
var x = $('#num_to_enter').val();
while (i <= x){
var name = $('#fname[i]').val();
var lname = $('#lname[i]').val();
var email = $('#Email[i]').val();
i++;
}
$('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
$.ajax({url : 'process.php',
type:"POST",
while (i <= x){
data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
i++;
}
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
}
A sample of form :
<?php
echo "<form method='post'>";
$i=1;
while($i <= $num_to_enter){
$form_output .= "First Name:
<input id='fname' type='text' name='fname[$i]'><br />
Last Name:
<input id='lname' type='text' name='lname[$i]'><br />
Email:
<input id='Email' type='text' name='Email[$i]'><br />
$i++;
}
echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";
?>
Then DB MySQL Sample
<?php
while ($i <= $x){
$x = $_POST['num_to_enter'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['email[$i]'];
$sql = "INSERT INTO `mytable`
(`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";
$i++;
}
?>
Here is a simple demo of AJAX:
HTML
<form method="POST" action="process.php" id="my_form">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[custom1]">
<input type="text" name="firstname[custom2]">
<br><br>
<input type="submit" value="Submit">
</form>
jQuery
// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){
// do not allow native browser submit process to proceed
e.preventDefault();
// AJAX yay!
$.ajax({
url: $(this).attr('action') // <- find process.php from action attribute
,async: true // <- don't hold things up
,cache: false // <- don't let cache issues haunt you
,type: $(this).attr('method') // <- find POST from method attribute
,data: $(this).serialize() // <- create the object to be POSTed to process.php
,dataType: 'json' // <- we expect JSON from the PHP file
,success: function(data){
// Server responded with a 200 code
// data is a JSON object so treat it as such
// un-comment below for debuggin goodness
// console.log(data);
if(data.success == 'yes'){
alert('yay!');
}
else{
alert('insert failed!');
}
}
,error: function(){
// There was an error such as the server returning a 404 or 500
// or maybe the URL is not reachable
}
,complete: function(){
// Always perform this action after success() and error()
// have been called
}
});
});
PHP process.php
<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */
// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';
// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];
/**************************************************/
// some logic for sql insert, you can do this part
if($sql_logic == 'success'){
// give JSON back to AJAX call
echo json_encode(array('success'=>'yes'));
}
else{
// give JSON back to AJAX call
echo json_encode(array('success'=>'no'));
}
?>
var postdata={};
postdata['num']=x;
while (i <= x){
postdata['fname'+i]= name[i];
postdata['lname'+i]= lname[i];
postdata['email'+i]= email[i];
i++;
}
$.ajax({url : 'process.php',
type:"POST",
data:postdata,
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
PHP
$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
echo $_POST['fname'.$i];
echo $_POST['lname'.$i];
echo $_POST['email'.$i];
}

AJAX Password Change without Refresh

I'm trying to implement password change functionality into my website. I've got all the password changing script, validation, etc done. But now I need to prevent the page from going to the script page or refreshing. When the user clicks the submit button, I want nothing to change except a message displaying successfully changed or error. So here's my html:
<form id="change_Pass" action="" method="post">
Current Password<input type="password" id="change_password" name="change_password"><br>
New Password<input type="password" id="new_password" name="new_password"><br>
Verify Password<input type="password" id="verify_password" name="verify_password"><br>
<input type="submit" value="Submit" id="change_pass_submit">
</form>
And my jquery:
$('#change_pass_submit').click(function(){
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "/Private/change_password.php", // the file to call
success: function() { // on success..
//$('#success_div).html(response); // update the DIV
alert("good");
},
error: function() { // on error..
//$('#error_div).html(e); // update the DIV
alert("bad");
}
});
return false; //so it doesn't refresh when submitting the page
});
And my php:
<?php
session_start();
require_once '../classes/Bcrypt.php';
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$usr = $_SESSION["username"];
$old_pwd = $_POST["change_password"];
$new_pwd = $_POST["new_password"];
$new_pwd = Bcrypt::hash($new_pwd);
try {
$link = new PDO('mysql:host=*;dbname=*;charset=UTF-8','*','*');
$query = "SELECT *
FROM Conference
WHERE Username = :un";
$stmt = $link->prepare($query);
$stmt->bindParam(':un', $usr);
$stmt->execute();
$row = $stmt->fetchAll();
$hash = $row[0]["Password"];
$is_correct = Bcrypt::check($old_pwd, $hash);
if($is_correct) {
$query = "UPDATE Conference
SET `Password`=:new_pwd
WHERE Username = :usr";
$stmt = $link->prepare($query);
$stmt->bindParam(':new_pwd', $new_pwd);
$stmt->bindParam(':usr', $usr);
$stmt->execute();
return true;
} else return false;
} catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
But for some reason, when I hit the submit button, the page STILL goes to change_password.php. I have no idea why, i've looked at so many tutorials and my code matches theirs but for some reason mine won't stay on the same page. Where did I go wrong?
Instead of using $('#change_pass_submit').click(function(), use $('#change_Pass').submit(function().
.click will only work if the submit button is actually clicked where .submit will work even if the user presses enter.
This should fix your error but it is untested.
Bind your handler to the form's submit event:
$(document).on('click', '#change_Pass', function() {
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "/Private/change_password.php", // the file to call
success: function() { // on success..
//$('#success_div).html(response); // update the DIV
alert("good");
},
error: function() { // on error..
//$('#error_div).html(e); // update the DIV
alert("bad");
}
});
return false; //so it doesn't refresh when submitting the page
});
Try putting preventDefault(); in the last line of the function performed by .submit
$(document).ready(function(){
$( "#cambiar_pass_form" ).submit(function() {
$.ajax({
...
...
});
event.preventDefault();
});
});

Categories