Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a different script for an additional AJAX call. The results should be loaded into div C on page A. Unfortunately, I am having trouble getting this to work.

I searched online and found a similar question on Stack Overflow, but it seems to focus on triggering a second AJAX call automatically rather than through a form submission like in my case.

The current working code I have, which utilizes Prototype, looks like this:

first.php

<script type="text/javascript" src="js/prototype.js"></script>
<script> 
Ajax.Responders.register({
    onCreate: function(){ Element.show('spinner')},
    onComplete: function(){Element.hide('spinner')}
});
</script>

<form id="first_form">
<input  /> etc, etc
<input type="button" onclick="first_box()" value="Call get_first_data.php">
</form>

<script>
function first_box(){
new Ajax.Updater( 
        'first_div',
        'get_first_data.php', { 
            method: 'post',
            parameters: $('first_form').serialize()
});
}
</script>

<div id="first_div">
    <p>The output from get_first_data.php appears here.</p>
    <img alt="spinner" id="spinner" src="images/ajax-loader.gif" style="display:none;" />
</div>

To extend this functionality, I aim to trigger another script from the output of get_first_data.php within the first_text div on page first.php. The result of this second script should also display on first.php. I attempted to replicate the above code with adjustments in get_first_data.php, but it doesn't seem to be working as intended.

get_first_data.php

<script type="text/javascript" src="js/prototype.js"></script>
<script>
Ajax.Responders.register({
    onCreate: function(){ Element.show('spinner')},
    onComplete: function(){Element.hide('spinner')}
});
</script>

<form id="second_form">
<input  /> etc, etc
<input type="button" onclick="second_box()" value="Call get_second_data.php">
</form>

<script>
function second_box(){
new Ajax.Updater( 
        'second_div',
        'get_second_data.php', { 
            method: 'post',
            parameters: $('second_form').serialize()
});
}
</script>

<div id="second_div">
    <p>The output from get_second_data.php should appear here, but it's not displaying.</p>
    <img alt="spinner" id="spinner" src="images/ajax-loader.gif" style="display:none;" />
</div>

... continue with the remaining content from get_first_data.php ...

Lastly, I would like to know how to achieve the same functionality using jQuery instead of Prototype.

Answer №1

It seems like I've grasped your question correctly.

You mentioned, "I want to call another script from the get_first_data output in the first.php". What is the reason for wanting this? The content from get_first_data is loaded on-demand and may not be readily available at all times. Typically, it's standard practice to define JavaScript/jQuery scripts on a page that's loaded through an AJAX request. Below is the code implementation of this concept. Additionally, I have included a "callSecondBoxButton" button in first.php, which triggers the execution of the second_box() function defined in the dynamically loaded get_first_data.php page. Therefore, the second_box() function can be invoked from both first.php and get_first_data.php.

I'm not well-versed with the Prototype representation, but the jQuery script would be structured as indicated below.

If desired, consider utilizing the camelCase notation for the id attributes and enhancing error handling to display user-friendly alerts only.

first.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - first</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document)
                    .ready(function () {
                        $('#spinner').hide();

                        $('#firstButton').click(function (event) {
                            first_box();
                        });

                        $('#callSecondBoxButton').click(function (event) {
                            if (typeof second_box === 'function') {
                                second_box();
                            } else {
                                alert('The "second_box" function is not (yet) defined!');
                            }
                        });
                    })
                    .ajaxStart(function () {
                        $('#spinner').show();
                    })
                    .ajaxStop(function () {
                        $('#spinner').hide();
                    });

            function first_box() {
                $.ajax({
                    method: 'post',
                    dataType: 'html',
                    url: 'get_first_data.php',
                    data: $('#first_form').serialize(),
                    success: function (response, textStatus, jqXHR) {
                        $('#first_div').html(response);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $('#first_div').html(textStatus + '<br />' + errorThrown);
                    },
                    complete: function (jqXHR, textStatus) {
                        //...
                    }
                });
            }
        </script>
    </head>
    <body>

        <form id="first_form">
            <input type="text" value="abc" />
            <input type="button" id="firstButton" value="Call get_first_data.php">
            <input type="button" id="callSecondBoxButton" value="Call second_box() from first.php">
        </form>

        <div id="first_div">
            <p>
                The output from get_first_data.php appears here.
            </p>
            <img alt="spinner" id="spinner" src="images/ajax-loader.gif" />
        </div>

    </body>
</html>

get_first_data.php

<script type="text/javascript">
    $(document).ready(function () {
        $('#secondButton').click(function (event) {
            second_box();
        });
    });

    function second_box() {
        $.ajax({
            method: 'post',
            dataType: 'html',
            url: 'get_second_data.php',
            data: $('#second_form').serialize(),
            success: function (response, textStatus, jqXHR) {
                $('#second_div').html(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('#second_div').html(textStatus + '<br />' + errorThrown);
            },
            complete: function (jqXHR, textStatus) {
                //...
            }
        });
    }
</script>

<hr />

<form id="second_form">
    <input type="text" value="def" />
    <input type="button" id="secondButton" value="Call get_second_data.php">
</form>

<div id="second_div">
    <p>
        The output from get_second_data.php should appear here, but it doesn't.
    </p>
    <img alt="spinner" id="spinner" src="images/ajax-loader.gif" />
</div>

get_second_data.php

<hr />

<div>
    I am the content/data of get_second_data.php.
</div>

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

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

Personalized Assistance - PHP Helper Class

Greetings, I have developed a PHP Web application utilizing Zend Framework and MVC with a MySQL database. My next goal is to incorporate Context-Sensitive Help into the application, but after conducting research, I have been unable to find any helpful gui ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

Utilizing one URL to post parameters and retrieving JSON data from a different URL

Currently I am working with jQueryMobile and PhoneGap, but encountering an issue. I am trying to retrieve details in JSON format by posting parameters to one URL (URL1) and receiving the JSON response from another URL (URL2). However, I am unable to access ...

Auto-suggest feature using Jquery for dynamically pulling suggestions from a database table

How can I implement an auto-suggest text field that can fetch usernames from my database? I intend to utilize the autocomplete plugin from Jquery UI for this purpose. My aim is to create a fast and highly secure solution. ...

Client-side validation with Jquery is failing to function properly

Currently, I am experimenting with the jquery.validate.unobtrusive.js plugin to dynamically generate form fields. Here is an example of how I'm creating a textarea field: var message = $("<textarea id='test'></textarea>"); $(mes ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

Choosing multiple values in the selectize plugin from the controller: A step-by-step guide

Need help with selecting multiple options I'm utilizing the following plugin: https://github.com/selectize/selectize.js/blob/master/docs/usage.md I have an object as displayed in the image below: https://i.stack.imgur.com/sQsKe.png This is my Client ...

Handling errors in Angular and rxjs when encountering undefined returns in find operations

I am currently faced with the challenge of catching an error when the variable selectionId, derived from my route, is null or contains an invalid value. My code structure has a mechanism in place to handle errors when the category variable is undefined, bu ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

Creating a custom video to use as the favicon for my website

Imagine this: With the help of this plugin, you can have a video playing as your site's favicon using the following code snippet: var favicon=new Favico(); var video=document.getElementById('videoId'); favicon.video(video); //stop favicon.v ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

Preventing Credit Card Charges with Stripe in Laravel 4: Waiting for Another Form Submission

Currently, I am in the process of creating a form that will include a Stripe payment button. The layout is expected to resemble the following (consider the finish button as faded out with all necessary information yet to be filled in): My intention is for ...

What is the best way to display circles (generated from JSON data) in reverse order by incorporating a delay function?

I am currently working on creating an interactive visualization using circles that expand over a specified period, all centered at the same point. I have a script that generates these circles and saves the data in a JSON file. The smallest circle is posit ...