0

I'm not a programmer, so I'm in trouble despite searching the net.

I am using a JS script inserted in WordPress through which I enter a domain and it returns me some data.

The script calls an external PHP file.

However, when I click the form button, it returns me an HTML string which includes the value of the previously entered input field and, instead of the DATA value it processed from the PHP file, the string [object Object].

This is HTML:

<div class="divtoolg">
<form id="form">
        <div class="form-group">
            <input class="form-control" type="text" id="domain" required placeholder="Enter Input">
        </div>
        <div class="form-group">
            <button class="btn btn-danger btn-block">
                Get Data
            </button>
        </div>
        <div id="result"></div>
</form>
</div>

This is the script:

/*jshint esversion: 6 */
let $ = jQuery;
$(document).ready(function(){
        $("#form").submit(function(e){
            e.preventDefault();
            $("#result").html("");
            var domain = $("#domain").val();
            console.log(domain);

            $.ajax({
                metod: 'POST',
                url:'process.php',
                data:{domain:domain},
                async: true,
                
                complete:function (data) {
                console.log("data ="+data);
                $("#result").html(`<h2>The ${domain} is ${data} old </h2>`);
                $("#domain").val(domain);
                },
                error:function () {
                $("#domain").val("");
                $("#result").html("Error!");
                }
            });
        });
});

This is the PHP file:

<?php

if(isset($_POST['domain']))
{
require('Ageclass.php');
$w=new DomainAge();
echo $w->age($_POST['domain']);
}
?>

Anyone have any ideas? Many thanks.


New JS

/*jshint esversion: 6 */
let $ = jQuery;
$(document).ready(function(){
        $("#form").submit(function(e){
            e.preventDefault();
            $("#result").html("");
            var domain = $("#domain").val();
            console.log(domain);

            $.ajax({
                method: 'POST',
                url:'../process.php',
                data:{domain:domain},
                
                success:function (data) {
                console.log(data);
                $("#result").html(`<h2>The ${domain} is ${data} old </h2>`);
                $("#domain").val("");
                },
                error:function () {
                $("#domain").val("");
                $("#result").html("Error!");
                }
            });
        });
});
  • 1
    It's likely that `data` is an array or object, rather than a string. the browser does not know how you wish that to be displayed, so it simply displays [Object object] instead. This is a prompt to you that you need to process the data first, and extract from it the information that you actually need on screen. When you logged `data` to your console, what does it show you? P.S. Try just `console.log(data);` without the data= part. – ADyson Jan 13 '21 at 11:14
  • Hello and thanks.So, with `console.log(data)` same thing. –  Jan 13 '21 at 12:41
  • Which browser are you using to test this? In most modern browsers it would allow you to expand the object in the console. If not, try `console.log(JSON.stringify(data));` to get a visual representation in JSON. (See also [this question](https://stackoverflow.com/questions/47842644/js-log-object-why-is-showing-object-object) for more logging options.) Another way to try and view it is to look in the "Network tab" in your Developer Tools, find the request to process.php, open it up and look at the Response tab for that request. – ADyson Jan 13 '21 at 12:42
  • So, in console return this: "{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}". On tab Network the file is present with 200 OK response but here, the request method, is GET?!?!? –  Jan 13 '21 at 13:08
  • Ohhh...I just noticed you're using the "complete" callback for some reason. Have a look at what it returns, according to the documentation: https://api.jquery.com/jquery.ajax/ . If you want to get just the actual data returned, and not the entire internal XHR object (which has full details of the HTTP request & response), then use the "success" callback. i.e. replace `complete(data) {` with `success(data) {` - again check the documentation. And also, almost every jQuery ajax tutorial you would ever see will use "success" (unless they use Promise-like callbacks), you never see "complete" used. – ADyson Jan 13 '21 at 13:19
  • `On tab Network the file is present with 200 OK response but here, the request method, is GET`... that's because you have a typo: `metod: 'POST'` should be `method: 'POST'`. Always double-check your work :-) – ADyson Jan 13 '21 at 13:20
  • P.S. `async: true` is redundant - `true` is the default value for this option, so you don't actually need to include this line at all. – ADyson Jan 13 '21 at 13:23
  • (METOD) What a stupid mistake, sorry. However it is frustrating. Believe it or not, I also tried "success". The difference is that nothing is printed in "result" with success, not even object. –  Jan 13 '21 at 13:37
  • Well that is likely to be fixed if you change the method. Try it again. (Unless of course $w->age doesn't return a value for any reason. You could always try echoing a hard-coded value instead, to test out the Ajax part.) – ADyson Jan 13 '21 at 13:48
  • No, it still doesn't work. "You can always try to repeat a hard-coded value, to test the Ajax part.)". Unfortunately what you say to me is incomprehensible, I am not a programmer and what I have done so far has been really difficult for me. –  Jan 13 '21 at 13:55
  • Now, after correcting METHOD, and setting SUCCESS, I no longer get response but I get 404 error on PHP file –  Jan 13 '21 at 14:02
  • By hard-coding a value I meant you could replace `echo $w->age($_POST['domain']);` with something like `echo "test";` to ensure that the AJAX part is working successfully, without relying on the age function. – ADyson Jan 13 '21 at 14:24
  • But anyway, if the file process.php is in the same folder on the server as the file containing the HTML, then it makes no sense it would return a 404, just because you changed the method. The only reason could be maybe if the webserver has something configured in it (maybe in a .htaccess file) to prevent access to certain URLs via POST. But normally that would return a 405 error, not 404. – ADyson Jan 13 '21 at 14:25
  • P.S. Can you please update the question to show your code as it looks now, after you changed it. – ADyson Jan 13 '21 at 14:29
  • So, the suggested "test" echo test also failed. Error 404 is not on file not found which is not in the same folder as the html file. I remind you that we are on WordPress and therefore the HTML is inside a page while the PHP and JS files are in a custom folder. However, the 404 error is generated for a (new) conflict with theme jquery (precisely here: try {r.send (i.hasContent && i.data) –  Jan 13 '21 at 14:36
  • Sorry the information in your last comment is very unclear. What does a 404 have to do with some JS code or a jquery theme? It might be better if you post a screenshot showing the error details. – ADyson Jan 13 '21 at 14:53
  • No, sorry, i can't. –  Jan 13 '21 at 15:19
  • Why not, exactly? You can put a picture on imgur and then link to it. Without fully clear information of what is going on it's going to be very difficult to help you. – ADyson Jan 13 '21 at 15:32
  • Anyway if it's process.php which returns the 404, then you need to make sure that the link to process.php is correct _relative to_ the URL in which the $.ajax code is running (note that it's relative to the URL in which the page is loaded, not to the location of the JS script on disk). – ADyson Jan 13 '21 at 15:35
  • I'm working on a answer, hang tight – joshmoto Jan 13 '21 at 15:37

1 Answers1

1

This might help you get on the right track with handling ajax better in wordpress, the right way.

This answer will probably need to be a work in progress to get it exactly to your requirement, as it is not clear what you are exactly after. Follow these instructions below...


Lets tidy up your form a bit, and lets just use name instead of id for targeting inputs.

<form id="form">
   <div class="form-group">
      <label for="domain">Domain</label>
      <input class="form-control" name="domain" type="text" placeholder="Enter domain" required>
   </div>
   <div class="form-group">
      <button class="btn btn-danger btn-block" type="submit">Get Data</button>
   </div>
</form>

Now lets create a wordpress ajax url window variable which can be used inside your js files or inline on your wordpress pages.

Place this html/php in your wordpress template <head> before the ajax js script is loaded...

<script>window.admin_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';</script>

As you can't use the above because you can't manually edit theme files, see updated js code below including this var non-dynamically.

Now lets tidy up your form js and wordpress ajax call...

// document ready
jQuery(document).ready(function ($) {
     
    // non-dynamic wordpress ajax url
    const admin_ajax_url = '/wp-admin/admin-ajax.php';

    // our form jquery object
    const $form = $('#form');

    // on form with id submit
    $form.on('submit', function (e) {

        // prevent the form from submitting
        e.preventDefault();

        // set empty submission object
        let submission = {};

        // for each of this form submit event target object entries as key/field
        for (const [key, field] of Object.entries(e.target)) {

            // if object entry (field) has a name attribute
            if (field.name) {

                // add name/value to submission object
                submission[field.name] = field.value;

            }

        }

        // our form submit ajax call
        $.ajax({
            method: 'GET',
            url: admin_ajax_url,
            data: {
                action: 'handle_form_submission',
                submission: submission
            },
            success: function (response) {

                // console our response (object, not string)
                console.log(response);

            },
            error: function (response) {

                // do error js send response

                // console our error response (object, not string)
                console.log(response);

            }
        });

    });

});

In your functions.php, add this code to handle the ajax form submission send json responses...

// require your age class (make sure you are actually hitting this)
require_once(__DIR__ . '/lib/DomainAge.lib.php');

// add our handle #form submission php ajax actions
add_action('wp_ajax_nopriv_handle_form_submission', 'handle_form_submission', 20);
add_action('wp_ajax_handle_form_submission', 'handle_form_submission', 20);

// function to handle submission
function handle_form_submission() {

    // get our form submission object
    $submission = $_GET['submission'];

    // create our domain age object
    $domain = new DomainAge();

    // get our domain age result
    $age = $domain->age($submission['domain']);

    // dump results
    var_dump($submission['domain'];
    var_dump($age);

    // if we have domain age
    if($age) {

        // send age response
        wp_send_json_success($age);

    } else {

        // send error response
        wp_send_json_error([
            'message' => 'Domain age cant be found.'
        ], 404);

    }

    // kill handler
    die;

}

Original DomainAge.lib.php does not work in latest php.

See updated gist link below to work with php-7...

https://gist.github.com/joshmoto/9ee439f6a7046f449b49b51e9cf6275f

joshmoto
  • 4,472
  • 1
  • 26
  • 45
  • There was a syntax error in my `php`, i've fixed. What is the path to your `Ageclass.php` inside your theme? – joshmoto Jan 13 '21 at 16:32
  • example: wp-content/foldername/foldertool/ –  Jan 13 '21 at 16:37
  • I've also fixed the js – joshmoto Jan 13 '21 at 16:37
  • You need to put the `Ageclass.php` class inside your theme `wp-content/themes/yourtheme/foldername/foldertool/` and you will see i've updated the path to the theme directory. – joshmoto Jan 13 '21 at 16:39
  • Updated JS again – joshmoto Jan 13 '21 at 16:40
  • Ok, now, PHP work, thanks. Only error on '' remain. –  Jan 13 '21 at 16:47
  • Are you placing this html inside your `` in `header.php`? Make sure it is before ``; – joshmoto Jan 13 '21 at 16:48
  • It dynamically loads in the page head but I can't touch the theme files. –  Jan 13 '21 at 16:50
  • How are you dynamically placing this in your ``, can you not edit the `header.php`? Can you send me a screenshot of you `` outputted code. – joshmoto Jan 13 '21 at 16:51
  • Can you use `=` short code php, do you know what php your are running? Shorthand php only works in in 5.4+. I've updated code to old `echo` method. – joshmoto Jan 13 '21 at 17:00
  • It is loaded via HEADER & FOOTER plugin –  Jan 13 '21 at 17:02
  • You can edit `functions.php` but your can't edit the `header.php`? Not sure wether the PHP will work in your plugin. Plus we need to add this inside to ``, not necessarily the header. – joshmoto Jan 13 '21 at 17:03
  • Latest WordPress and PHP 7.3 –  Jan 13 '21 at 17:04
  • Exactly. Theme files cannot be touched. We only work on a child theme. –  Jan 13 '21 at 17:05
  • In your header and footer plugin, can you see if any php is being used currently? We need to ideally run this code to get the current admin ajax url. `` – joshmoto Jan 13 '21 at 17:06
  • No, nothing is used in that plugin especially on this page which is still in testing. –  Jan 13 '21 at 17:08
  • OK i got another idea, i'm going to update answer – joshmoto Jan 13 '21 at 17:09
  • I've updated the `JS` and added a `admin_ajax_url` constant variable manually here. This might work but i'm not sure. – joshmoto Jan 13 '21 at 17:12
  • Ok and then I remove that script from the HEAD? –  Jan 13 '21 at 17:14
  • Yes, don't use inline – joshmoto Jan 13 '21 at 17:15
  • Perfect, no mistakes. If I click on the GET DATA button, now, the console reports me "{success: true, date: {…}}" Now you have to insert the success and error functions that I used and have everything printed in the RESULT div. –  Jan 13 '21 at 17:18
  • My `handle_form_submission` php is just an example, you will need to handle your submission entry data and use `wp_send_json_success` to send your response as an `object` back too your `success` ajax response. And if your handling error then use `wp_send_json_error` to send a relevant error message to your `error` ajax response. Don't send both `wp_send_json_success` and `wp_send_json_error` like in my example, make sure you handle your submission and then send the relevant response. – joshmoto Jan 13 '21 at 17:23
  • Thanks for your help but as I said I'm not a programmer and I don't understand anything you said now. –  Jan 13 '21 at 17:25
  • I thought I could solve the problem here but, I really don't understand anything. I will look for a freelancer who understands something and who is willing to fix this and develop other simple tools like this. –  Jan 13 '21 at 17:27
  • Lol, i've update php example so you can see what I mean, this php is not valid but these `wp_send_json` functions will send data back to your ajax resonses as object data, not strings. But yeah this kind of stuff is a little advanced if you are not a programmer. – joshmoto Jan 13 '21 at 17:28
  • Ok i drop you an e-mail –  Jan 13 '21 at 17:37