I have this method that retrieves a list of dates from my database.
function getdate($id) {
$select = $this->db->query("select * from dates where user_id= '$id' ");
$row = $select->fetchAll(PDO::FETCH_COLUMN);
return $row;
}
And I have a model file "load calendar.php" which calls the method getdate:
$dates = $user->getdate($id);
echo $dates;
I want to be able to store the array $dates in an array my js file:
$(document).ready(function() {
var dbdates = new Array();
$.ajax({
type: 'POST',
url: 'loadcalendar.php',
data: { dates:dates },
success: function(response) {
dbdates = response;
alert(dbdates);
}
});
However, when I alert dbdates, nothing comes out. My 'getdate' method works. I only need help with the Ajax call. Thank you in advance!
Analyze these statements here,
$dates = $user->getdate($id);
echo $dates;
getdate() method actually returns an array, and what you're trying to do with echo $dates; is, you're trying to convert an array to a string, which won't work.
Instead, json_encode the array and echo it, like this:
$dates = $user->getdate($id);
echo json_encode($dates);
Also, add dataType: 'json' setting in your AJAX request, like this:
$(document).ready(function() {
var dbdates = new Array();
$.ajax({
type: 'POST',
url: 'loadcalendar.php',
data: { dates:dates },
dataType: 'json',
success: function(response) {
dbdates = response;
console.log(dbdates);
}
});
});
Related
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');
Having a few problems creating a products index.
It looks like you're pushing down html as well in the products.php page. Make sure the output of the php that you're retrieving from only returns JSON.
Also, check the syntax on your script:
$.get({
type: "GET",
url: "products2.php",
data: 'id=' + userid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("decription").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
document.getElementById("stock").innerHTML = data[3];
}
});
You were using $rows but attempting to access data. Adding a simple console.log(data); in the success function will dump the results to the console in chrome/firefox so you can see what is being returned. (Be sure to check the network tab as well, as it can give you some tips as to why the data isn't being properly fetched.)
I've done something similar and this worked fine for me:
<?php
$array['status'] = 0;
...
echo json_encode($array);
Populate the array with whatever you need.
And then:
$.ajax({
type: "type",
url: "url",
data: {
data: data
},
success: function (data) {
console.log(data.status);
}
});
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I make an AJAX request:
function getdbsite(wantedid) {
alert(wantedid);
$.ajax({
url: 'public/xml/xml_getdbsite.php',
dataType: 'text',
data: {"wantedid": wantedid},
type: 'POST',
success: function (data) {
resultObj = eval(data);
site=resultObj[0];
// alert(site->language); }These cause errors
// alert(site->name); }
reply=resultObj[1];
}
});
}
The server side PHP:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once '../../includes/initialize.php';
header("Content-Type: application/json");
$id=$_POST['wantedid'];
$site = Website::find_by_id($id);
if($site){
$arr[0] = $site;
$arr[1] = "OK";
}else {
$arr[0] = "$id";
$arr[1] = "Failed";
}
$arr = json_encode($arr);
echo("$arr");
AJAX responce: [{"id":"19","idlanguage":"1","name":"QI"},"OK"]
But I am unable to access the db row.
I have searched and found:
Parse PHP array of objects with jQuery Ajax
but do not understand the answers, their examples only have 1 field. Please help.
I strongly suggest don't use eval() function for this.
Instead, explicitly set that you are going to receive JSON from the server:
dataType: 'JSON',
Example:
PHP:
if($site){
$arr['data'] = $site;
$arr['message'] = "OK";
}else {
$arr['data'] = $id;
$arr['message'] = "Failed";
}
echo json_encode($arr);
exit;
JS:
$.ajax({
url: 'public/xml/xml_getdbsite.php',
dataType: 'JSON',
data: {"wantedid": wantedid},
type: 'POST',
success: function(response) {
// use dot notation not -> arrow notation
var data = response.data;
var message = response.message;
alert(message);
alert(data.id);
alert(data.idlanguage);
}
});
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"
I'm trying to parse a information that gets returned from a DB and encoded into a JSON object.
this is the code that retrieves the information:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}
and this id how I'm trying to parse the information:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var obj = $.parseJSON(response);
$.each(obj, function(){
alert(this['code'] + ", " + this['standard_one_id'])
});
}
});
I've tried a number of different ways to do this, but I only ever get [object][object] as a response.
this is the response:
http://i.imgur.com/E5Hux.png
Use
console.log(this['code'] , this['standard_one_id'])
Instead of
alert(this['code'] + ", " + this['standard_one_id'])
Add dataType attribute to your AJAX call.
$.ajax ({
type: "POST",
dataType: "JSON",
url: "lib/search/search.standards_one.php",
async: "false",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var obj = $.parseJSON(response);
$.each(obj, function(){
alert(this['code'] + ", " + this['standard_one_id'])
});
}
});