Scenario :
I have a datatable which has checkbox on each row. When i try to select all checkbox and remove all selected data from datatable, it was not refreshing but the code works perfectly fine on the backend. But when i try to select all except 1 row (any of the row) it works fine...
phpaction :
$query = "
SELECT id ID, code Code, name Name, description Description FROM tablename WHERE active = 1 ORDER BY id ASC";
$res = mysqli_query($dbcon, $query);
if (mysqli_num_rows($res) > 0) {
$data = array();
$tbl = '';
while ($row = mysqli_fetch_assoc($res)) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode('');
}
ajax:
$datatable.find('input[type="checkbox"]:checked').each(function() {
ID = $(this).attr("value").substr((($(this).attr("value")).length - 8) * -1);
remove(ID);
});
function remove(ID) {
requestAction = 'remove';
$.ajax({
url: 'phpaction.php',
method: 'post',
data: {
requestAction: requestAction,
ID: ID
},
success: function(data) {
list();
},
error: function(err) {
console.log(err);
}
});
}
Related
I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);
On smaller list of options the autocomplete drop down list does show on focus. but if the options are more than a specific number (50 to be exact) it no longer shows.
How to make it show no matter what the number of options in the list ?
$(document).ready(function() {
var sst;
//auto complete for artist
$('#artist').autocomplete({
source: 'artists.php',
minLength: 0,
select: function(a, b) {
sst = b.item.value;
}
}).focus(function() {
$(this).data("uiAutocomplete").search($(this).val());
});
//auto complete for title
$('#title').autocomplete({
source: function(request, response) {
$.ajax({
url: "titles.php",
dataType: "json",
data: {
q1: sst,
q2: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 0
}).on('focus', function(event) {
$(this).autocomplete("search", "");
});
});
the mysql query :
<?php
$db = mysql_connect('localhost','root','1313');
if(!$db){
die( "connection failed ");
}
$db_s = mysql_select_db("LYRICSFINDER",$db);
$data = array();
$searchTerm1 = trim(strip_tags($_GET["q1"]));
$searchTerm1 = addslashes($searchTerm1);
$searchTerm2 = trim(strip_tags($_GET["q2"]));
$searchTerm2 = addslashes($searchTerm2);
$query = "SELECT TITLE FROM DATA WHERE ARTIST LIKE '%".$searchTerm1."%' AND TITLE LIKE '%".$searchTerm2."%' ORDER BY TITLE ASC";
$result = mysql_query($query,$db);
$i=0;
while($row = mysql_fetch_assoc($result) ){
$data[] = $row['TITLE'];
$i++;
if($i>50)break;
}
mysql_close($db);
echo json_encode($data);
?>
I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}
When you load the page, I have two separate divs that get images randomly from a database then echo them as the background-image. I also get other data that comes along with the image.
I need to get data from a new PHP file and change the background-image of a div on click of a button (so that you don't need to refresh the page).
In getnew.php:
$select = mysqli_select_db($conn, "database");
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
In main.php:
$("#button").on("click",function(){
//
})
As I understand it you use jQuery's $.get to fetch the data from getnew.php but how exactly can I then use the data to change the background-image without having to refresh the page?
For example: style="background-image: url('<?php echo $img1link ?>')">
You'll need to use ajax, send data from the server and parse it at the client
Here is a code sample based on your snippet
In getnew.php:
$select = mysqli_select_db($conn, "database");
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$img1link = $row['link'];
$rating1 = $row['rating'];
$s1 = $row['sigma'];
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
$rating2 = $row2['rating'];
$s2 = $row2['sigma'];
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link));
In main.php:
$("#button").on("click",function(){
$.getJSON("getnew.php",function(data){
//use data.img2 and data.img1 and set the background
// for example: $('#someDiv').css('background-image',"url('"+data.img1+"')");
});
})
use JQuery CSS codes..as you are able to fetch the data from a page, pass the image path in jquery.css code, it will do as per your desire.
Try to analyze the code
Place it in a finction which will be called on click of the function:
on success you may use css like code:
This is just an example in ajax/jquery
$.ajax("signin.php", {
data: {
login: login,
pass: pass
},
success: function(data)
{
//alert(data);
if (data==1)
{
s$("#login").animate({ opacity: 1,top: '49%' }, 200,function(){
$('.userbox').show().animate({ opacity: 1 }, 500);
$("#login").animate({ opacity: 0,top: '60%' }, 500,function(){
$(this).fadeOut(200,function(){
$(".text_success").slideDown();
$("#successLogin").animate({opacity: 1,height: "200px"},500);
});
})
})
}
else
{
alert(data);
setTimeout( "unloading()", 1000 );
showError('OOPS..please check the credentials..');
}
},
error: function()
{
//alert(data);
showError('OOPS..Error in Connection..');
},
type: "POST"
});
Just a quick script, but hope it helps:
in getnew.php
$select = mysqli_select_db($conn, "database");
function get_random_image(){
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$result=[
'link' => $row['link'],
'rating' => $row['rating'],
'sigma' => $row['sigma']
];
return $result;
}
if($_POST['request']=='get_random_image'){
$r = array();
array_push($r, get_random_image());
array_push($r, get_random_image());
echo json_encode($r);
}
in javascript file:
$("#button").on("click",function(){
show_image();
})
function show_image(){
var response = get_data("get_random_image");
response = jQuery.parseJSON(response);
$.each( response, function( key, value ) {
// do something with the data like this:
$('.image').append('<img src="'+value.link+'">');
}
}
function get_data(requested_action)
{
var data=$.ajax({
type: "POST",
url: '../getnew.php', // relative path to the php file
data: {
request:requested_action
},
async: false,
dataType: 'json'
});
var msg= data.responseText;
return msg;
}
I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";