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;
}
Related
I have a separate PHP file containing a valid mysql query returning # of Rows representing my criteria (No. of active Notifications), and I have a JQUERY code to display notifications counter, but I only can use it statically with .text('5') for example. I want to be able to link the PHP MYSQL query result to the JQUERY output on browser.
notfcounter.php:
<?php
function getNotCount() {
require_once $_SERVER['DOCUMENT_ROOT'] . 'info.php';
$conn = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$count = $_POST['action'];
$sqlquery = "SELECT did FROM users WHERE users.uid=".$_SESSION['id'];
$result = $dbc->query($sqlquery);
while ($row = $result->fetch_assoc()) {
$rows = $row['did'];
}
$countquery = "SELECT noname, noaction FROM notfs WHERE notfs.did=".$rows." AND notfstatus = 0";
$result2 = $dbc->query($countquery);
if (mysqli_num_rows($result2)!=0)
{
$count = mysqli_num_rows($result2);
echo ''.$count.'';
}
else
{
$count = 0;
echo ''.$count.'';
}
echo $count;
}
?>
JQUERY external file:
$(document).ready(function () {
// ANIMATEDLY DISPLAY THE NOTF COUNTER.
$('#notfs_Counter')
.css({ opacity: 0 })
//.text('5') this is what I use to display a counter statically
$.ajax({
type: 'post',
url: 'notfcounter.php',
data: {action: 'getNotCount'},
success: function(data) {
alert(data);
}
})
.css({ top: '0px' })
.animate({ top: '0px', opacity: 1 }, 500);
});
after researching more about AJAX, I got to understand it better and knew where I was wrong.
I had to adjust my code to reposition the $(selector). commands inside the AJAX success function call to properly display my data. Also, I didn't need a function on my PHP code, I removed the function and echo'd the needed variable for display $count, and modified AJAX action to count, code is below:
AJAX & JQUERY:
$.ajax({
type: 'post',
url: 'notfscounter.php',
data: {action: 'count'},
success: function(data) {
//alert(data)
$('#notfs_Counter').css({opacity: 0})
$('#notfs_Counter').text(data)
$('#notfs_Counter').css({ top: '0px'})
$('#notfs_Counter').animate({ top: '0px', opacity: 1 }, 500);
}
});
PHP:
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . 'info.php';
$conn = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$sqlquery = "SELECT did FROM users WHERE users.uid=".$_SESSION['id'];
$result = $dbc->query($sqlquery);
while ($row = $result->fetch_assoc()) {
$rows = $row['did'];
}
$countquery = "SELECT noname, noaction FROM notfs WHERE notfs.did=".$rows." AND notfstatus = 0";
$result2 = $dbc->query($countquery);
if (mysqli_num_rows($result2)!=0)
{
$count = mysqli_num_rows($result2);
echo ''.$count.'';
}
else
{
$count = 0;
echo ''.$count.'';
}
echo $count;
?>
special thanks to #ADyson for his encouraging & helpful guide.
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);
}
});
}
I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];
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']";
my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });