Performing an AJAX call using Object-Oriented Programming in PHP

The application is designed to display an image, along with the name and occupation based on user input when hovered. I am encountering the following issues: Notice: Undefined index: src in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php and Notice: Undefined index: name in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php

Since I am relatively new to Ajax, any assistance would be greatly appreciated.

$(document).ready(function() {
    $('#view').click(function() {
        var namevalue = $('#name').val();
        $.post("PHP_AJAX.php", {
            name: namevalue
        }, function(data) {
            $('#bar').html(data);
            $("img").hover(function(e) {
                var s1 = "<img src=";
                var s2 = " width='110px' height='120px' />";
                var srcval = s1.concat($(this).attr('src'), s2);
                $.post("PHP_AJAX.php", {
                    src: srcval
                }, function(data1) {
                    $('#info').css({
                        top: e.clientY,
                        left: e.clientX,
                        backgroundColor: 'yellow'
                    }).fadeIn().html(data1);
                });
            }, function() {
                $('#info').fadeOut();
            });
        });
    });
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="PHP_AJAX.js"></script>
    <style>
        #info {color:black; border:5px blue solid; width:150px; height:100px;display:none;position:absolute;}
    </style>
</head>
<body>
    <p id='bar'>Please enter name to view image! </p>
    <p id='info'>info</p>
    <form>
    <p>Name : <input type='text' name='name'id ='name'/></p>
    </form>
    <button id='view' name ='view'>View</button>
</body>
</html>

class Person
{
// some properties
    private $name;
    private $occupation;
    private $image;
// constructor
    public function __construct($nameval, $occuval, $imgval)
    {
        $this->name       = $nameval;
        $this->occupation = $occuval;
        $this->image      = "<img src=" . $imgval . " width='110px' height='120px' />";
    }
// get name property
    public function getname()
    {
        return $this->name;
    }
// get occupation property
    public function getoccupation()
    {
        return $this->occupation;
    }
// get image property
    public function getimage()
    {
        return $this->image;
    }
}

$obj1 = new Person("Picasso", "Painter", "pi1.jpg");
$obj2 = new Person("Ronaldo", "Football Player", "ronaldo.jpg");
$obj3 = new Person("Picasso", "Teacher", "pi2.jpg");
$obj4 = new Person("Madonna", "Singer", "madonna.jpg");
// storing objects in an array
$arr   = array($obj1, $obj2, $obj3, $obj4);
$count = 0;
for ($i = 0; $i < 4; $i++) {
// if name already exist
    if ($arr[$i]->getname() == $_POST['name']) {
        echo "<p>Image of " . $arr[$i]->getname() . "</p>";
        echo "<p>" . $arr[$i]->getimage() . "</p>";
        $count++;
    }
    if ($arr[$i]->getimage() == $_POST['src']) {
        echo "<p>Name: " . $arr[$i]->getname() . "</p>";
        echo "<p> Occupation:" . $arr[$i]->getoccupation() . "</p>";
        $count++;
    }
}
// if name doesn't exist
if ($count == 0) {
    echo "<h3> NOT FOUND! </h3>";
}

Answer №1

It's always a good practice to use the isset() function before comparing values, for example:

$arr[$i]->getname() == $_POST['name']

Therefore:

if (isset($_POST['name']) && $arr[$i]->getname() == $_POST['name']) {
    ...
}

if (isset($_POST['src']) && $arr[$i]->getimage() == $_POST['src']) {
    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conditionals are always evaluated as true

After writing this post function in my jQuery plugin, I encountered a peculiar issue. I have a doubt about the condition statement in this jQuery code. Can you confirm if it is correct? if(info = "enabled"){ $("#mod"+mod_id+" > img.status").attr(" ...

How can I use Ajax to open views in Asp.net Core 3.1?

Why is the view not being displayed even though there is no error? jQuery : $('#edit_button').on("click", function () { var instance = $('#jstree').jstree("get_selected"); if (instance != 0) ...

File uploading class in CodeIgniter - naming files with current date and time

I am looking to customize CodeIgniter's file uploader class so that each uploaded file is saved with a filename based on the date and time, regardless of the file type. Here is my current upload function: function do_upload() { $ ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

Guidelines for Naming Data Attribute Values in JavaScript

When it comes to the Data Attribute Value, should one use hyphens or camelCase as a convention? Hyphen Example: <input type="text" name="some_input" data-target="to-grab-input-via-javascript"> Camel Case Example <input type="text" name="some_ ...

PHP Quick Tip: How to effortlessly update a JSON array with new data

{ "messages": [ { "sender": "x", "message": "Placeholder", "date": "May 8, 2016 11:47:45 PM" } { "sender": "y", "mess ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

What is the best way to retrieve information from a database?

Last year, I hired a developer to work on some PHP and database tasks for me. He connected the website pages to a menu, which was stored in a separate function or table. I'm not quite sure why linking everything to a menu is necessary. Here's th ...

I'm missing out on that gray background

input your code hereI am working with the following html/php code snippet: <div class="footerbottom"> <span class="footermenuitem"> <span class="footermenutitle">PRODUCTS</span> <?php $menu = menu_navigation_links('menu-pro ...

Unable to adjust the default thumbnail dimensions

I am currently working on a WordPress gallery and I am facing an issue with changing the default thumbnail size. Despite setting the photo as a post thumbnail with a natural size of 150x150 in the WordPress media settings, I have attempted to adjust the th ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Using JQuery Datatables to output HTML based on JavaScript conditional logic

I am presently working on a project that involves using JQuery Datatables to display my data. Within this project, I am utilizing the datatables render method to format the data before it is displayed. However, I have encountered a challenge where I need t ...

Utilizing Jquery UI's date picker function to dynamically select a date with the $_GET method

How can I manually set $_GET variables to choose the date on the date picker? http://jqueryui.com/demos/datepicker/ (for example: http://www.example.com/?day=8&month=3&year=2022) Is this a possibility? Thank you ...

Creating a condensed version of the process: Utilizing jQuery for thumbnail preview on hover to create an image slideshow

I've created a video preview slideshow function using jQuery. As a newcomer to jQuery, I'm questioning if there's a more efficient way to achieve this. Having separate timers for each frame feels cumbersome and limits the flexibility in chan ...

How can I utilize JSON data for calculations in PHP?

I'm having trouble using the JSON result in calculations. No matter what I try, it doesn't seem to work. <?php //product id $gp_id=$_GET['gp_id']; //Importing the database connection require_once('dbConnect.php'); ...

Add up the inputs whenever there is a change using jQuery

I'm trying to implement a feature in my code where the price is automatically recalculated every time there is a change. <table class="table table-striped table-bordered listItem"> <tbody> <tr> <th width="20%"> ...

What is the best way to target all elements sharing a common class?

Currently, I have a Boolean variable stored in a hidden input field. When the user is signed in, it's set to false; otherwise, it's set to true. I have download buttons that should link to a file for download. My goal is to hide these buttons an ...

Updating multiple rows in Laravel using input data

Check out the app here I recently created a multi-row update feature with JavaScript. The button function successfully retrieves the ID of each row, but now I'm facing a challenge. I want to include an input form for the data that is being updated. ...

Issue with Jquery .html() not adding content

Utilizing Jquery to dynamically update a list based on dropdown selections. After successfully fetching data and constructing the correct HTML content within the "item" variable, applying .html(item) does not result in the expected HTML updates. <div c ...

Issue with submit button functionality - troubleshooting with if-else logic

When my submit button is clicked, I want it to trigger an if-else statement. The goal is to check the 'complete' field in my users table and if the value is 6 or above, send an email (I already have the code for this). If the value is less than 6 ...