Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version)

I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no other ticket exists. If the generation is successful, it should return 1, otherwise 0.

However, currently it's returning the header.php along with the response (0 or 1) at the end. How can I prevent it from returning header.php?

AJAX:

function generateTicket() {
  $.ajax({
    url: 'generateTicket.php',
    type: 'post',
    datatype: "json",
    data: {
      showid: <?php echo $showid ?>,
      seats: <?php echo $seats_json ?>
    },
    success: function(response) {
      alert(response);  
    }
  });
}

generateTicket.php:

<?php 
include('includes/header.php');

//Login check
if (!$loggedIn) {
    header('Location: login.php');
    die();
}

//Variable initialization
$userid = $_SESSION['userid'];
$showid = $_POST['showid'];
$seats = $_POST['seats'];
$result = 1;

//Generate a ticket for each seat
foreach($seats as $seat){
    //Load ticket from database
    $query = "SELECT * FROM  ticket_uebersicht WHERE Sitzplatz LIKE ? AND VorstellungID = ? LIMIT 1";
    $statement = $pdo->prepare($query);
    $statement->execute(array($seat, $showid));
    $row = $statement->fetch();

    //Check if ticket exists
    if(!$row){
        $code = guidv4();
        $query = "INSERT INTO tickets (code, UserID, VorstellungID, Sitzplatz) VALUES (?,?,?,?)";
        $statement = $pdo->prepare($query);
        $statement->execute(array($code, $userid, $showid, $seat));
        continue;
    }else{
        if($row['marktplatz'] != 0){
            //Adjust existing ticket
            $code = guidv4();
            $marketplace = '0';
            $query = "UPDATE tickets SET UserID = ?, code = ?, marktplatz = ? WHERE Sitzplatz = ? AND VorstellungID = ? AND NOT marktplatz = 0 LIMIT 1";
            $statement = $pdo->prepare($query);
            $statement->execute(array($userid, $code, $marketplace, $seat,  $showid));
            
            //Process refund
            if(!($row['UserID'] == -1)){
                $betrag = $row['preis'] - 2;
                $query = "INSERT INTO rueckerstattung (UserID, Betrag) VALUES (?,?)";
                $statement = $pdo->prepare($query);
                $statement->execute(array($row['UserID'], $betrag));
            }
            continue;
        }
        $result =  0; //Error
    }
    
}

echo json_encode($result);

//Generate Ticket ID (GUID)
function guidv4($data = null) {
    // Generate random data
    $data = $data ?? random_bytes(16);
    assert(strlen($data) == 16);

    // Set version and variant bits
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

    // Format UUID
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
exit;
?>

header.php:

<?php
include('db_connect.php');
include('righthandler.php')
?>

<!-- Header -->
<!DOCTYPE html>
  <html lang="de">
  <head>
    ... Head content goes here ...
  </head>

  <!-- Website Header with Navigation Bar-->
  <!-- Navbar Code goes here -->

AJAX success response: (my index.php)

<!DOCTYPE html>
  <html lang="de">
  <head>
    ... This section contains the head content ...
  </head>

  <!-- Website Header with modified Navigation Bar and success message. -->
  <!-- Updated navbar info displayed here. -->
1

Answer №1

Your index.php file's content can be found in the header.php file. By including header.php in the generateTicket.php file, you essentially retrieve the body of index.php in your ajax request. The include statement acts as a placeholder that is replaced by the content of the included file.

To resolve this issue, you can either relocate the HTML code from header.php to a different file or refrain from including header.php in generateTicket.php.

If neither solution works for you, there is a workaround available. You can capture the output from header.php using output buffering and then discard it.

ob_start();
include('includes/header.php');
ob_end_clean();

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

assign a class to a PHP variable

I am struggling with the syntax needed to add a class to the $output variable that I want to display here. As someone who is not very familiar with PHP, I attempted to include a breadcrumb divider using css 'content:' but couldn't figure out ...

Having trouble with arrays in JavaScript - receiving TypeError when trying to set a property

Issue: An error has occurred - Uncaught TypeError: Cannot set property '0' of undefined Snippet of relevant code: var field = new Array(6); for(var x=0; x<field.length; x++){ field[x] = new Array(12); for(var y=0; y<field[x].length; y ...

JavaScript - If you change the properties of an object within an array, does it automatically set the array as needing an update?

If we were to imagine a scenario where there is an array containing 3 objects, and then I decide to access the second object by its index in order to modify one or more of its properties, what would happen? Would this modification mark the entire array a ...

jQuery's :last selector allows you to target the last

I need assistance with my jQuery code $('#share_module:last').css("background-color","red"); Unfortunately, it is only affecting the first #share_module Here is an example of the HTML structure: <div id = "share_module" class = "id of the ...

Ways to extract the content from the textarea

Currently, I am working on a project that involves using CKEditor. Within the project, there is a panel with various properties used to create a tooltip. I decided to utilize CKEditor to insert content into the tooltip because it provides an excellent user ...

The object returns true when the specified condition matches the key within the object

I need assistance with a specific object query. I am looking to execute the filter function in order to retrieve a list of keys from an object where the condition is true, as shown below: myObject = { key1: { name:"key1", select:true }, ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Incorporate the ajax response into the design of the Material Design

I am looking to create a website that dynamically updates content using AJAX requests. I have JSON data that needs to be displayed in MDL cards. You can learn more about MDL cards here. Here is my AJAX code: $(document).ready(function(){ displayRecor ...

The JQuery video player's full screen toggle feature is not correctly assigning the class name

I've been tackling a bug in my JavaScript/jQuery video player that has left me stumped. One of the key features of this player is an enter/exit full-screen button located at the bottom of the HTML snippet: (function($) { /* Helper functions */ ...

Activate the Masterpage menu to emphasize its current state

I am currently utilizing the AdminLTE template on my website. One issue I have encountered is with the menu and its child menus. When redirecting to different pages using image buttons, the menu collapses back to its original state. While navigating throu ...

Is there a way to extract an ID from a URL using PHP?

Hey there, I have a link that looks like this: I also have similar links and I'm looking to extract the ID from each one. The challenge is that the characters surrounding the ID vary for each link, so simply cutting out characters from the left and r ...

Exploring the significance of $this in PHP within object-oriented programming

What is the scope of $this in PHP? Can we declare it outside a function, within a class? class Blogs extends Controller { public $articlesmodel; public function __construct() { $this->articlesmodel = $this->loadmodel('a ...

Developing hierarchical JSON objects with PHP and MySQL

Suppose I've successfully created two tables within my database: `INSERT INTO `months` (`month_id`, `month_name`) VALUES ('1', 'January');` and `INSERT INTO `weeks_and_days` (`week_id`, `week_nr`, `day_nr`) VALUES ('1&apos ...

Unlocking the Secrets of Launching a Modal with Javascript

I currently have an HTML code that includes a fabulous floating button. When I click on this button, I would like to open a modal popup window but unfortunately, I am unsure of how to achieve this. index.html <html> <head> <link rel="s ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...

Problems arising from jQuery Mobile, NPM, and WebPack

After spending a considerable amount of time researching and experimenting, I am confident that I could piece something together to make it work. However, I would rather gain an understanding of the root cause of my issue. It is widely acknowledged that j ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...

How can I deactivate all form controls within an AngularJS form?

To prevent any changes to the form components when the view button is clicked, I need to disable them. Here is my form: <form action="#" class="form-horizontal" > <div class="form-group"> <label for="fieldname" class="col-md-3 cont ...

Discovering the differences between input values in HTML when using scripts

I have a code snippet here for an HTML project. The code includes an input field for username and password. I am looking to compare the user's input with a specific value using JavaScript. My question is, what code should be included in the button cli ...