0

I am unable to get a button to work as I intend it to in Drupal 7.

I am adding the button to the add content page of a specific content type using form alter:

function charlie_get_form_article_link_node_form_alter(&$form, &$form_state, $form_id) {

    $form['add_button'] = array(

        '#type' => 'item',

        '#markup' => '  
            <script>
                function getArticleInfo() {
                    jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                        console.log(articleHTML);
                    });
                    return false;                       
                }
            </script>

            <button type="button" onclick="getArticleInfo()">
                Submit URL
            </button>

        ',

    );

}

I have simplified the articlegrabber.php file down to just this (though I don't think it matters, because the button click does not seem to be executing the JS):

<?php

$ogLink = $_GET['url'];

echo $ogLink;  ?>

Instead of my intended results (which the code delivers independent of its implementation in Drupal), the console logs the HTML for the add content page that the button is on.

I have read a lot about how Drupal likes to make all button types "submit", but my button is actually rendering as type="button". The HTML from the rendered page (as you would expect):

                    <script>
                        function getArticleInfo() {
                            jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                                console.log(articleHTML);
                            });
                            return false;                       
                        }
                    </script>

                    <button type="button" onclick="getArticleInfo()">
                        Submit URL
                    </button>

Any ideas about how to get it to execute the code on click rather than returning the HTML for the page would be much appreciated.

1

You need Simple Drupal AJAX load with jQuery and delivery callback which is explained in 5 simple steps this page.

So include a anchor link through the form alter and have the link render the content through attached javascript file through jQuery.load() function.

To attach js file,

$form['#attached']['js'][] = array(
  'data' => drupal_get_path('module', 'module_name') . '/some_file.js',
  'type' => 'file', 
);

For Drupal ajax forms refer this official documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.