Accessing an array in PHP from Javascript/jQuery - php

I have all my html, php and javascript/jquery code in a single file. I have an array $arr in php (json_encode($arr)) which when printed shows the data in php. How do I access it in javascript. The array contains all the rows from the resultset of a query execution. I have looked up jsonParse and var json_obj = but have not got any results. I am newbie so any help is appreciated. My code so far in php :
$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0)
{
$resultarray = array();
while($row_again = $result_again->fetch_assoc())
{
$resultarray[] = $row_again;
}
}
echo json_encode($resultarray);
My code in the .js file :
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(data) {
alert("Result: " + data);
}
});
});

Step 1:
Render json_encode($arr) into javascript string variable.
var json = '<?= json_encode($arr) ?>';
Step 2:
Parse JSON string into javascript object.
var obj = JSON.parse(json);
Or if you're using jQuery:
var obj = jQuery.parseJSON(json);
You now have a javascript object which you can access properties of like below :)
alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column
Edit -- in reply to slugspeeds update
Ok, so looks like you're doing this the AJAX way using jQuery. Since your PHP script is using json_encode() the jQuery $.ajax() should return an javascript array object.
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(arr) {
console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)
$.each(arr, function( index, row ) { // loop through our array with jQuery
console.log('array row #'+index, row); // show the array row we are up to
// you can do what you want with 'row' here
});
}
});
});
For reference:
https://developer.chrome.com/devtools/docs/console

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;

Ajax call json undefined Object : object

the json value keeps returning unidentified or it doesnt display at all
PHP CODE
$index=0;
while($row = $result->fetch_array()){
$index++;
$data=array(
array(
$index=>$row['menuName']
)
);
}
echo json_encode($data);
}
JQUERY AJAX
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
$('.navbar ul').append('<li>'+data[0]+'</li>');
}
}); //ajax request
});
</script>
The json is fine it displays in the right format. When i change my jquery to data[0] it displays object Object and if i do data[1 or higher] it gives me undefined. I dont know what im doing wrong i even tried it do this: data[0].1 and it displays nothing.
Any help will be appreciated.
First thing to do is to fix the PHP script part which responds to the request.
Create a valid JSON string response. The simpliest way is first to create a container (an array).
Then second is the to continually push fetched rows in there. Then finally use json_encode in the end.
Don't encode while inside the loop:
Simple example:
// initialize container
$data = array();
// the pushing of rows
while($row = $result->fetch_array()) {
$data[] = $row; // push the whole row
}
// finally, echo it to into a JSON string
echo json_encode($data);
// don't put me inside the WHILE
PHP Note: If this is mysqli, I'd suggest use the ->fetch_assoc() instead or just simply ->fetch_array(MYSQLI_ASSOC) flag.
In your AJAX script, just handle the response as you normally would:
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
// every each row, create an LI element with an anchor
$.each(data, function(index, element){
$('.navbar ul').append('<li>'+element.menuName+'</li>');
// just use the column names as the properties in your data response that came from PHP
});
}
});
});
</script>
If this runs, this should yield something into a markup like this:
<li>
Table1
</li>
<li>
Table2
</li>
<li>
Table4
</li>

how do I get my ajax data into a php array?

I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.

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

Categories