I have number of checkboxes on my page and I want to get those checkbox values in my database.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+mandate_array+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
assign_mandate.php :
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
count($mandate);exit; // it does not show the count in console
?>
When I print the array it show me the array data in console but when I try to echo the count of array it shows blank. Why ?
Thanks in advance
You have to echo the variable count value.
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
echo count($mandate);exit; // it does not show the count in console
?>
Use JSON.stringify.
You would typically convert the array to a JSON string with JSON.stringify, then make an AJAX request to the server, receive the string parameter and json_decode it to get back an array in the PHP side.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringify(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
mandate_array is Array so you wont posted array data in query string, you should use JSON.stringfy() function to convert array/JSON object into string.
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringfy(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
In PHP code
var_dump(json_decode($_POST['mandate_array']));
Use echo in front of the count()
Related
I have post the data and return the value with json_encode and get that in ajax success stage. but i can't out that data value in specific input. Here is my html input. The return value are show in console and alert box as below.
{"status":"0","data":[{"user_id":"1","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"\u304a\u306a\u307e\u30481"},{"user_id":"31","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"uchida"}]}
<input type="text" id="admin_id" class="form-control">
Here is my ajax
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
alert(result);
}
});
}
Use JSON.parse to get specific input from result
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
var obj = JSON.parse(result);
alert(obj.status);
//alert(result);
var user_id = [];
var start_time = [];
for (i = 0; i < obj.data.length; i++) {
user_id[i] = obj.data[i].user_id;
start_time[i] = obj.data[i].start_time;
}
alert(' First user '+user_id[0]+' Second User '+ user_id[1]+' First start_time '+start_time[0]+' Second start_time '+ start_time[1] );
}
});
}
Use a each loop to get the ids,result is a object that has a data array:
$.each(result.data,function(i,v){
console.log(v.user_id);
//$('.admin_id').val(v.user_id);//use val to append the value, note you have multiple ids so you need multiple inputs
});
if this doesn't work then you return a string not json so you need to convert it to json using:
var result = JSON.parse(result);
Read Following posts you will get idea about json parsing
Parse JSON from JQuery.ajax success data
how to parse json data with jquery / javascript?
and you can try looping like this
var parsedJson = $.parseJSON(json);
$(parsedJson).each(function(index, element) {
console.log(element.status);
$(element.data).each(function(k,v) {
console.log(v.user_id);
});
});
When in an AJAX callback, you can use result.data to access the array of objects being returned. You can work with these like you would any other Javascript object. You may need to deserialize the JSON first.
To accomplish what you're trying to do, the following code would do the trick, although it will only use the very first object in the array as you only have one text box.
var responseObj = JSON.parse(result);
document.getElementById('admin_id').value = responseObj.data[0].user_id;
My PHP file retrieves data from a PostgreSQL DB. I have to send them back to my jQuery function in two different arrays. One is passed by using:
echo json_encode($tb);
and works fine, in my js file i get data correctly by using:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb) {
console.log(tb);
})
console output is as expected.
The other is always a PHP array, but I have to replace chars:
str_replace(array('[', ']'), '', htmlspecialchars(json_encode($ltb), ENT_NOQUOTES));
but if I write:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb, ltb) {
console.log(tb);
console.log(ltb);
})
console.log(ltb) simply outputs
success
what I'm I getting wrong?
The second parameter of succes is the response staus. This is the reason because you get success when logging tlb.
You can only return one JSON at at time, so combine them:
echo json_encode(array("other stuff", "tb" => $tb, "tbl" => array("some" => "data")));
On JS side you can simple acces them by index or key:
tb[0]; // "other stuff"
tb.tb; // content of $tb variable
tb.tbl; // {some: "data"}
The final working code:
PHP:
$tb = array();
$ltb = array();
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
array_push($ltb, $row["x"], $row["y"]);
array_push($tb, $row["z"],$row["t"]);
}
echo json_encode(array('tb'=>$tb,'ltb'=>$ltb));
JS
$.ajax({
type: "POST",
url: './DB/lb.php',
dataType: 'json', // this is what I forgot!!!
data: {d_p: oa}, // passes variable for PHP function
success: function (response) {
console.log(response.tb+" "+ response.ltb);
$.each(response.tb, function( i, item ) {
// iterate over tb array
}
$.each(response.ltb, function( i, item ) {
// iterate over ltb array
}
});
From a datapicker i send 2 dates to a php.
I'm trying to print a group of value from json to use in a statistic.
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
console.log(JSON.stringify(obj));
}
});
Ajax callback returns into log:
[{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
I tried with:
var date = "dt"
console.log(JSON.stringify(obj.date));
var quantity = "qt"
console.log(JSON.stringify(obj.quantity));
But always returns undefined. I need to have something like this:
[0,0,0,0...]
and
[2014-06-04,2014-06-05,2014-06-06,2014-06-07...]
the author of the question clearly does not need an answer, but maybe the direction of its solution will help others.with this return, to get two arrays, as described in the requirement, it is enough to iterate through the values of objects in the array and get their values by key, decomposing them into the corresponding arrays.
/* IF Ajax callback data = [{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
*/
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
var result = [];
var result1 = [];
for(var i in obj)
{
result.push(obj[i]['qt']);
result1.push(obj[i]['dt']);
}
console.log(JSON.stringify(result));
console.log(JSON.stringify(result1));
}
});
var itemtotal = parseFloat(words[1]).toFixed(2.0)*qty;
$.ajax({
type: 'POST',
url: 'cartitem.php',
data: {itemtotal:itemtotal},
success: function(data){
alert(data);
}
I want to add the value from each AJAX call to a PHP array for later processing. How can I do that?
php :
if (isset($_POST['itemtotal']))
{
$array = [];
if (is_numeric($_POST['itemtotal'])) {
//you need to do some validation here its just an example
array_push($array, $_POST['itemtotal']);
}
}
hope it helps
I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];