how to convert this string to an array? - javascript

I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.
Here where I create the array in my JS file.
function get_array(){
var datos = []; // Array
$("#tbl_esctructura tbody > tr").each(function() {
var item = $(this).find('td:eq(1)').text();
var cantidad = $(this).find('td:eq(4)').text();
datos.push({
"item": item,
"cantidad": cantidad
});
});
datos = JSON.stringify(datos);
$.ajax({
data: {
'datos': datos
},
url: "<?php echo base_url() ?>Controller/data_from_array",
type: 'POST',
dataType : "json",
success: function(response) {
}
});
}
the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]
Now my controller PHP
public function data_from_array(){
$data = $this->input->post('datos', TRUE);
$items = explode(',', $data);
var_dump($items);
foreach ($items as $row) {
echo $row->item.'<br>';
}
}
and the var_dump($items) this is the result
array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
}
And in this echo I get this error Message: Trying to get property 'item' of non-object
And I don't know what I'm doing wrong

Looks like a standard JSON.
Be sure to add true to json_decode function (second parameter) to return array instead of object.
$result = json_decode($data, true);
Have a look at JSON as this is a, nowadays, standard of data interchange for web and mobile apps and learn more about the function:
https://www.php.net/manual/en/function.json-decode.php
also look at its counterpart that will encode your arrays into JSON format:
https://www.php.net/manual/en/function.json-encode.php

You can use this code as the explode return array, not an object.
public function data_from_array(){
$data = $this->input->post('datos', TRUE);
$items = explode(',', $data);
var_dump($items);
foreach ($items as $row) {
echo $row["item"].'<br>';
}

there are two scenarios:
if you want to parse JSON object, then
$items = json_decode($data); // instead of $items = explode(',', $data);
if you want to treat data as a strings then
echo $row[0].'<br>'; // instead of echo $row->item.'<br>';

Related

Notice Array to string conversion in

Ran into an issue with simply querying and returning the suggestID value.
I keep getting Array to string conversion, so i'm a bit lost. I'm
Javascript
$('#autocomplete').on('typeahead:selected', function (e, data) {
console.log(data);
var dataID = data;
$.ajax({
type: "POST",
url: "get.php",
data: $.param({itemID: dataID }),
success: function(data) {
console.log(data)
}
});
})
Get PHP FILE
<?php
require 'db.php';
if(isset($_POST['itemID'])) {
$db = new DbConnect;
$conn = $db->connect();
$str = $_POST['itemID'];
$stmt = $conn->prepare("SELECT * FROM mytable WHERE id = '$str'");
$stmt->execute();
$result= $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
?>
The itemID parameter is being treated as an array by PHP:
$str = $_POST['itemID'];
If you were to var_dump that you might see that $str is an array.
When the data passed to ajax is an object and one of the property values is an array, param will serialize it using the array bracket syntax, which PHP automatically treats as an array. For example:
$.param({key: [1, 2, 3]}); // "key[]=1&key[]=2&key[]=3"

how to send this data from local storage to php online using jquery

This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.

ForEach Array Javascript

I have an array in PHP and I would like to loop through it.
Unfortunately, the array gives back this in JavaScript:
Array
(
[data] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
[0] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
)
And not:
var myvar = [10, 11, 12, ...];
So I cannot loop through it. Any suggestions?
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
print_r($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})
That kind of output is indeed what you get with print_r. Instead use json_encode as follows:
echo json_encode($r[0]);
Then in JavaScript indicate that your are expecting JSON:
$.ajax({
type:"POST",
url:"getSortable.php",
dataType: "json" // <!-- add this
}).done( // ...etc
As $r[0] (in PHP) is a plain string, you'll need to split it into an array, either in PHP, or in JavaScript. In PHP that could be done with explode:
echo json_encode(explode(",", $r[0]));
Or with JavaScript (but then use the first PHP version) you can use split:
var sortedList = list.split(',');
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
echo json_encode($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})

AJAX : Getting two different JSON variable from php using ajax

I am need to directly get the variable from the response.php which contains the needed value. How can I the filter that JSON variable separately? Or if i merge both array into 1 JSON call then how do i get the different value
AJAX
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
var rankings = data;
//get the first json
//get the sencod json
}
});
}
getMaleRanking();
My php
echo json_encode(resultMergeMale, JSON_NUMERIC_CHECK);
echo json_encode(resultMergeFem, JSON_NUMERIC_CHECK);
You have to give response in json format for fetching valued in multiple paramater. Your php code should be
$response=array('mr'=>'','mf'=>'');
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
$response['mr'] . =$firstval;
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
$response['mf'] .= $secondval ;
}
}
echo json_encode($response);
die();
You have to pass dataType:'json', so Jquery automatically convert JSON string into JSON object and you can access by its property. Your Ajax code should be
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
dataType:'json',
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
alert(data.mr);
alert(data.mf);
}
});
}
getMaleRanking();
Comma delimit the values, like this
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
}
}
echo $firstval.",".$secondval
And then in your Ajax call,
success:function(data){
var rankings = data.split(",");
var firstval = rankings[0];
var secondval = rankings[1];
//your logic here
}

passing array from javascript to php

I am trying to pass an array() on PHP from JavaScript but PHP receives nothing. It always sets $str to "". Why?
JavaScript
var ArrayPassedID = [];
function pass(){
$.ajax({
url: 'http://mysite/index2.php?task=getPassed',
type:'get',
dataType:'json',
data: {id: JSON.stringify(ArrayPassedID)},
async: false,
success: function(response){
ArrayPassedID.push(response.id);
}
....
PHP
$str = "";
if(!empty($_POST["id"])){
$id = $_POST["id"];
$id = json_decode($id,true);
$str = implode(",",$id);
}
$data = query(SELECT id, response FROM `conversation` WHERE id not in ('".$str ."'));
$values = array();
$values['id'] = $data['id'];
$values['response'] = $data['response'];
return json_encode($values);
From Javascript, you send data with GET method of HTTP protocol.
From PHP, you retrieve data from global $_POST, which correspond to POST method.
Use same method in the two ways.
in ajax (js) :
type:"POST"

Categories

Resources