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"
Related
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>';
I try to get array from sql server using php , and parsing these array to javascript using ajax.
However , I have tried many solution by google , I can't get the array.
This is my php code:
<?php
include 'Connect.php';
$Store_int = $_GET['num'];
$sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;
mysqli_select_db($link, "web");
$link->set_charset("utf8");
$result = mysqli_query($link, $sql);
$arr = array();
while ($row = mysqli_fetch_object($result)) {
$p = (string)$row->Name;
$arr[] = $p;
}
//print_r($arr);
$jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo $jsonArr;
mysqli_free_result($result);
mysqli_close($link);
?>
Array in php will encode and display:
["pen","pencil","apple","cat","dog"]
and the .js file
function getArr(store_int) {
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function (data) {
alert(num);
jsArray = JSON.parse(data.jsonArr);
}, error: function (data) {
alert("123");
}
});
//alert(jsArray.length);
return jsArray;
}
In .js , I will always get empty response(undefined) from php.
Because the ajax will answer "error" function..., and the error status is 200.
Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. and You don't need JSON.parse() as you have defined dataType as json in your ajax call. Pass a function to your getArr() function and use your data in that function.
function getArr(store_int, outputFn){ // what do you use store_int for?
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function(data) {
outputFn(data)
},error: function(data){
alert("123");
}
});
}
Then use it like
getArr('5', function (data) {
console.log(data)
})
Console output
Your problem lies here. You are attempting to access data.jsonArr which is always undefined. The JSON data sent is actually embodied by data variable.
success: function(data) {
alert(num);
jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}
NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. Putting this at the top of your PHP script should solve your problem.
<?php
header('Content-Type: application/json');
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")
})
})
I am passing through The continent to the PHP file from a js file. Basically I need to insert the data to the database (put the continent in) and get the ID of it, but no matter what I do, it returns either an empty string or a 500 Internal Service Error.
Here is the PHP Code:
$continent = $_POST['continent'];
$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";
if(!$result = mysqli_query($con, $sql)){
die('There was an error running the query [' . $db->error . ']');
}
$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;
Here is the JS Code:
$.ajax({
url: 'process.php?section=continent',
type: 'POST',
data: 'continent='+key,
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
The Key that is passed through would be something like Africa.
I have tried the following in the php file:
return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);
I have struggled for around 2 hours now. I cannot seem to find the error.
Note
Please note that the information is being inserted to the database just fine, just that I cannot get the ID.
In ajax you need to print/echo output for return data rather return statement so try to replace
return $result2->num_rows;
to
echo $result2->num_rows;
also you can send your query string like:-
$.ajax({
url: 'process.php',
type: 'POST',
data: {'section':'continent','continent':key},
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
Then check your post data by echo if correct something wrong with query executing can't find $con and $db defined on posted code
You are returning but you are not in a function, so try echoing instead (echo mysqli_insert_id($conn);)
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"