pass php array to javascript using ajax - javascript

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

Related

Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.
The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.
The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}
The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.
The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.
Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$special_pop_sql = "
SELECT setting
FROM triggers
WHERE trigger_name = 'Special Pop'
LIMIT 1
";
if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
$special_pop_stmt->execute();
$special_pop_row = $special_pop_stmt->fetch();
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['specialPopStatus' => $special_pop_row]);
JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
obj = JSON.parse(data);
specialPopStatus = obj.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
//Catalog Requests
specialPopStatus = data.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();
the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);
Also in the javascript because you have given
datatype: 'json',
as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
specialPopStatus = data.specialPopStatus;
//status2 = specialPopStatus;
console.log(specialPopStatus + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();

Send fetchAll array via ajax

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

How to access the data in the object returned by an ajax call [duplicate]

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

Loop Through json_encoded PHP Array in JavaScript

I am having an issue with looping through an array that was passed from PHP through an Ajax request.
For some reason my javascript thinks that either every character is a part of the array or my response variable is just being passed as a string.
Here is my javascript:
<script>
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
success: function(response) {
console.log(response);
}
});
});
</script>
And here is my PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
echo json_encode($names);
?>
The response that I get looks like this:
["Test Person","Test2 Person"]
However, if I loop through this using javascript or just print out response[0] I get each character as part of the array. The first element would be [, next would be ", etc.
I would like Test Person to be one element and Test2 Person to be another.
Does anybody know what I am doing wrong? Thanks!
You need to use JSON.parse on the response. Wihtout calling that function you are just getting the index of characters in the JavaScript string.
var resultArray = JSON.parse(response);
resultArray[0]; //Should Be "test Person"
The result of the .ajax method is interpreted according to the Content-Type header of the response. If it is incorrect or not specified, the response variable will contain the raw json code as a string.
So one solution is change the PHP code by adding this line:
header("Content-Type: text/json");
Docs:
The type of pre-processing depends by default upon the Content-Type of
the response, but can be set explicitly using the dataType option. If
the dataType option is provided, the Content-Type header of the
response will be disregarded.
You can parse that text to an object, or you can let JQuery do that for you by specifying a datatype in the call. The response parameter will then hold the object instead of the raw json string.
Docs:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: "json",
success: function(response) {
console.log(response);
}
});
});
In this particular situation, you can use
success: function(response) {
response = eval(response);
console.log(response);
}
But this is bad practice.
Really the best solution here is to modify your ajax call as follow:
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: 'json',
success: function(response) {
console.log(response);
}
});
});
The specified datatype, will request the returned data to be json, and the jquery will automatically parse it to a javascript object.
You must parse JSON to array. You can do this using the following code:
var arr = $.parseJSON(response);
Now arr[0] should be "Test Person".
You can do it the hard way, or this way:
First, you need to specify the return type for AJAX.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Alternatively, you could do it this way:
$(function() {
$.getJSON("/dev/editButton/get_names.php", function(response) {
console.log(response);
});
});
For this to work, you will need to specify the HTML headers accordingly in PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
header("Content-Type: application/json");
echo json_encode($names);
exit();
?>
The exit(); is just for safety so you wouldn't ruin the valid JSON format.
JSON stands for JavaScript Object Notation, so you should not have to do anything complicated there. Here is a simple loop you could use for example:
for(var i in response) {
console.log(response[i]);
}
Alternatively, if the response is not an array but an object with properties, you could loop through the object properties by getting the right keys first:
var objKeys = Object.keys(response);
for(var i in objKeys) {
var key = objKeys[i];
console.log(response[key]);
}
I hope this helps!

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