Using ajax with a while statement and DB - php

I have a question about using ajax.I want to delete something of my screen (to be clear, some articles) I'm generating content (the articles) on the screen with this code:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
This all is working very well without ajax. But I want to make this(the delete with the button) happen without a page refresh.
When i for example check the content of $test['id'], i receive one number. My problem with the code below is that when i want to put the title into variabel (var titel) for ajax, it loads all the titels from my page.
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
EDIT
I hope i explained my question in a better way now

Your problem is here
var titel = $(".titelopmaak").text();
You get all the values ​​of the elements with class .titelopmaak but you only need one.
This is the correct one, we go up the tree and then find the item.
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
But, control elements by the title its very bad practice, use id instead of.
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>

You can try like this....
You have to specify individual id for each html elements
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
javascript function
Refer the h1 and div by their ids.
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
deleteArticle.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";

Related

Post data with url variable using ajax

I have a Follow/unfollow button which is working perfectly with PHP. How do i write ajax to follow/unfollow without page refresh and update the button value(follow or unfollow) accordingly?
PHP:
//FOLLOW
if(isset($_POST['follow'])){
$sql = mysqli_query($conn, "INSERT INTO `follows`(`user_id`, `following_id`) VALUES ('$Sessionid','$getID')");
header("Location: /funaholic/profile?Profileid=$getID");
}
//UNFOLLOW
if(isset($_POST['unfollow'])){
$sql = mysqli_query($conn, "DELETE FROM `follows` WHERE user_id=$Sessionid AND following_id=$getID");
header("Location: /funaholic/profile?Profileid=$getID");
}
//CHECK IF ALREADY FOLLOWING
$getFollowing = mysqli_query($conn, "SELECT * FROM `follows` WHERE user_id='$Sessionid' AND following_id='$getID'");
$rowcount = mysqli_num_rows($getFollowing);
if($rowcount === 0){
if($Sessionid == $getID){
echo "<form action='update' id='followform' method='POST'>
<button class='follow' name='follow'>UDATE PROFILE</button>
</form>";
}else {
echo "<form action='profile?Profileid=".$getID."' id='followform' method='POST'>
<button class='follow' id='myBTN' name='follow'>FOLLOW</button>
</form>";
}
}else{
echo "<form action='profile?Profileid=".$getID."' method='POST'>
<button class='follow' id='myBTN' name='unfollow'>UNFOLLOW</button>
</form>";
}
AND THIS IS THE AJAX POST FUNCTION:
//FOLLOW UNFOLLOW AJAX
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: $(this).attr('action'),
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});

jQuery Ajax working for only first result in while loop

The loop works fine, it display what it supposed to do, but there is a mysql update button of which updates only the first row value displayed:
$(document).ready(function() {
$("#update").click(function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var recordId = $("#recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
async: true,
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
}
});
});
});
<?php
$conn = new mysqli('localhost', 'root', '123456', 'lc');
$sql = "SELECT * FROM lc where customer='souhail'";
$result = $conn->query($sql);
// while ( $row=mysqli_fetch_assoc($result)) {
while($row = $result->fetch_array()) {
echo 'LC ID :<input type="text" id="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" id="lname" value="'.$row['element_101'].'"><br>';
$recordId = $row['lc_id'];
echo '<input id="recordId" name="recordId" value="' . $recordId . '" >';
?>
<button type="button" style="background-color:<?php
if($row['element_101'] == '1'){
echo '#0000FFF';
}elseif ($row['element_101'] == '2'){
echo '#ffff00';
}elseif ($row['element_101'] == '3'){
echo '#00FF00';
}elseif ($row['element_101'] == '4'){
echo '#ffffff';
}
//echo $row['element_101'];
?>;color:#000000" id="update">Go Forward ></button>
<br><br>
<?php
} ?>
You must have unique IDs but instead wrap each set in a container and access relative tags:
$(".update").on("click", function() {
var $container = $(this).closest(".container");
var fname = $container.find(".fname").val();
var lname = $container.find(".lname").val();
var recordId = $container.find(".recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
Php
while($row = $result->fetch_array()) {
echo '<div class="container">
echo 'LC ID :<input type="text" class="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" class="lname" value="'.$row['element_101'].'"><br>'; $recordId = $row['lc_id'];
echo '<input class="recordId" name="recordId" value="' . $recordId . '">';
echo '<button type="button" clsss="update">Go Forward ></button>';
echo '/div>';
} ?>

Cant pass value of checkbox through ajax

I have table received from database:
<p id="result"></p>
<?php
//$id = $_SESSION['staff_id'];
$teamResult = getQuarter($leader_id);
$count1 = 0;
if (mysqli_num_rows($teamResult) > 0)
{
?>
<table id="confirm">
<tr>
<th>1st Quarter</th>
</tr>
<?php
while($row = mysqli_fetch_array($teamResult))
{
$staff_id = $row['staff_id'];
$username = $row['username'];
$date1 = $row['date1']; $fdate1 = $row['fdate1']; $q1 = $row['q1']; $cfm1 = $row['cfm1'];
?>
<tr>
<td>
<?php if($date1 != NULL){
echo "Ev.date: ".$date1."<br/> Fb.date: ".$fdate1.""
."<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>";
}else {echo "";}
?>
</td>
</tr>
<?php
$count1++;
}
} else {
echo "<h2>No Data to Display</h2>";
}
?>
</table>
This field is checkbox but I changed it to text to see its value:
<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>
Here is what I got in table:
Then I have AJAX function:
<script>
$(function () {
$(document).on('click', '.confirm', function(){
var stid = $("#stid").val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
});
</script>
And change.php:
$info = $_POST["stid"];
list($value1,$value2) = explode('|', $info);
echo $value1;
echo "<br/>";
echo $value2;
But the problem is I dont get correct value. For first and second row i get 1| 1000302. Even for second row where is should be 1| 1000305. What it the problem and how can I solve it?
IDs have to be unique. $("#stid") will always select the first element with that ID.
You can simply use $(this) to get the value of the element you clicked on.
$(document).on('click', '.confirm', function(){
var stid = $(this).val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});

Select results from live search ajax

I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});

ajax / php form and variable assignment

My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();

Categories