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
})
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;
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));
}
});
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()
This question already has answers here:
Ajax - How to use a returned array in a success function
(4 answers)
Closed 6 years ago.
I have a jquery ajax request like;
$.ajax({
type: 'POST',
url: 'processor.php',
data: 'data1=testdata1&data2=testdata2&data3=testdata3',
cache: false,
success: function(result) {
if(result){
alert(result);
}else{
alert("error");
}
}
});
The handler processor.php is set to return an array like;
$array = array("a","b","c","d");
echo $array;
I want to do action in client side based on this. Say if array[0] is 'b', I want to alert "hi". Again if array[2] is 'x', I want to alert "hello", and so on. How can I filter array elements in order to grab their data?
You will have to return the array encoded in the json form like following
$array = array("a","b","c","d");
echo json_encode($array);
then you can access it in javascript converting it back to an array/object like
var result = eval(retuned_value);
You can also navigate through all array elements using a for loop
for (var index in result){
// you can show both index and value to know how the array is indexed in javascript (but it should be the same way it was in the php script)
alert("index:" + index + "\n value" + result[index]);
}
in your code it should look something like:
PHP Code:
$array = array("a","b","c","d");
echo json_encode( $array );
jQuery script
$.ajax({
type: 'POST',
url: 'processor.php',
data: 'data1=testdata1&data2=testdata2&data3=testdata3',
cache: false,
success: function(result) {
if(result){
resultObj = eval (result);
alert( resultObj );
}else{
alert("error");
}
}
});
Return JSON from php
http://php.net/manual/en/function.json-encode.php
and in javascript create an object from the json string, you can do this with using getJSON instead of ajax
http://api.jquery.com/jQuery.getJSON/
Make sure your php sets the right response header:
header ("content-type: application/json; charset=utf-8");
I find the best way to return an array from php to Ajax (jscript):
on the php side: echo json_encode($myArray);
on the javascript side (e.g. myAjax.responseText)
replyVal = JSON.parse(myAjax.responseText);
To send arrays TO php from javascript, use the matching JSON.stringify() to send
and php json_decode() to receive
In your PHP code encode the array as JSON object
echo json_encode($array);
Then you need to convert the JSON object into a Javascript/jQuery-compatible object. Afterwards you can convert back to an array
$.ajax({
success: function(result) {
jq_json_obj = $.parseJSON(result); //Convert the JSON object to jQuery-compatible
if(typeof jq_json_obj == 'object'){ //Test if variable is a [JSON] object
jq_obj = eval (jq_json_obj);
//Convert back to an array
jq_array = [];
for(elem in jq_obj){
jq_array.push(jq_obj[elem]);
}
console.log(jq_array);
}else{
console.log("Error occurred!");
}
}
});
$.ajax({
type: 'POST',
url: 'processor.php',//please return in json
dataType : 'json',//to get data in json
data: 'data1=testdata1&data2=testdata2&data3=testdata3',
cache: false,
success: function(result) {
if(result.array.length > 0){
for(var i=0;i<result.array.length;i++){
if(result.array.[i]== 'a'){
//do somthing..
//here, you can use switch case too...
}
}
}
}
});
i got an ajax function that calls a php who returns an array:
<?php
$testing = array("one","two","three", "four");
echo json_encode($testing);
?>
i call it with this ajax call;
$.ajax({
url:"ajax_response.php",
type:"POST",
success:function(msg)
{
var array = msg;
var test = array[2];
alert(test);
}
});
the problem is that i want to get array[1] as "one" and im geting 1 character on every array position ex: array[0] = "o", array[1] = "n", array[2] = "e". Its like the json encode or semething is spliting my array variables into characters.
Any help ??
Thanks in advance
You have to parse your answer. Easiest way would be to put a dataType to your AJAX call:
$.ajax({
url: "ajax_response.php",
dataType: 'json', // add the dataType
type: "POST",
success: function(msg) {
var array = msg;
var test = array[2];
alert(test);
}
});
Or you can parse it "by hand". This is sometimes necessary:
success: function(msg) {
var array = JSON.parse(msg); // or parse it manually
var test = array[2];
alert(test);
}
your response is in string format try this at your success function
success:function(msg)
{
var array ;
eval('array ='+msg );
var test = array[2];
alert(test);
}