Can't get values i need from json with ajax callback - php

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));
}
});

Related

take data array from jquery ajax

I'm trying to get a simple callback in a direct way
$(function(){
$("input[name='inputs_picture']").on("change", function(){
var formData = new FormData($("#frn_pic_id")[0]);
var ruta = "image-ajax.php";
$.ajax({
url: ruta,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(datos)
{
var $directions = datos;
var $prov_rut = $directions['prov_rut'];
$("#picture_product").html($prov_rut);
$("#ajax_res").attr("style", "visibility: visible");
}
});
});
});
var $directions is an array that I create in a very simple way
$src = $folder.$name;
$directions = array();
$directions["prov_rut"] = $prov_rut;
$directions["destino"] = $src;
echo $directions;
What I want to do is simply get the values of the array and use them later, I've tryed everything
Thank you in advance for taking a minute to take me out of this blocked.
Echoing an array doesn't do anything useful, it just prints the word Array. You need to use JSON.
echo json_encode($directions);
Then in the $.ajax() code, use:
dataType: 'json',
to tell jQuery to parse the JSON result. Then you'll be able to use datos.prov_rut and datos.destino in the success: function.
you can use json_encode function to encode convert your php array to json array
echo json_encode($directions);
To parse the json in ajax success you can use
var response = JSON.parse(datos);
response will be json object
so what kind of array are we talking here if its single diamention array lek [10,20,30]
then you can do
for(var i=0 ;i< datos.length; i++)
{
var val = datos[i];
}
if its array of object (json) [{id:1,nam:Rahul}] then
$(datos).each(function()
{
val = this.objectName
})

How to output json array value in ajax success?

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;

Not displaying array count

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()

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

Passing Two JavaScript Arrays to PHP

I need to get the distance between two points from JavaScript to PHP using Google Maps. Below is my function to get the distance and post no problems. Now, how can I send the arrays (i.e. volunteerDist and tvid) to another php file (i.e. distanceToDb.php) and what should be the code of my distanceToDb.php to get these data? Thanks! Actual codes is highly appreciated.
<?php
function getFDistance(lat, lng, vlat, vlng, vid) {
var eventlocation = new GLatLng(lat, lng);
var volunteerDist = new Array();
var tvid = new Array();
var volunteerlocation;
for(i=0;i<lat.length;i++) {
tvid[i] = vid[i];
volunteerlocation = new GLatLng(vlat[i], vlng[i]);
volunteerDist[i] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
}
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: function(data){
alert("Successful");
},
dataType: "json"
});
}
?>
I've passed arrays and objects using JSON in javascript, let's say through a jquery.post call:
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: successfunction,
dataType: "json"
});
Then, in the php file you just do this:
$js_data_arr = json_decode($_POST['data']);

Categories