This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've done a table of spells on phpmyadmin and i'm trying to access it via ajax request and store it entirely inside a javascript array.
Load_hero_spell.php :
<?php
include("../php/connect_database.php");
$sth = $bdd->query("SELECT * FROM spells_hero LIMIT 4");
$result = $sth->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
$php_array = array();
foreach($result as $row)
{
echo json_encode($result);
}
?>
Javacript file:
var spells_array = [];
$(document).ready(function()
{
$.ajax(
{
type: "POST",
url: "../php/load_hero_spell.php",
success: function(data)
{
spells_array = data;
alert(data);
},
error: function()
{
alert("Request failure");
}
});
alert(spells_array[1]);
});
Alert(data) display something like :
Array
(
[0] => Array
(
[nick] => Spell 1
[description] => Description 1
[icon_dir] => ../../images/icons/spells/AbolishMagic.png
[ownerID] => 1
)
[1] => Array
(
[nick] => Spell 2
[description] => description 2
[icon_dir] => ../../images/icons/spells/AbominationExplosion.png
[ownerID] => 1
)
)
but alert(spells_array); display undefined.
I'd like to be able to pass those value to an object so i can do something like
$(".Spell_icon").attr("src", Hero[1].spell[3].description);
The reason our array looks like that is due to the fact that you use print_r($php_array); in your php script. This format is something javascript simple does not understand. My advice would be to use json_encode($php_array). This way, your array will be turned into JSON, which javascript will understand.
add this line in php file instead of print_r($php_array);.
$someJSON = json_encode($php_array);
echo $someJSON;
you will get a JSON in proper format in javascript.
Related
This question already has answers here:
Pass Javascript Array -> PHP
(5 answers)
Closed last month.
This is the array of objects.
let arr=[
{
'teacherName':'skg',
'subjectName':'c',
'totalClass':4
},
{
'teacherName':'skg',
'subjectName':'php',
'totalClass':4
},
{
'teacherName':'skg',
'subjectName':'js',
'totalClass':4
},
]
This is jQuery I used to send the data.
$('#myForm').submit(function () {
console.log(arr);
console.log('submit');
$.ajax({
type: 'POST',
url: 'http://localhost/Backend/check.php',
data: {
arr: arr
},
success: function (data) {
$('#output').html(data);
}
})
})
I did not tried anything because I do not know what to do.
I'm not familiar with jquery, but normally in php you'd receive it via $_POST['arr'] and to convert json string into associative array you'd need use json_decode() function:
<?php
if (isset($_POST['arr']))
{
$data = json_decode($_POST['arr']);
}
?>
However, depending on how jquery sends data to the server, you might need change your php to something like this instead:
<?php
$data = json_decode(file_get_contents("php://input"));
if ($data)
{
//data received
}
?>
This question already has answers here:
How to pass parameters in $ajax POST?
(12 answers)
Closed 6 years ago.
im using ajax and php on my android app to query my database.
i am able to retrive all the results but dont know how to send a variable to my php so that i can use it as a custom query and retrive the results... something like this :
$id = $_POST['id'];
$sql = "SELECT * FROM mobile_app WHERE nome LIKE '{%id%}'";
but cant make my ajax post the variable and retrive the result...
this is my code :
my mobile app:
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON", // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.setItem('myData', JSON.stringify(data));
}
});
my php:
$sql = "SELECT * FROM mobile_app";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$output[] = array (
"nome" => $row['nome'],
"status" => $row['status'],
"hentrada" => $row['hentrada'],
"evento" => $row['evento']
);
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($output);
ajax() have a parameter
data:
by using this you can send as many param you want lik:
data:{
param1 : value1,
param2 : value2,
// and so on
}
In your case it is like:
data:{
id : value
}
and you can get this param in your php code like:
$id = $_POST['id'];
You need to add the following additional options to your $.ajax object:
type: 'post'
and
data: {
id: whateverVariableHasID
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I am using PHP and MySQL to swap out some content.
A click handler sends an AJAX request to the PHP script which performs a query, then encodes and prints the result as a JSON object.
All that seems to work, but I seem to be stuck on the most silly thing:
I can't work out how to actually use the result, as in set the individual values to JavaScript variables.
Edit: I added a couple more things I tried, to get a specific value to print out to the console, no luck thus far.
Edit: Found the correct syntax:
response[0].foo
javascript:
var listId = $(this).children('.hidden-id').html();
var options = new Object();
options.data = listId;
options.dataType = 'json';
options.type = 'POST';
options.success = function(response) {
console.log(response[0].foo);
};
options.url = './inc/change_list.php';
$.ajax(options);
the PHP script:
$list_id = $_POST['list_id'];
$q = "SELECT id, title, description, position FROM items WHERE list_id=$list_id ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
$result = array();
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$add_result = [
'id' => $row['id'],
'title' => $row['title'],
'description' => $row['description']
];
$result[] = $add_result;
}
$result = json_encode($result);
echo $result;
} else {
echo '{"result":"failure"}';
}
The JSON response will automatically be parsed to a Javascript object. So you can just do:
options.success = function(response) {
console.log(response.foo); // logs "bar"
// or
var foo = response.foo; // foo now holds "bar" as it's value
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to make a site that dynamically creates information using the jQuery ajax call $.getJson and the jQuery template plugin. In my index.html page, I have some of the following code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
console.log(jsonData);
});
console.log(JSON.stringify(jsonData));
// Load template from our templates folder,
// and populate the data from the post object.
$("#test").loadTemplate('#template', jsonData);
});
The ajax call executes the load.php, which has some of the following code:
//extract user ratings and respective movies
$_SESSION['username'] = $username;
$user_query = mysqli_query($link, "SELECT * FROM Client WHERE Username = '$username'");
$user_row = mysqli_fetch_array($user_query);
$user_id = $user_row['ID'];
$query = mysqli_query($link, "SELECT * FROM Ratings INNER JOIN Movie ON Ratings.Movie_ID = Movie.MovieID WHERE Client_ID = $user_id ORDER BY Rating DESC");
//adding movies to array list
$result = array();
while ($row = mysqli_fetch_array($query))
{
$movie = $row['MovieURL'];
$rating = $row['Rating'];
array_push($result, array('moviePicture' => $movie, 'movieRating' => $rating));
}
//converting array list to json and echoing it
echo json_encode($result);
I have tested the $result and it does create a json object with all of the data that it is supposed to. However, when the javascript is run in the index.html page, jsonData does not change its value from 'string'(when I check the console log). I believe the problem is with the function(data), since it does not log the console command I have in there. Any help would be appreciated.
Proper code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
$("#test").loadTemplate('#template', jsonData);
});
});
The problem with your code is, that you call loadTemplate before you got reply from load.php
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm creating a kind of API system like any social network :D
Basically, i created a php page that call with $getJSON method:
This is getuser.php
<?
include 'config.php'; connect();
$get = trim(strip_tags($_GET['id']));
$sql = "SELECT username,id,avatar FROM utenti WHERE id = $get ";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$row_set[] = $row;
}
echo json_encode($row_set);
?>
(example id=2)
[{"username":"Firefoxer","id":"2","avatar":"account\/firefoxer\/pic.jpg"}]
And .js function
$.getJSON('getuser.php', {
id: user
}, function (data) {
callback = data.avatar
});
alert(callback);
Question is... why it returns undefined object every time ? Code seems right, any ideas ?
Since you are getting array of objects, you have to mention the index for data.
ie data[0].avatar
$.getJSON( 'getuser.php',{ id: user }, function(data) {
callback = data[0].avatar
alert(callback);
});
i am not sure but try to set header as JSON object before your echo like below:
header('Content-type: application/json');
echo json_encode($row_set);
You can only access the data after the callback function has been executed:
$.getJSON( 'getuser.php',{ id: user }, function(data) {
// now it’s available
console.log(data);
});
// now it’s not
This is called asynchronous programming, do a search here on SO if this is a new concept for you.