简体   繁体   中英

SQL query using AJAX in Wordpress theme

I'm attempting to use AJAX to insert data into a database, but am unable to connect to the .php file on the server end. I'm thinking this is due to the fact that this is all run on Wordpress, so my normal url path to the .php file might not be correct.

Here is my setup:

Template file:

$('#newsletter-register').submit(function(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){

        if(ajaxRequest.readyState == 4){
            alert(ajaxRequest.responseText);
        }
    }

    ajaxRequest.open("GET", "register_newsletter.php", true);
    ajaxRequest.send(null);

});

'#newsletter-register' is form that the user will use to submit his/her information. The alert when the ajaxRequest is at readyState 4 is thrown correctly, but will an empty value.

My php is a simple echo returning a string to signal that the connection is correct (presently I'm just trying to see if the files are correctly calling eachother).

I'm thinking it must be the url path to register_newsletter.php as I've tried placing the code within the template file, outside, etc.

My javascript file is located in /theme/assets/js/code.js where as my template files (including the register_newsletter.php file) in /theme.

Any ideas?

I had this type of issue yesterday. In my situation the page would only be accessed from

www.site.com/aFolder/ 

The script was stored in my

'/wp-content/themes/themeName/processForm.php'

folder.

and the URL I used was:

../wp-content/themes/themeName/processForm.php

My JS was simply in the head of the main header.php file, but note that the URL I had to use was relative to the URL the page the script was accessed from. Does that shed any light on things?

EDIT:

As troubleshooting steps, try ensuring you can access your php file from it's absolute URL, and have a look in firebug to see what link is being called when you fire the ajax request to see if it matches up with what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM