westernKid
westernKid

Reputation: 173

Ajax not posting variable to php file

I am trying to use a drag-and-drop function in 'index.php' and post a variable, 'element' to 'store.php', where in the final version it should update a database.

'store.php' is called and runs but the variable is not being passed. I have attached below a shortened version of 'store.php' with a trap to catch this, so in this version I get the response "Element value not set".

INDEX.PHP:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="scripts/jquery-1.3.2.min.js"></script>
<script src="scripts/jquery-ui-1.7.1.custom.min.js"></script>
<link rel="stylesheet" href="style.css">

<div class="content_box" id="content_box_drag" onMouseOver="drag();">
    Drag label
    <?php for($i=0; $i<5;$i++) {
        echo "<p class='dragelement' id='dragelement_$i'>Ferrari_$i</p>";
    } ?>
</div>

<div class="content_holder_box" id="content_box_drop">
    Drop here
    <p class="dropper"></p>
</div>

<div style="clear:both;"></div>
    <br/><br/>
<div id="search_result"></div> 

<script>
    //initialize the drag and drop functions.
   function drag(){

    $( "#content_box_drag p" ).draggable({
        appendTo: "body",
        helper: "clone",
        revert: "invalid"

     });

    $( "#content_box_drop p" ).droppable({
        activeClass: "dropper_hover",
        hoverClass: "dropper_hover",
        accept: ":not(.ui-sortable-helper)",
        drop: function( event, ui ) {
             var ele = ui.draggable.text();
                $.ajax({
                url: "store.php",
                method: "POST",
                data: "element=" + ele,
                success: function(result) {
                    alert(result);
                }
           });
        }
    });
   }
</script>

STORE.PHP (shortened):

<?php

if(isset($_POST['element'])){
    $element=$_POST['element'];
} else {
    echo "Element value not set";
    exit;
}

?>

Any ideas why the variable is not being set?

Upvotes: 0

Views: 622

Answers (1)

sdespont
sdespont

Reputation: 14025

Parameter method doesn't exist, change to type: "POST"

Set your data as JSON map, change data: "element=" + ele to data: {element : ele}

http://api.jquery.com/jQuery.ajax/ (Search type description)

$( "#content_box_drop p" ).droppable({
    activeClass: "dropper_hover",
    hoverClass: "dropper_hover",
    accept: ":not(.ui-sortable-helper)",
    drop: function( event, ui ) {
         var ele = ui.draggable.text();
            $.ajax({
            url: "store.php",
            type: "POST",
            data: {element : ele},
            success: function(result) {
                alert(result);
            }
       });
    }
});

Upvotes: 1

Related Questions