Insert/Edit records using php and javascript/ajax - javascript

I'm trying to make user interface to edit/insert records and i'm having some troubles with my code.
Lists the records :
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$html.="<tr>
<td style>{$row['name']}<input type='hidden' id='id' value='$row[a_id]'></td>
<td>{$row['season']}</td>
<td><a href='edit1/new' id='edit'></a></td>
<tr style='height: 5px;'></tr>
</tr>..
Now the js that i`m having trubles with:
<script type='text/javascript'>
$('#edit').on( 'click', function () {
var x = document.getElementById('id').value;
$.ajax({
type: 'post',
url: 'insert_edit.php',
data: {
id: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>
inside the insert_edit.php
if(isset($_POST['id'])){
$html = Edit();
}else{
$html = Add();
}
For some reason the on click function doesnt seem to work and it doesnt posts datainsert_edit.php`
Any help will be apriciated thank you.
NOTE: I'm not sure even if the posts works I'm using the Java Script the right way since my while loop prints it foreach ID and my guess is even it if it posts the data it will aways posts the value of the first record.

Try this- on click function replace with this-
$(document).on("click", "#edit", function(){
// ..
})

I managed to fix it. Here is how I did it:
I made an array $urlparts wich is my permalinks.
The button code goes like this
..a href='/account/competitions/edit1/update/$row[a_id]'>Edit..
And some php
if (isset($urlparts[4]) && is_numeric($urlparts[4])){
require_once ("insert_edit.php");
$html = Edit();
}
and inside the Edit();
just snach the id with
$id = $urlparts[4];
Thank you for the feeedback guys. Made me realize that I`m looking at the issue from the wrong angle:)

Related

Updating the database when double clicking js

I'm working on a project, and I have an issue. First, let me present a few things to you.
Database
An example on what the database structure looks like
ID | NAME
1 | Daniel
2 | David
HTML / PHP script
What the page itself looks like
<?php
$allUsers = mysqli_query($db,"SELECT * FROM users");
echo "<table class=\"table table-hover\" style=\"width: 100%;\">
<thead>
<tr>
<th scope=\"col\">#</th>
<th scope=\"col\">Username</th>
</tr>
</thead>
<tbody>";
while($row = mysqli_fetch_array($allUsers))
{
echo "<tr>";
echo "<th class=\"inner\">" . $row['id'] . "</th>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "
</tbody>
</table>";
?>
Javascript code
The Javascript code as found on this website as well
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value +
'"
/>');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}
Now the first thing I'd like to ask: This does not seem to work on my php page. On my html page on the other hand, where I tried this as well, it does work. What am I doing wrong?
When we've fixed that, how could I make sure that when my user double clicks a value, and changes it, that it updates in the database as well. So, for example, if a user of mine double clicks the value "David" and sets it to "Jeremy", the database will be update to Jeremy as well.
First of all, you should distinguish server script and client/ browser script. PHP is server script, when you run this file, it will be compiled to html file. Javascript/ jquery is browser script, it just runs on html file.
If you want when my user double clicks a value, and changes it, that it updates in the database as well. You should add more code in javascript/ query:
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
// add code here
// submit the value to server to update database
}
});
"This does not seem to work on my php page. On my html page on the
other hand, where I tried this as well, it does work"
"if a user of mine double clicks the value "David" and sets it to
"Jeremy", the database will be update to Jeremy as well."
Actually both question are related to the same problem. When changing your value with JS you're changing your HTML (front only) but by reloading you'll get the value you had at first... If you want to change your database you'll have to use AJAX as said Litvak. Could be something like this...
if (event.keyCode == 13) {
var name = $(".thVal").val();
var id = // you need to get the ID to be able to change your database at the right row
$.ajax({
type: 'POST',
data: {
id : id,
name : name
}
url: 'changeName.php',
dataType: 'html',
success:function(data, text) {
// If change in database worked, do this...
$(currentEle).html(name);
}
error : function(request, status, error) {
// There was a problem, couldn't change database, do this...
}
});
}
and your changeName.php would be where you run your sql script to change the database...
function changeName($id, $name) {
// make your checks here and your sql call
}
changeName($_POST['id'], $_POST['name']);

Trying to dynamically add, and name, div to page using javascript/php

I am new to php and javascript. I want to dynamically add a div to a page with php. In the end what I want is to be able to call a php function that adds a div. I want to call the function multiple times for a single page - so I want to add multiple divs via multiple function calls.
That doesn't seem to be difficult, but... I want each of the dynamically added divs to have the same class name, but a unique id and, for various reasons, I want the id to be based on the number of divs of that class already on the page (e.g. the first div added might have id = 0. the second id = 1, third id = 2 etc.).
I have looked a stackoverflow but haven't found any clues. I'd really appreciate any help.
I have tried the following, but it doesn't work (this is a very simplified version):
function getCount() {
?><script>
$(document).ready(function(){
var elems = $('body').find('.mydiv');
$.ajax({
type: 'POST',
url: '',
data: {count: elems.length},
cache: false,
success: function(response) {
console.log(response);
}
});
});
</script><?
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="../jquery-3.2.1.js"></script>
</head>
<body>';
$count = -1;
getCount();
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
if (!empty($key) && !empty($value)) {
echo 'key = '.$key.' value = '.$value;
if ($key == 'count') {
$count = $value;
}
}
}
}
if ($count > -1)
echo "<div class = 'mydiv' id = 'mydiv".$count."'></div>";
echo "</body></html>";
you dont want to mix js and php here, you can achieve this using php alone, here is the code sample
<?php
echo 'your headers and layout tags go here';
function addDiv($count){
echo "<div class = 'mydiv' id = 'mydiv".$count."'>current div id is ".$count."</div>";
}
$count=0;
addDiv($count++);
addDiv($count++);
addDiv($count++);
?>

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

How to make a button reusable after the first click with AJAX/JQUERY and PHP

I have built a follow/unfollow Twitter like system using PHP. With help of this forum I have been successful creating a dynamic button that allows you to “follow” or “unfollow” each user, using AJAX/JQUERY to run the PHP/MySQL code in the back and avoid refreshing the page when the action happens. The thing is that I am able to run this script on the background only once. Let’s say a user unfollows a member by mistake (my AJAX/JQUERY script won’t have any problem with that), but then wants to follow him again, this is where I am stuck. The page will have to be refresh to make this happen. I know this is happening due to the PHP dynamic data that I am using as you will see in my code.
In the PHP code am running an iteration that output all the members in the database. I am outputting here (for simplicity) just the member’s name and a follow/unfollow button to each one. The php variable $what_class is the result of a PHP function that looks into the database to determine if the user is following or not that member. $what_class will output the strings “follow” of “unfollow” so the class can be defined, and then be targeted by either of the two the Jquery scripts.
PHP CODE
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<button class="<?php echo $what_class; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" ><?php echo $what_class; ?></button>
<?php } ?>
Below is the JQUERY scripts, as mentioned before, the button class will be defined by PHP through $what_class. This is the problem when trying to re-use the button after the first time, class won´t change in PHP’s $what_class unless the page is refreshed. I tried to use $(this).removeClass('unfollow').addClass('follow') to change the class using Jquery and have the button to be re-usable but it isn’t working.
JQUERY SCRIPTS TO FOLLOW OF UNFOLLOW
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("button.follow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
});
});
</script>
Does anyone knows how I accomplish having a reusable button without reloading the page? I thank you in advance.
Previous Answer:
What I do for that kind of scenario is to have two buttons. One will be shown to the user, and the other one will be hidden.
<button class="follow" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Follow</button>
<button class="unfollow" style="display:none" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Unfollow</button>
Just tweak your php code what to show and what not.
When a button is click, hide this button and show the other one.
$(document).ready(function(){
$(".follow").on("click", function(){
$(".follow").hide(200);
$(".unfollow").show(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
$(".unfollow").on("click", function(){
$(".follow").show(200);
$(".unfollow").hide(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
});
Check this JSfiddle.
Update:
We can use toggleClass() of jQuery.
<button class="follow" data-member_id="12" user_id="12">Follow</button>
And the script:
$(document).ready(function(){
$(".follow, .unfollow").on("click", function(){
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$(".follow, .unfollow").toggleClass("follow unfollow");
$(this).text(function(i, text){
return text === "Follow" ? "Following" : "Follow";
});
});
});
Check this JSfiddle.
use <button class="followUnfollow <?php echo $what_class; ?>"
You need to write as less code as possible. Have a common class such as followUnfollow and then check if follow class exists within this element using hasClass function from jQuery.
Have a look at the code below.
<script type="text/javascript">
$(document).ready(function() {
$("button.followUnfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($(this).hasClass('follow')) { // FOLLOW
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
} else { // UNFOLLOW
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
}
});
});
</script>

A href load database items onClick

i'm developing a simple Content Management System that allow users to create categories and subcategories. This is the code.
$categories = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($categories)) {
$text = $row['text'];
$id = $row['id'];
echo "<li><a href='?category=$id'>$text</a></li>";
}
Now, all works fine as expected but i would like that when a user click on <li> items the system loads subcategories related to the selected category. In PHP i can't do this so i need to use JavaScript but i don't understand why. I wrote this code.
<script type="text/javascript">
function loadSubCategories() {
<?php
if(isset($_REQUEST['category'])) {
echo "Hello";
}
?>
}
</script>
and obviously
echo "<li><a href='?category=$id' onClick='javascript:loadSubCategories()'>$text</a></li>";
This not works because nothing appear when i click on a link. How can i solve?
Pass id attribute in function call like this:
echo "<li><a id="$id" onClick='javascript:loadSubCategories(this.id)'>$text</a></li>";
Then you can use jQuery/Ajax, try something like this:
$( document ).ready(function() {
function loadSubCategories(id){
$.ajax({
url : Class/Method-Name,
type : 'POST',
data : form_data,
success : function(msg){
// Action
}
}),
}
});

Categories

Resources