frosty
frosty

Reputation: 2851

Get data from PHP file on click of a button

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 ?>')">

Upvotes: 1

Views: 3133

Answers (3)

Uri Goren
Uri Goren

Reputation: 13682

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+"')");
   });
})

Upvotes: 1

Indra
Indra

Reputation: 702

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;
}

Upvotes: 0

lakshman
lakshman

Reputation: 656

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"
                      });

Upvotes: 0

Related Questions