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);
}
Related
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
})
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;
I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in 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));
}
});
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()