Data Insertion repeated on Save through AJAX - javascript

I built my first ever app using PHP Codeigniter 4 and deployed it to producation yesterday, where users save the data of their items sold. They are saved using AJAX through JQuery where after every save function, page is reloaded. Here is my code on frontend:
$('form[name="transfer_record"]').submit(function (event) {
// This will prevent form being submitted.
event.preventDefault();
// Call your function
var save_date = $("#date").val();
var save_phone_number = $("#phone_number").val();
...
var save_team_lead = $("#team_lead").val();
var save_qa_comments = $("#qa_comments").val();
$.ajax({
url: "<?= base_url(). "/save_transfer_record";?>",
type: "POST",
data: {
save_date:save_date,
save_phone_number:save_phone_number,
...
save_team_lead:save_team_lead,
},
success: function (data) {
alert('Transfer Data Saved Successfully');
location.reload(0)
},
});
});
Here is my code on controller in PHP:
public function save_transfer_record()
{
date_default_timezone_set('America/New_York');
$usa_date = date("Y-m-d H:i:s");
$TransfersIBModel = new TransfersIBModel();
if(isset($_POST)){
$saveTransferForm = [
'date' => $usa_date,
'phone_number' => $this->request->getPost('save_phone_number'),
...
'team_lead' => $this->request->getPost('save_team_lead'),
];
$TransfersIBModel->save($saveTransferForm);
}
}
My PROBLEM IS: Yesterday was first day in production, and there were three instances where there were duplicate entries.
One of them, orange one, have different timestamp which maybe makes me think User entered it twice. But rest two were at same time. So, what could be the issue and how can I mitigate it.
How can I do ensure no duplication without making 'Phone Number' entry unique?
If I make 'Phone Number' unique, how can I make it work?
Please suggest me. I can try disabling button on Ajax click, but I don't think it would work because it feels like my AJAX request ran twice somehow because once it clicks, page should reload before second AJAX request, shouldn't it.Lastly, what is the best practice now, should I hard delete duplicate entries from Table or do not show duplicate values.

Related

Can I execute a Doctrine function that delete in database on leaving the page?

I have a project using Symfony, Doctrine and Javascript.
Briefly it's about a planning app and i'm working on the modification page.
So we have the html with some Twig, the controller in php and the javascript file.
The general idea is when a user goes on modification page, it writes it in the database so that 2 users can't modify the same day simultaneously. The thing is I want to delete the row in the database when the user is leaving the page or even closing his navigator suddenly, to let other users modify after him.
I have this in php :
public function modificationDeleteTest(){
$modificationRepository = new ModificationRepository($this->getDoctrine());
$modifications = $modificationRepository->findAll();
// I'm using GET and POST just to be sure to get the date somehow
if (isset($_GET['date'])) {
$dateModified = $_GET["date"];
}
if (isset($_POST['date'])) {
$dateModified = $_GET["date"];
}
$i = 0;
foreach ($modifications as $modification) {
$modifArray[] = array(
'dateModified' => ($modification->getDatemodified()->format('Y-m-d'))
);
if($modifArray[$i]['dateModified']==$dateModified){
$this->modificationDelete($modificationRepository, $modification);
}
$i++;
}
}
And I tried using the window events onunload and onbeforeunload in JS with some Ajax, and maybe 20 different ways :
window.onbeforeunload = function() {
if(isset($_GET("date"))){
dateModified = $_GET("date");
}
if (isset($_GET("id"))) {
idUser = $_GET("id");
}
$.ajax({
url: "/ModificationDeleteTest",
type: 'POST',
data: {date:dateModified, id:idUser},
async:false, // so browser waits till xhr completed
success:function() {
alert("bye!");
}
});
};
I'm using routes, I tried with these one :
ModificationDeleteTest:
path: /ModificationPlanning
controller: App\Controller\ModificationPlanningController::modificationDeleteTest
methods: [POST]
Unfortunately it seems that the php functions are never called
I also tried to call them outside of the class but because of Doctrine and $this, it doesn't work either.
It's been a full day that I'm just cycling between errors and functions not called, so I'm asking you for some advice
PS : Note that I'm beginning with Doctrine, JS and especially Ajax, that's why I have a hard time to use them combined

issue using $.ajax with php effectively

I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function

How to add checkbox info to MySQL database using Ajax?

I have a simple list populated via MySql via Ajax / Json. The list is just a title and description and every entry has a checkbox. I need the checkbox, once clicked, to push to database that it is clicked. How would you go about doing that?
[btw...
right now since I have a setTimeInterval on my SQL data to deliver the list on the fly it automatically resets my checkbox. I'm assuming that if I record that my checkbox has been set via boolean in the SQL that there could be a way to keep it checked...]
I'm new at this and I'm just playing around and trying to learn so this information is entirely theoretical.
You can use the on() function to listen to checkbox clicks.
$(function() {
$(document.body).on('click', 'input.mycheckbox', function() {
var checkbox = $(this);
var checked = checkbox.attr('checked');
$.ajax('service.url', {
type: 'post',
data: {action: 'checkbox-select', id: checkbox.attr('id'), checked: checked},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
// Revert
checkbox.attr('checked', !checked);
}
});
}
});
Feel free to ask if you need any clarification or if this doesn't fit your situation.
EDIT:
The data parameter of the AJAX function is an object that will be posted to your PHP page. When your PHP code is running, $_POST will be an array containing the values we passed. So, $_POST['action'] will be 'checkbox-select', $_POST['id'] will get the ID, and $_POST['checked'] will be true or false depending on whether the checkbox was selected or deselected. Your method of getting the ID in the Javascript will probably change; I just put checkbox.attr('id') to give you an idea.
When learning PHP it can be helpful to dump the responses from the server on the client-side. Example PHP code:
if($_POST['action'] == 'checkbox-select']) {
$checkbox = $_POST['id'];
$checked = $_POST['checked'];
// Your MySQL code here
echo 'Updated';
}
echo 'Code ran';
I edited the JS to show the result from the server.

Execute ajax only one time

I want only execute my ajax post 1 time, i try to avoid to the user refresh the page and execute so much times the ajax post,
I thought in create a cookies, but i don't know, and i'm no sure, somebody know how?
This is my jquery.
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) { alert(JSON.stringify(r)) },
dataType: 'JSON',
data: { data: data, }
})
});
/I need run this AJAX only one time because is a checkout page to send the order, and if i refresh the page, send every time the same order, and this i don't want/
Thanks a lot!
Things like these can not be safely controlled on the client's browser. Any user with minimal knowledge in JavaScript will be able to open up the developers tools for their browser and manipulate the code or any values you might have stored (such as deleting the cookie you have set).
This limitation should be implemented on the server.
It really depends on the scope of your application. You might be able to limit the requests per IP address, but that might prevent multiple people from the same office for example loading the page at the same time.
Using user authentication and persistent server storage you'll be able to limit the effect of the request, but you probably won't be able to prevent the actual request from being sent as anyone can make that request even from outside the browser. You could store the user_id of the user that initiated the request and only allow the resulting action to occur if a certain time has passed since the last request.
A better solution to avoid double submits, is to use a POST query for the submit request and let the server respond with a redirect to a normal (harmless) receipt/thankyou page.
Then if the user refreshes the receipt page they will simply repeat the GET request to the receipt page and not the post.
You should still add some checks server side to avoid multiple POST requests somehow (using sessions, timestamps or something), in case a malicious user deliberately tries to resubmit.
This will only work on IE8 and above, but you can use localStorage:
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
if(localStorage['submitted'] === undefined){
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) {
localStorage['submitted'] = true;
alert(JSON.stringify(r));
},
dataType: 'JSON',
data: { data: data, }
})
}
});
This way the first time it will run the AJAX because you haven't set the localStorage variable, but upon success you do and it will not resubmit on page refresh.
If you wanted to have the ability to send again upon a future visit, just use sessionStorage instead of localStorage. Same syntax and everything.

Auto refresh with ajax/jQuery after initial form submit then change page title

I have a form set up that, when submitted, uses an ajax call to retrieve data via a PHP file that in turn scrapes data from a given URL based on the input field value.
Everything is working perfectly, but what I'd like to do now is implement a couple of additional features.
1) After the initial form submission, I'd like it to auto-update the query at set intervals (Chosen by the end user). I'd like to append the new results above the old results if possible.
2) When new results are returned, I'd like a notification in the title of the page to inform the user (Think Facebook and their notification alert).
Current jQuery/Ajax code:
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'jobSearch.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.val('Searching....'); // change submit button text
},
success: function(data) {
$('#container').css('height','auto');
alert.html(data).fadeIn(); // fade in response data
submit.val('Search!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
I'm not too sure how I'd go about this, could anyone give me an insight? I'm not after somebody to complete it for me, just give me a bit of guidance on what methodology I should use.
EDIT - jobSearch.php
<?php
error_reporting(E_ALL);
include_once("simple_html_dom.php");
$sq = $_POST['sq'];
$sq = str_replace(' ','-',$sq);
if(!empty($sq)){
//use curl to get html content
$url = 'http://www.peopleperhour.com/freelance-'.$sq.'-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}else{
$url = 'http://www.peopleperhour.com/freelance-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}
$html = file_get_html($url);
$jobs = $html->find('div.job-list header aside',0);
echo $jobs . "<br/>";
foreach ($html->find('div.item-list div.item') as $div) {
echo $div . '<br />';
};
?>
Question 1:
You can wrap your current ajax code in a setInterval() which will allow you to continue to poll the jobSearch.php results. Something like:
function refreshPosts(interval) {
return setInterval(pollData, interval);
}
function pollData() {
/* Place current AJAX code here */
}
var timer = refreshPosts(3000);
This has the added benefit of being able to call timer.clearInterval() to stop auto-updating.
Appending the data instead of replacing the data is trickier. The best way, honestly, requires rewriting your screen scraper to return JSON objects rather than pure HTML. If you were to return an object like:
{
"posts": [
// Filled with strings of HTML
]
}
You now have an array that can be sorted, filtered, and indexed. This gives you the power to compare one post to another to see if it is old or fresh.
Question 2:
If you rewrote like I suggested above, than this is as easy as keeping count of the number of fresh posts and rewriting the title HTML
$('title').html(postCount + ' new job postings!');
Hope that helps!
If i understand correctly. . .
For updating, u can try to do something like this:
var refresh_rate = 2500
function refresh_data() {
// - - - do some things here - - -
setTimeout (refresh_data(),refresh_rate); // mb not really correct
}
You can read more about it here
Hope, i helped you

Categories

Resources