Troubleshooting with ajax and jquery - javascript

I have a table loaded from a database and I want to be able to click and edit the row and have it update the database.
Currently it is not working and I have no idea why. What ways are there to troubleshoot this? How can I tell if the ajax is running? I am new to jquery and ajax, so I am not familiar with any debugging techniques that may be useful.
Here is the relevant code I have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#fact_"+ID).hide();
$("#source_"+ID).hide();
$("#upvotes_"+ID).hide();
$("#downvotes_"+ID).hide();
$("#fact_input_"+ID).show();
$("#source_input_"+ID).show();
$("#upvotes_input_"+ID).show();
$("#downvotes_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var fact=$("#fact_input_"+ID).val();
var source=$("#source_input_"+ID).val();
var upvotes=$("#upvotes_input_"+ID).val();
var downvotes=$("#downvotes_input_"+ID).val();
var dataString = 'id='+ ID +'&fact='+fact+'&source='+source+'&upvotes='+upvotes+'&downvotes='+downvotes;
//var dataString = "'{'id':'"+ ID +"','fact':'"+fact+"','source':'"+source+"','upvotes':'"+upvotes+"','downvotes':'"+downvotes+"'}";
if(fact.length>0 && upvotes.length>0 && downvotes.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
alert("Success");
$("#fact_"+ID).html(fact);
$("#source_"+ID).html(source);
$("#upvotes_"+ID).html(upvotes);
$("#downvotes_"+ID).html(downvotes);
}
});
}
else
{alert('Enter something.');}
});
// Edit input box click action
$(".editbox123").mouseup(function()
{return false});
// Outside click action
$(document).mouseup(function(){
$(".editbox123").hide();
$(".text").show();
});
});
</script>
And table_edit_ajax.php is:
<?php
$con=mysqli_connect("XXXXXX","XXXXXX","XXXXXX","XXXXXX");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
if($_POST['id'])
{
$id=mysqli_real_escape_string($_POST['id']);
$fact=mysqli_real_escape_string($_POST['fact']);
$source=mysqli_real_escape_string($_POST['source']);
$upvotes=mysqli_real_escape_string($_POST['upvotes']);
$downvotes=mysqli_real_escape_string($_POST['downvotes']);
$sql="UPDATE `FACTS` SET `fact_fact`='" .$fact . "', `fact_source`='" . $source . "', `fact_upvote_ctr`='" . $upvotes . "', `fact_downvote_ctr`='" . $downvotes . "' WHERE `fact_id`='" . $id . "';";
mysqli_query($con, $sql);
}
?>

Related

removing users from page on button click using ajax technology

I want to remove the whole element on button click.
Removal must be done through Ajax technology, that is, without reloading the page.
After deleting a user, the entry with him should disappear from the list of all users.
Here is the structure of my code:
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].');">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$(this).closest(".infoAllUsers").remove();
}
});
}
</script>
There are no errors in js and php, there is nothing in the console, deletion from the database occurs correctly.
I am new to jQuery so I have tried some things like:
$(this).parent('div').remove();
$(this).closest('div').remove();
$(this).parent('.infoAllUsers').remove();
Take a different/cleaner approach
Set the id as a data attribute and assign a class, then add the click event to that.
<button class="delete" data-id="'.$user['id'].'">Delete</button>
$('.infoAllUsers .delete').click(function(elm) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {
'id': $(elm).data('id')
},
success: function() {
$(elm).parent().remove();
}
});
})
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].', this);">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id, this2) {
var $t = $(this2);
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$t.closest('.infoAllUsers').remove();
}
});
}
</script>
The code seems correct, the only thing that occurs to me is that your php backend is not returning an Http code that is in the 2XX range and that is why it does not enter the success function of your ajax request, have you tried to make a console.log() inside the function that deletes the <div> to see if the JS reaches that point?
Jquery.ajax() function documentation

Sent value and show output when select tag change

I new in term of using jQuery.
I practice using native php ajax, but for this time I need to learn jQuery for the current technology and demand.
I sent "types" value method POST to other page (ajaxInfo.php) when the tag change.
After the select tag change, it should show the result at <div id="showList"> that come from database (MySQL). But nothing happen.
Below are the source code.
Body
<select id="form-types" class="col-xs-10 col-sm-5" name="types">
<option value="">PLEASE CHOSE</option>
<option value="STATE">STATE</option>
<option value="FACULTY">FACULTY</option>
<option value="PROGRAME">PROGRAME</option>
</select>
<div id="showList"></div>
jQuery AJAX
<script type = "text/javascript" >
$(document).ready(function () {
$("select#form-types").change(function () {
var types = $("select#form-types").val();
if (types != null) {
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function (response) {
$("#showList").html(response);
}
}
});
});
});
</script>
Post Page (ajaxInfo.php)
<?php
if (isset($_POST["types"]) === TRUE){
$types = $_POST["types"];
}
else{
$types = null;
}
include '../dbco.php';
$query = $dbc -> query ("SELECT child FROM infobase WHERE parent='$types'");
if ($query -> num_rows > 0){
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc()){
echo "$count" . $result['child'] . "<br />";
count++;
}
}else{
echo "NO " . $types . " REGISTERED";
}
?>
Thank You.
You are using id (form-types) for your select input field. but your are tying to targeting another id (form-jenis).
use same named id for select input field and in your jquery selector.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(e){
e.preventDefault();
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'show.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
You have a missing bracket
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
}); // add this
</script>
I found out that my ajax jQuery function do not have close pair, so i decide to add it and it work.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}); // Add This
}
});
});
</script>
After the code running good, i also found out the error at ajaxInfo.php, the count inside the loop missing $ symbol
if ($query -> num_rows > 0)
{
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc())
{
echo "$count" . $result['child'] . "<br />";
$count++; //HERE
}
}
Thanks for the people that help.

How to only return the value itself from php to javascript?

I've looked around on the internet for answers, but I couldn't find any specific to my situation. As mentioned in the title, i'm trying to retrieve and then display a certain value from mysql database.
Disregarding the security measures which I will add later on, I've managed to retrieve the data, but when I send it back to the javascript and alert it, this value is returned: {"acc_points":"5"}. I would like it it to be just "5", is there any way that I can do this? Thanks!
Here are the codes:
js file
$(document).ready(function() {
$("#viewpoints").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/apppoints.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(JSON.stringify(response));
}
})
}
});
});
php file
<?php
header('Content-Type: application/json');
require 'dbcon.php';
session_start();
$acc_id = $_SESSION["acc_id"];
$sql = "SELECT acc_points FROM points WHERE acc_id = '$acc_id'";
$result = mysqli_query($con, $sql);
$acc_points = mysqli_fetch_assoc($result);
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "Failed. Please try again.";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>

Ajax not submitting $_Post

I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);

PHP auto-fill selectbox through URL

I have a question I can't figure out.
<?php
$killtheboy = 0;
if($killtheboy == 1){
echo "<input type=\"text\" name=\"dwanummer\" id=\"dwanummer\">";
}else{
echo "<div id=\"dropdowndwa\">
<select name=\"dwanummer\" id=\"dwanummer\" class=\"dwanummer\">
<option selected=\"selected\">Kies uit lijst</option>";
include("config/instellingen.php");
$query = "SELECT DISTINCT `Klantvraag`,`Wensweek` FROM `DWA` WHERE `Status DWA` = 'DBAA' OR `Status DWA` = 'DBAP' OR `Status DWA` = 'DIUI' ORDER BY wensweek - '$wensweekber' ASC";
if ($result = mysqli_query($connect, $query)) {
while ($get = mysqli_fetch_assoc($result)) {
$week = date('W', strtotime("this week"));
$jaar = date('Y', strtotime("this week"));
$wens = ''. $jaar . ''. $week. '';
$wensweek = $get['Wensweek'];
$wensweekber = $wensweek - $wens;
echo '<div class="selectBlock"><option value="' . $get['Klantvraag'] . '" name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option></div>';
}
}
echo "</select></div><br />";
}
?>
The above code (PHP) fetches a list of numbers on pageload and I have to select one in order to fetch that information through JS.
<script type="text/javascript">
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax
({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
}
});
});
});
</script>
Basically I have a search system and u can find all 'cases' there and if you see one you want then you click it it goes to the above page with code and it auto selects that ID instead of still having to select it. (like additem.php?id=125533 or something)
Can someone please explain me how I can solve this.
Can you try this, You need to use selected attribute in select element
$Selected ='';
if(isset($_GET['id']) && ($get['Klantvraag'] == $_GET['id'])){
$Selected =" selected='selected' ";
}
echo '<option value="' . $get['Klantvraag'] . '" '.$Selected.' name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option>';
Javascript:
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
Populate();
});
Populate();
});
function Populate(){
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
removeAllNameSelectBoxes();
var selected = $("#dropdowndwa option:selected").map(function (i, el) {
return el.value;
}).get();
getNamesFromSelectIds(selected);
}
});
}

Categories

Resources