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

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

Error in ReactJS: Trying to access property 'items' of an undefined object

I've been diving into ReactJS, but I've hit a roadblock with this perplexing error. My goal is to update the parent's items array state from its child component. To achieve this, I attempted to pass the addItem function as a prop to the chi ...

Implementing an API-based login system in Laravel 8

Just created my first app using API. I am new to Laravel and PHP. This is the migration I have: Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('c ...

Issue with Django query not being successfully transferred to AJAX in JSON structure

Trying to populate a textfield with its corresponding database value using Django and AJAX. The objective is for the textfield to automatically update when the dropdown value changes. However, encountering an error in console: SyntaxError: Unexpected to ...

What's the reason behind the refusal of my connection to localhost at port 3000 in Node.JS?

As a student venturing into the world of back-end development for the first time, I decided to dive into learning Node.JS. To kick things off, I downloaded a PDF book titled "Jumpstart Node.JS" from SitePoint. Following the provided instructions, I attempt ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

Verifying whether every value in the X array is present in the Y array or not

Currently, I am working with two arrays: const arrA = [1, 2, 3, 4, 5]; const arrB = [1, 2, 3, 4, 5, 6, 7, 8, 9]; My goal is to determine if all elements in array A exist in array B. Here are a few scenarios for better clarity: const arrA = [1, 2, 3, 4, ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

What is the best way to retrieve each index from a particular Array within an AJAX object?

Currently, I am using an ajax call to request data from the giphy API. Here is the code snippet: $.ajax({ url: queryURL, method: "GET" }).then(function(response) { console.log(response); Upon checking the console log, I noticed that the response ob ...

Mongoose documents are set to automatically be deleted after a duration of one month

My goal is to retain a particular document for one month after the client-user deletes it. To achieve this, I have decided to simulate a delete action and display data in the browser. Sample schema: const product = new mongoose.Schema({ --- trash : { ty ...

Having trouble with Simplehtmldom's innertext function?

While working with simple_html_dom: I encountered the following code snippet: $j = ' <itemBody> <div>films - to watch (Simple Present)<br/> <textEntryInteraction responseIdentifier="RESPONSE_1"/> ...

Expanding a responsive HTML background image using Javascript

I've spent countless hours grappling with this code, attempting to dynamically resize the background of HTML based on the browser window size using JavaScript. Here's what I have so far (I'm using Firefox for this): GM_addStyle('body ...

Accordion menu causing Javascript linking problem

After following a tutorial, I managed to create an accordion menu in JavaScript. In the current setup, each main li with the class "ToggleSubmenu" acts as a category that can hide/show the sub-lis. Now, my query is this: How can I retain the link functio ...

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...