Patrick Traile Patrick Traile - 2 months ago 15
Ajax Question

Sending values between AJAX and PHP

<?php //Site root variable; ?>
<?php require_once("../includes/site_init.php"); ?>

<!DOCTYPE HTML>

<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Creativity Optimized.</title>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="https://npmcdn.com/imagesloaded@4.1/imagesloaded.pkgd.min.js"></script>
<script src = "_scripts/main.js"></script>
<!-- <script src = "_scripts/custom.js"></script> -->
<script src="https://unpkg.com/masonry-layout@4.1/dist/masonry.pkgd.min.js"></script>
<link rel="stylesheet" href="_css/custom.css">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,400i,600,700&subset=latin-ext" rel="stylesheet">
<link rel='shortcut icon' href='_images/favicon.png'>
</head>

<body>



<?php //Header include; ?>
<?php require("../includes/header_include.php"); ?>


<section class = "hero">

<div class = "heroOverlay"></div>

<ul class = "heroText">

</ul>

<ul class = "heroNav">

</ul>

</section>



<section class="welcome-text-container">
<h1>Welcome to MP</h1>
<p class="welcome-text">
MP Creations® is a unique advertising agency and visual design studio.
We create visual content for almost any medium to tell compelling stories for our clients.
Our methods rely on creative and strategic thinking. We do it with passion, love and care. See you soon.
</p>
</section>

<div class="content-heading-container">

<h1 class="content-heading">why us?</h1>

</div>

<section id = "mainContent">
<a href="work.php" title="Forward thinking" class="item-buttons">
<img src="_assets/mp_forward_thinking.png" alt="forward thinking" />
</a>
<a href="work.php" title="Lets work together" class="item-buttons">
<img src="_assets/mp_work_together.png" alt="working together" />
</a>
<a href="work.php" title="Projects to play" class="item-buttons">
<img src="_assets/mp_play_projects.png" alt="play projects" />
</a>
<a href="work.php" title="Nesletter" class="item-buttons">
<img src="_assets/mp_newsletter.png" alt="working together" />
</a>

</section>


<section id = "workPreview">
<div class = "sectionGrids">
<h2><span>Recent Developments</span></h2>
<div class = "grid" >

<?php $all_portfolio_items = PortfolioItem::find_all();
foreach ($all_portfolio_items as $item) { ;?>
<div class="grid-item">
<a href=work.php data-jobID = '<?php echo $item->id; ?>'>
<img class="grid-img-hover" src='<?php echo '_portfolio-items'.DS.$item->filename; ?>'/>
<div class="title-wrap-hidden"><p class="job-name-hidden"><span><?php echo $item->job_id; ?></span></p></div>
<div class="title-wrap"><p class="job-name"></p></div>
</a>
</div>
<?php ; } ?>

</div>

<p><a href="work.php">See More Creations</a></p>
</div>
</section>

<?php //Footer include; ?>
<?php require("../includes/footer_include.php"); ?>

<?php
// chdir("_images");
// $file = "somefile.txt";
// $handle = fopen("$file","wt");
// fwrite($handle,"peaches and cream");
// fclose($handle);
?>


<script>
$(document).ready(function(){
$(document).on('mouseenter', '.grid-item', function(){

var container = $(this);
var jobId = container.children().find('.title-wrap-hidden').text();

// AJAX request
$.ajax({
url: 'db_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data) {
// success
container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
alert(errorThrown);
}
});
});


$(document).on('mouseleave', '.grid-item', function(){

var container = $(this);
container.find('.title-wrap').html('<p class="job-name"></p>');

});
});
</script>

</body>

</html>


I have this php that loads in some images from a database to the front end. What I want to do now is when I hover over (mouseover) an image, I want to pass the $item->job_id to another php script using AJAX so that I can use that job_id to look up the name of that image from another table in the database.

the other php script might simply look something like this

<?php require_once("../includes/site_init.php");
require_once("../includes/site_init.php");

if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];

$portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
echo $portfolio_item_name[0]->name;
}else {
echo 'result failed';
}
?>


So job_id would come from the AJAX request calling this php file and the AJAX itself would get job_id from the previous php up above. What might the AJAX look like for something like this? and what changes would be needed for the php scripts?

Answer

You can use jQuery and AJAX to asynchronously send $item->job_id to a PHP page. The solution would be,

  • Place the below jQuery code just above the ending </body> tag, like this:

    <!--YOUR CODE-->                
    
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
    <script>
        $(document).ready(function(){
            $(document).on('mouseover', '.grid-img-hover', function(){
                // job id
                var jobId = $(this).parent().find('.title-wrap').text();
    
                // AJAX request
                $.ajax({
                    url: 'yourpage.php',
                    type: 'POST',
                    data: {jobId: jobId},
                    success: function(data) {
                        // success
                        alert(data);
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        // error
                        alert(errorThrown);
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    

    Note: Don't forget to change yourpage.php in the url setting of AJAX request.

  • And on yourpage.php page, process your AJAX request in the following way,

    require_once("../includes/site_init.php");
    
    if(isset($_POST['jobId'])){
        $job_id = $_POST['jobId'];
    
        $portfolio_item_name = Job::find_by_sql('SELECT name FROM '.static::$table_name." WHERE id = '" . $job_id . "' LIMIT 1");
        echo $portfolio_item_name->name;
    }
    
Comments