ruzD
ruzD

Reputation: 555

jquery Post value to PHP webpage

I have made a web page with a dropdown menu. The idea is when we click any option of the dropdown menu it open produccion.php with a POST parameter 'edicion'. This parameter I use to do a query in a Database.

At moment the problem is that it's open the produccion.php but I think that doesn't POST the value of the variable

Jquery code:

    $('#drEdicion a').click(function(event){
        alert($(this).text());

        var ed = $(this).text();

        $.ajax({  
            url:"produccio.php",  
            type:"POST",  
            data:{edicion: ed},  
            dataType:"text",  
            success:function(data){  
                window.location.href = 'produccio.php'
            }  
        });     

    });

Is it possible that the problem is when it's send via ajax?

Thanks in advance.

Upvotes: 0

Views: 550

Answers (2)

Adrian Wragg
Adrian Wragg

Reputation: 7401

Your code is currently POSTing the content of the hyperlink over to produccio.php via AJAX. When that call completes it is then redirecting the user to the same page but without the POSTed value. Based on your comment:

I want to open produccion.php after selection option in dropdown button. With this option I do a query

it appears you actually want to open produccio.php with the POSTed value in the browser.

By far the easiest solution to the problem would be to alter the PHP code to accept the value of edicion from $_GET["edicion"] instead, and output your hyperlink as:

<a href="produccio.php?edicion=...">...</a>

This will also provide a better experience for users, especially if they have issues with JavaScript (or, for example, happen to be a search engine). However, if you're set on only using $_POST, the following code may - I've not tested this myself - allow this:

$('#drEdicion a').click(function(event){
    event.preventDefault();

    var ed = $(this).text();
    $('<form action="produccio.php" method="POST">' + 
          '<input type="hidden" name="edicion" value="' + ed + '" />' +
          '</form>').appendTo('body').submit();
});

(with credit to the top answer on Dynamically create and submit form)

Upvotes: 1

Razib Al Mamun
Razib Al Mamun

Reputation: 2713

Follow bellow code :

$('#drEdicion a').click(function(event){
        //alert($(this).text());
        event.preventDefault();
        var ed = $(this).text();

        $.ajax({  
            url:"produccio.php",  
            type:"POST",  
            data:{edicion: ed},  
            dataType:"html",  
            success:function(data){  
                //#dropdown-menu id show all produccio.php data
                $("#dropdown-menu").html(data);
            }  
        });     

});

produccio.php

<?php
   $edicion = $_POST['edicion'];
   //now you can able to access edicion post param
?>

HTML like this :

<div id="dropdown-menu"></div>

Upvotes: 0

Related Questions