I am sending some data with ajax, and as a response i get multidimensional array.
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
success: function(data){
imagesList = data;
console.log(imagesList);
curentImage = imagesList[0];
}
});
Response, data looks like this. This is what i get on console.log(imagesList):
I am using php, and the response is provided like this <?php echo json_encode($data) ?>
[
[1,487124,"<img src=\"http:\/\/example.com\/images\/1\/487124.jpg\" \/>","http:\/\/example.com\/photos\/salle-a-manger---mineral\/649518","Title 1"],
[2,732924,"<img src=\"http:\/\/example.com\/images\/1\/732924.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 2"],
[3,341649,"<img src=\"http:\/\/example.com\/images\/2\/341649.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 3"]
]
If i try to access the first array with imagesList[0] it only shows [
How can i access the first or second array, or values inside of them?
specify the dataType in ajax request
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
dataType:"json",
success: function(data){
$.each(data,function(key,value){
console.log('key:'+key+", value:"+value);
//do your stuff
});
}
});
Use this
var obj = $.parseJSON(data);
Related
I want to extract JSON data from laravel using JQUERY but the result is always undefined.
this is the json code I've got:
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
and this is the js code:
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
$('#result').text(data.category)
}
})
})
Since your code return JSON data is
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
The ajax success function parameter is called data and the first key in the json result is named data, to access the value of category, your code should be
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
//Call the first wrapper key first.
$('#result').text(data.data.category)
}
})
})
Use the $.parseJSON which parse the well formatted json string into js object.
Your success callback will be
success: function(data){
var obj = $.parseJSON(data);
$('#result').text(obj.data.category)
}
Make it even simpler:
jQuery('#show')
.click(function() {
jQuery
.getJSON('example.com/api/product/1')
.done(function(data) {
jQuery('#result').text(data.data.category);
}
});
In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);
The goal
Send [{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}] via $.ajax() using jQuery.
The problem
I have this:
[...]
var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: object,
success: function(response) {
console.log(response);
}
});
And, in laboratory.php:
<?php print_r($_REQUEST); ?>
And finally, the return via console is:
Array
(
[undefined] =>
)
This is what the data's variable means:
[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]
And this is what object means (by Chrome's console):
[Object, Object]
Can someone give me an idea?
have you tried using JSON.stringify:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
$.ajax({
type: "POST",
contentType: 'application/json',
url: "laboratory.php",
data: JSON.stringify(object), // using stringify
success: function(response) {
console.log(response);
}
});
Here's the problem. passing your array of objects to $.param() (which is what jQuery does internally with data: that isn't a string) results in "undefined=undefined&undefined=undefined" which is exactly what you are getting back from php. Your array simply is in a format that jQuery can't understand. Since what you actually want to send is json, don't use $.parseJSON because it'll turn your json into an array and what you really want is just a string.
//var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: data,
success: function(response) {
console.log(response);
}
});
For multiple data, getJSON is better in my opinion:
$.getJSON('laboratory.php', function(json) {
$.each(json, function(key, val) {
//Getting the value of id
val["ID"];
//Getting the value of name
val["NAME"];
//DO whatever u want.
});
});
I'm using this ajax to pass an array of strings to another page.
This is the array on nomes.php
[ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio',]
This is the code, the alert doesn't work - can anyone help?
$.ajax({
type: 'post',
url: 'nomes.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
You need to encode the PHP-array to a JSON-array.
<?php
echo (json_encode($myPhpArray));
?>
You can serialize the array into JSON using stringify to pass them through. Add this to your Ajax call:
data: JSON.stringify(arr);
Replace arr with your JavaScript array. This needs a plugin though. Have a look at this answer for more info.
Alternatively, if your array is in PHP, not in JavaScript you can echo it out directly like this:
data: <?php echo json_encode($arr) ?>,
If you're trying to pass the json to the server, you can do it like :
var strArray = ['str1', 'str2', 'str3'];
$.ajax({
type: 'post',
url: 'nomes.php',
data: {strarray: strArray},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
If you're trying to receive it, you need to set the header on php side :
header('content-type: application/json');
echo json_encode(array('str1', 'str2', 'str3'));
I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......