Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress 301 Moved Permanently response on Jquery.post request

I've lost my hopes on finding a solution to my problem, hope someone can help me here. Here's the problem:

I have a wordpress installation with an extra table called wp_lojas (for stores). The customers can go to the site and through a form, put their address, and using the Google Maps Api, find the stores near them.

When the user submits the form, I verify their address position (latitude/longitude) and through a SQL query I seek the nearest stores.

The form sends the parameters (latitude/longitude/radius) through an ajax requisition ($.post()) to a php file that is inside my theme folder (/wp-content/themes/accessorize/dadosLojas.php) and that file builds an XML with the found stores.

Everything works fine offline, on my local machine. Online I get an answer "301 Moved Permanently". If you guys have Firebug installed and want to try, the test link is http://www.colletivo.com.br/accessorize/ and the form is on the footer of the page. If you guys want an address from Brazil, try "Rua Vicente Leporace, 1534".

If you don't understand what I tried to explain, or need more information, please let me know.

Thank you very much.

like image 598
Angelo Silva Avatar asked Nov 04 '22 10:11

Angelo Silva


1 Answers

Problem Solved with the hint Greg Pettit gave!

I wasn't aware of the possibility of Wordpress intercepting ajax requests, I thought it had something to do with htaccess redirecting the request to a non-existent url.

Knowing this, I researched how to make ajax requests using the functions of Wordpress and here is the solution:

In my theme's functions.php:

// Hooks wp_ajax that points to the function that builds the XML Stores
add_action('wp_ajax_procura_lojas','procuraLojas'); // Unlogged User
add_action('wp_ajax_nopriv_procura_lojas','procuraLojas'); // Logged User

// Function that Builds Stores XML
function procuraLojas() {

    global $wpdb;

    // Retrieve $_POST informattion coming from jQuery.post
    $lat = $_POST["latitude"];
    $lon = $_POST["longitude"];
    $raio = $_POST["raio"]; 

    // Query wp_lojas and Build XML
    $consulta = $wpdb->get_results(sprintf("SELECT * , ( 3959 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( latitude ) ) ) ) AS distancia FROM wp_lojas HAVING distancia < '%s' ORDER BY distancia",
    mysql_real_escape_string($lat),
    mysql_real_escape_string($lon),
    mysql_real_escape_string($lat),
    mysql_real_escape_string($raio)));

    $dom = new DOMDocument("1.0", "utf-8");
    $no = $dom->createElement("lojas");
    $parnode = $dom->appendChild($no);

    header("Content-type: text/xml");

    foreach ($consulta as $loja){

        $no = $dom->createElement("loja");
        $novono = $parnode->appendChild($no);

        $novono->setAttribute('nome',           $loja->nome);
        $novono->setAttribute('lat',            $loja->latitude);
        $novono->setAttribute('lon',            $loja->longitude);
        $novono->setAttribute('telefone',       $loja->telefone);
        $novono->setAttribute('email',          $loja->email);
        $novono->setAttribute('endereco',       $loja->endereco);
        $novono->setAttribute('numero',         $loja->numero);
        $novono->setAttribute('complemento',        $loja->complemento);
        $novono->setAttribute('bairro',         $loja->bairro);
        $novono->setAttribute('cidade',         $loja->cidade);
        $novono->setAttribute('estado',         $loja->estado);
        $novono->setAttribute('cep',            $loja->cep);
        $novono->setAttribute('distancia',      $loja->distancia);

    }

    // Print XML and Exit   
    echo $dom->saveXML();
    exit;

}

In the header of Wordpress I put:

<script type='text/javascript'>
/* <![CDATA[ */
var MyAjax = { ajaxurl: "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php" }; // Build the Link to admin-ajax.php / Javascript Global Variable
/* ]]> */
</script>

When the user submits the form, I send a POST ajax for the class of Wordpress that is responsible for it 'wp-admin/admin-ajax.php':

jQuery.post(
    MyAjax.ajaxurl, // Link to the file 'wp-admin/admin-ajax.php' responsible for handling ajax requisitions
    {
        action : 'procura_lojas', // Name used in the hook 'wp_ajax_procura_lojas'
        latitude : center.lat(), // Latitude Parameter
        longitude : center.lng(), // Longitude Parameter
        raio : raio // Radius Parameter
    },
    function(data) { // Callback

        // Retrieve all nodes called 'loja' and put it in the map
        var markers = data.documentElement.getElementsByTagName("loja");
        for (var i = 0; i < markers.length; i++) {
            var dados = [];
            dados["nome"] = markers[i].getAttribute('nome');
            dados["estado"] = markers[i].getAttribute('estado');
            dados["cidade"] = markers[i].getAttribute('cidade');
            dados["bairro"] = markers[i].getAttribute('bairro');
            dados["endereco"] = markers[i].getAttribute('endereco');
            dados["numero"] = markers[i].getAttribute('numero');
            dados["complemento"] = markers[i].getAttribute('complemento');
            dados["cep"] = markers[i].getAttribute('cep');
            dados["telefone"] = markers[i].getAttribute('telefone');

            var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lon')));
            var marker = createMarker(markers[i].getAttribute("name"), latlng, dados);
        }
    }
);

That's it! Thanks Greg Pettit for clarifying my ideas.

One link that helps me too was 5 tips for using ajax in wordpress

I hope this answer may help someone one day.

like image 135
Angelo Silva Avatar answered Nov 10 '22 21:11

Angelo Silva