I am trying to send data to PHP using JQuery ajax. However, I am only able to the send the first key=value
to PHP, the second key=value
echo as blank.
For example:
functionName="+env works but not username="+username;
How can I pass multiple key value pair to PHP from JQuery AJAX?
Jquery AJAX
var envdata="functionName="+env+",username="+username;
alert(envdata);
if(action == 'R'){
$.ajax({
type: "GET",
url: 'getdata.php',
data: envdata,
success: function(response) {
$("#textarea_message").val(response);
}
getdata.php
$env = filter_input(INPUT_GET, 'functionName');
echo $env
$username = filter_input(INPUT_GET, 'username');
echo $username;
You're building your data
wrong. it's basically equivalent to a URL query string, which means you need to use &
as the separator, not a ,
:
var envdata="functionName="+env+"&username="+username;
^---note the &
commas mean nothing to PHP as far as url query arguments go, so your ,username=foo
would become part of the functionname
value.
A simple var_dump($_GET)
would show you exactly what PHP is seeing come in. Doing that should've been your first stop when you didn't get your expected data in the script.
Read about JSON
$(document).ready(function() {
$('#some_button').on('click', function() {
var checks = new Array();
$("input[name='ls_id']:checked").each(function() {checks.push($(this).val());});
$.ajax({
type: 'POST',
url: "some url",
dataType: 'json',
cache: false,
data: {checks: checks, func: 9},
success: function(data) {
}
});
});
});
getdata:
$json = json_decode($_POST['checks'], true);
print_r ($json);