How to add checkbox info to MySQL database using Ajax? - javascript

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.

Related

Send JS variable to PHP on another page without form

I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.
The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});

Data Insertion repeated on Save through AJAX

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.

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

Saving Text After Text-Swap

I'm creating a shipping status report and what I am trying to accomplish, I can't seem to figure out. In my report table I have a button and it shows "Mark as Shipped". If I click on that button it changes to say "Shipped". This is going to serve as just as an easy reporting method for me.
I am doing the text swap like this...
<script>
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
</script>
I had to add
e.preventDefault()
into the code because the page would reload after I clicked on the button.
One of the issues I am having with this is it isn't allowing me to go back to the original. I tried moving e.preventDefault() to the bottom of that code, but it didn't help.
Now the main part of my question is I want this to be able to save after I have selected it. I'm not sure if I will have to scratch what I'm doing, house this in a db, or if I can do it with my existing code... I definitely need it to save once selected though.
Then one last thing. I'm not sure how to do this with just pressing a button. I know how to do it with php, but I am very new to JS.
When I select "Mark as Shipped" I want a time stamp for d - t -y and time to be added in my td row. Is this possible to do with JS?
I'm looking for ways I can accomplish doing all of this. I have looked all over and can't seem to find anything that is similar to what I want.
Any ideas?
UPDATE
I added it all in to the same script as instructed. Now my button doesn't even change at all and nothing is sending to the db.
<script>
$.ajax({
url: "shippingStatusSend.php",
data: {action: "Shipped", order: order_id},
type: "POST",
dataType: "text"
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
</script>
PHP page called shippingStatusSend.php
I just started learning how to do prepared statements so this may be an issue too.
<?php
//connection to db
$con = mysqli_connect("localhost", "root", "", "bfb");
//Check for errors
if (mysqli_connect_errno()) {
printf ("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$order_id = trim($_POST['order_id'] );
$status = trim($_POST['action'] );
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO shippingStatus (order_id, status, date_Shipped) VALUES (?, ?, NOW())")) {
/* bind parameters for markers */
$stmt->bind_param('is', $order_id, $status);
/* execute query */
$stmt->execute();
/* close statement */
mysqli_stmt_close($stmt);
}
?>
In order to make JavaScript changes static, you'll need to use some server side, such as using PHP to store the change in a database.
For that, you'll need to use AJAX, which is easy with jQuery:
$.ajax({
url: "example.php",
data: {action: "Shipped", order: orderID},
type: "POST",
dataType: "text"
}).done(function(r){
//Do your code for changing the button here.
});
Change example.php to your PHP script that will make the change server side, and make sure you pass the orderID of the order you're changing. In the PHP file, you can access $_POST['action'] and $_POST['order'] to get the information from the JavaScript.
Then in the done part (which is called after the AJAX has finished), you can update the button. You can also do some error checking in there to be on the safe side. the r variable can be used for any response data from the PHP file (for example, if you echo "Done" in your PHP, r will equal "Done").
Edit
As per your updated question/code, your problem is that you are creating an AJAX call when the page loads, and not on button click. Change it to:
$("button").on("click", function(e) {
e.preventDefault();
var el = $(this);
$.ajax({
url: "shippingStatusSend.php",
data: {action: "Shipped", order: order_id},
type: "POST",
dataType: "text"
}).fail(function(e,t,m){
console.log(e,t,m);
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
Update
To get order_id you'll need to store it in the DOM somewhere. As per your comments you have it in:
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
So something like:
var order_id = $('.tdproduct').text();
will get the id, but only if you only have one element with that class. Otherwise you'll have to store in some other unique element to grab.
Saving On Reload
Once you have the value saved in the database, you need to have PHP render it on page load. Rather than having your static html saying Mark as Shipped, use a PHP echo or print to output the information from the database.

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