I am struggling/trying since last 24 hours with a simple thing, which i am not able to understand why i am not able to access the PHP variable. I know am doing something wrong and i have no idea what's that..
window.alert("Variable" + <?php echo $_POST; ?> );
Its giving me output as Function Array() {[native code]}
, How can i print the values ? and i think the POST attribute is blank, Can anyone check ? Why POST variable is blank ?
I am sending data to the file via POST method as
<script type="text/javascript">
function callAjaxAddition() {
arguments0 = {
arg1: $("#exampleForm input[id='pac-input']").val(),
arg2: ("#exampleForm input[id='pac-input']").val()
};
$.ajax({
type: "POST",
url: "processAjax.php",
data: {
arguments: arguments0
},
success: function(data) {
$("#answer").html('<ul><li>' + data + '</li></ul>');
send_apptn_req();
}
});
return false;
}
</script>
and ProcessAjax.php file is
<?php $a=0;foreach($_POST['arguments'] as $v) $a= $v;echo $a;?>
Thanks in advance please..
$_POST
is an array so you should use print_r()
or var_dump()
instead of echo
:
window.alert("Variable" + <?php print_r($_POST); ?> );
If debugging the $_POST variable in Javascript is what you want to do I suggest you do this:
console.log(<?php echo json_encode($_POST); ?>);
And you'll see the content in your developer tools on your browser.
For reference you can look at the answers to this question.
EDIT:
<form method="POST">
<input type="text" name="first"/>
<input type="text" name="second" />
<input type="submit" value="submit">
</form>
<?php if (isset($_POST)): ?>
<script type="application/javascript">
console.debug(<?php echo json_encode($_POST); ?>);
</script>
<?php endif; ?>
EDIT 2: (after you updated your code)
Change the type
option in the ajax jQuery function to method
like so:
<script type="text/javascript">
function callAjaxAddition() {
arguments0 = {
arg1: $("#exampleForm input[id='pac-input']").val(),
arg2: $("#exampleForm input[id='pac-input']").val()
};
$.ajax({
method: "POST",
url: "processAjax.php",
data: {
arguments: arguments0
},
success: function(data) {
$("#answer").html('<ul><li>' + data + '</li></ul>');
send_apptn_req();
}
});
return false;
}
</script>
Also note that after the AJAX POST, your $_POST
variable will contain the data
object that you passed to the $.ajax
function and therefore what you are passing:
data: {
arguments: {
arg1: $("#exampleForm input[id='pac-input']").val(),
arg2: ("#exampleForm input[id='pac-input']").val()
}
}
will translate into:
Array (
'arguments' => Array (
'arg1': 'value of arg1'
'arg2': 'value of arg2'
)
)
So the loop in processAjax.php is quite useless since you're not looping through the inside array.
$_POST is an associative array of variables passed to the current script.
So you need to use print_r
instead of echo
.
window.alert("Variable" + <?php print_r($_POST); ?> );