Display data from an array - javascript

In index.php page i have a script that fetches data from demo.php and displays the result in a div.
<div class="leftbox">
<?php
echo "<div id='proddisplay'>";
echo "</div>";
?>
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'demo.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
in demo.php script i get the result from
print_r($result);
the result that i get in the div is
Array ( [0] => 1st value [1] => 2nd value [2] => 3rd value [3] => 4th value )
I wish to get individial data from this array so that i can use each data seperately and wherever i want in the index.php page, but i am not able to do so. can anyone tell how can i fetch individual values from array for index page
P.S:
i have an option to display the format in demo page in the form of result[0] and so on for every index value and call it as it is in the index page but that bounds me with the css. I wish to use any css in index page and just call the values in index page.
I tried using result[0] in index page but it displayed no result i tried assigning the values of an array to a variable and then call these variables to index page but that also didn't displayed any result

The simplest way to loop through values in an array is to use foreach.
foreach
foreach($result as $value){
print($value);
}
http://php.net/manual/en/control-structures.foreach.php
http://www.w3schools.com/php/php_looping_for.asp

Either access each value individually - for example $result[0]. Or if you want to loop over the entire array you can use foreach
Example:
foreach($result as $val){
//do something with $val
}
PHP Arrays

Simply assign values of indexes to variables like below:
$first_value = $result[0];
$second_value = $result[1];
$third_value = $result[2];
$fourth_value = $result[3];
and so on in same sequence.

As you're using Ajax to get the data, you need to pass the array back as a JSON string. Add another parameter, dataType: 'JSON' to your Ajax call, this tells jQuery you're expecting a JSON string as a response and it'll automatically convert the JSON into an array for you when passing the result to the success function.
Then in your data.php value you need to run echo json_encode($result); to pass result back to the Ajax success function as a JSON string. jQuery converts it back from a JSON string to an array for us (that's why we add the dataType). Then in your Ajax success function you console.log(resultdata.0) you'll get value1, and console.log(resultdata.1) will give you value2.

convert your array to json
echo json_encode($result);
in your script
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#first').html(returndata[0]);
$('#second').html(returndata[1]);
$('#third').html(returndata[2]);
$('#fourth').html(returndata[3]);
console.log(returndata[0]);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
first,second,third,fourth will be the id of the div or the area where you wish to display the result

Related

Passing data from javascript to PHP via POST not working

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

Getting Variables in PHP by JavaScript

I'm adding a new record in my MySql DB with javascript and I have to elaborate this function in PHP.
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
//btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];//Declare the array
var i=0;
//Put the datatable(item_details) rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
processData: false,
url:'item_action.php',
method:"POST",
data:{
//btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
....
}
error : function () {
....
}
})
});
<?php
if ($_POST['btn_action']=='add_pricelvl'){
$query="....."
//Getting variables by JavaScript
}
?>
I can't get any variable in my PHP file... how is that possible?
Trying to check any $_POST[variable] in the PHP File they are NULL... why?
Try removing processData: false,. That command is telling jQuery to not turn the object into a query string. If you want to use $_POST[] in your script, it will expect it to be sent over as a query string.
http://api.jquery.com/jQuery.ajax/
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
To get the body from a POST call you should use something like this
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, true);
Then you can manipulate $obj variable as a regular php array.

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

How to access AJAX returned data with PHP?

I hava data structure like this which is then returned to another file with AJAX:
$data = array();
$data['message'] = "You are searching: $domain!";
$data['domain:name'] = "domain.tld";
$data['domain:registrar'] = "Registrar Ltd.";
$data['domain:creation'] = "2015-26-05";
$data['domain:expiry'] = "2016-26-05";
$data['ns'] = "ns1.somedns.tld";
$data['owner']['name'] = "Owner Name";
$data['owner']['type'] = "Org";
echo json_encode($data);
That data is then append to html with AJAX like this:
$.ajax({
type: 'POST',
url: 'carnetEpp.php',
data: $(this).serialize(),
success: function (data) {
dataType: 'json',
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
Now I want to pass that returned JSON object to PHP variable, so I can easy manipulate date with PHP. How do I do that? Or is best practice to do it with JS? Basically I want to print every key:pair value, so maybe for in is good choice.
And, I am not sure, should, or must I echo data in my script so AJAX can pick it up, or can I just pass data to variable and then fetch it in AJAX?
You need to add this code in success.
var obj = jQuery.parseJSON(data);
alert(obj.message);
OR
var obj = $.parseJSON(data);
alert(obj.message);
You will get the message sent from PHP.
before sending data in php, setup header for response:
$data = [
'key' => 'value',
'key2' => 'vlue2'
];
header('Content-Type: application/json');
echo json_encode($data);
then if u use jquery, $.getJson() it really cool solution for handle input json data.

returning an ajax response

I have researched this for several days now and I just can't get anything to work. I am using php to query a MySQL database. I'm getting a response via ajax but I need to be able to use the response. For example I need to take the response multiplied by 5. I can show the response in my HTML but I can't do anything to make my script read it as a number. I've tried parseInt Number() and so on. The code as I have it returns the correct number but I can't use it. Here is my code.
$('#checkStockButton').click(function(){
$.ajax({
type: "GET",
url: "mainApple.php",
data: "",
async: false,
success: function(result) {
stockPriceApple = result;
parseInt(stockPriceApple,10)
$('#responsecontainerApple').html(stockPriceApple);
}
});
return false;
});
parseInt returns a number, so you need to do this:
stockPriceApple = parseInt(result,10);
$('#responsecontainerApple').html(stockPriceApple);
As the content of your success function
if you want to read data into your success function, you first have to do: json_encode($result) at server-side (PHP) and then decode it in your java-script success function like: var str = JSON.parse(result); alert str[0]
for example: server side php
function sendjson(){
$data=array(0=>'zero', 1=>'one');
echo json_encode($data);
}
and client side, in your ajax success function:
success: function(html){
var str = JSON.parse(html);
alert(str[0]);
}
or using associative array:
serverside php:
function sendjson(){
$data=array('firstvalueofarray'=>'zero', 'secondvalueofarray'=>'one');
echo json_encode($data);
}
and clientside:
success: function(html){
var str = JSON.parse(html);
alert(str.firstvalueofarray);
}
in both cases the alert box will display 'zero'

Categories

Resources