I have run into some problems in $.ajax() and $.post() calls for sending some variables at interface-end to server-end PHP for processing. Though this seems to be a trivial problem and reported heavily in forms but I tried with all the options from the last couple of days but met with no success.
我的设想如下:
I have a simple interface with a 4X4 grid drawn so that users can click on any position and a 2D coordinate value will recorded through a jquery function which is working fine. Now I need to send these two x-y variables to the PHP for storing in the DB with the click of a user button. I allow the user to click multiple times but have a submit button so that the final clicked values are only submitted. I have all the work written in a file test.php as follows:
<?php
$x = $_POST[ xval ];
$y = $_POST[ yval ];
echo "X-Value......" . "$x";
echo "Y-Value......" . "$y";
// Code to store $x and $y in database
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
var x=0;
var y=0;
$("#table").click(function(e1){
// Process x, y values from the grid..This part is working fine and tested also
})
$("#form").submit(function(event) {
//var $form = $(this);
//var url_s = $form.attr( action );
var data_s = {xval: x , yval: y };
//$.post("test.php", { xval:"x", yval: y });
$.ajax({ type: "POST", url: "test.php", data: {xval: x , yval: y }});
})
});
</script>
<div class="form">
<form name="form100" id="form">
<input type="submit" name="SubmitOption" id="button" value="Next">
</form>
</div>
I am posting the values in the same page i.e. test.php, since I want to process the values in the top-part of the PHP-code, but I am not able to retrieve the $x, $y values in the PHP-end. The I tested to post with a form as follows: ">
After testing, I found that $_POST is only able to load the form variables with method="post" action=" but never works with $.post or $.ajax calls with jQuery variables. I tried for a work around method by loading two text areas in the form from jQuery click function and then used the form POST with method="post" action=" which works since now the jQuery variables are transferred to the form variables.
How to perform a AJAX call ($.ajax or $.post) using only a form submit button and pass the jQuery variables to the server-PHP through the $_POST array since it seems that $_POST array gets loaded only with form variables from method="post" action=" and is not able to be invoked from $.post() and $.ajax() and pass the jQuery variables to the $_POST array. Another question will be how to pass jQuery variables without a form in $_POST array using only a input type="button" click (tried with $("#button").click(function()....but POST not working with $.ajax and _POST array is empty) since technically I don t need a form as I do not have any form variables ?