I have a json file like this.
{
"name" : [
"Alsa", "Alice", "Alas", "Alpha", "Beta", "Bervis", "Bankai", "Celcia", "Celsa", "Ceasar",
"Domino", "Dorito", "David", "Eurius", "Easter", "Ethium", "Fourin", "Flora", "Fifa", "Genius"
]
}
I would perform a jQuery AJAX call like this.
function method1(){
$.ajax({
url: "name_suggestion.json",
type: "GET",
dataType : "JSON",
success : function(data){
for(i in data.name){
name_array.push(data.name[i]);
}
}
});
}
function method2(){
$.post('search_name.php', {
names: JSON.stringify(name_array)
}, function(data, status){
console.log(data);
}
);
}
$.when(method1()).then(method2);
In PHP file,
<?php
$nameData = json_decode($_POST['names']);
print_r($nameData[1]);
?>
When the function is called, it shows an error saying array key is not defined.
If I pass a normal array written in JavaScript, it won’t show the error but that’s not how I want to do:)
I am just into AJAX so if there is any mistake, I would love to know!
EDIT:
Here is the final code which works(Thanks for the answer)
var name_array = [];
function method1() {
$.ajax({
url: "name_suggestion.json",
type: "GET",
dataType: "JSON",
success: function(data) {
name_array = data.name;
method2(name_array);
}
});
}
function method2(name_array) {
$.get('search_name.php', {
names: JSON.stringify(name_array)
}, function(data, status) {
console.log(data);
});
}
method1();
2
Answers
In your PHP code, you are trying to access the second element of $nameData using print_r($nameData[1]). However, json_decode with the default second parameter set to false returns an object, not an array. To access the elements, you should use the arrow (->) operator instead of square brackets.
Hope it works mate!
Picking up on the suggestion above by @Brad – the
Fetch
api offers an easy to use, powerful and reliable means of sending ajax requests. An "All-in-One" example solution using Fetch