Ajax call json undefined Object : object - php

the json value keeps returning unidentified or it doesnt display at all
PHP CODE
$index=0;
while($row = $result->fetch_array()){
$index++;
$data=array(
array(
$index=>$row['menuName']
)
);
}
echo json_encode($data);
}
JQUERY AJAX
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
$('.navbar ul').append('<li>'+data[0]+'</li>');
}
}); //ajax request
});
</script>
The json is fine it displays in the right format. When i change my jquery to data[0] it displays object Object and if i do data[1 or higher] it gives me undefined. I dont know what im doing wrong i even tried it do this: data[0].1 and it displays nothing.
Any help will be appreciated.

First thing to do is to fix the PHP script part which responds to the request.
Create a valid JSON string response. The simpliest way is first to create a container (an array).
Then second is the to continually push fetched rows in there. Then finally use json_encode in the end.
Don't encode while inside the loop:
Simple example:
// initialize container
$data = array();
// the pushing of rows
while($row = $result->fetch_array()) {
$data[] = $row; // push the whole row
}
// finally, echo it to into a JSON string
echo json_encode($data);
// don't put me inside the WHILE
PHP Note: If this is mysqli, I'd suggest use the ->fetch_assoc() instead or just simply ->fetch_array(MYSQLI_ASSOC) flag.
In your AJAX script, just handle the response as you normally would:
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
// every each row, create an LI element with an anchor
$.each(data, function(index, element){
$('.navbar ul').append('<li>'+element.menuName+'</li>');
// just use the column names as the properties in your data response that came from PHP
});
}
});
});
</script>
If this runs, this should yield something into a markup like this:
<li>
Table1
</li>
<li>
Table2
</li>
<li>
Table4
</li>

Related

How to access members of associative array from AJAX Response

I have a shorthand ajax call that triggers on a selection box change.
<script type'text/javascript'>
$('#selection_project').change(function(event) {
$.post('info.php', { selected: $('#selection_project option:selected').val()},
function(data) {
$('#CTN').html(data);
}
);
});
</script>
It works, but the response from the server is this:
if (isset($_POST['selected']))
$selected = $_POST['selected'];
$results['selected'] = $selected;
$response = json_encode($results);
echo $response;
$results is an associative array with many values from a SQL query.
My question is how do I access any particular element?
I've tried things like
data.selected
or,
data['selected']
I also understand that somewhere in the .post method there should be a statement defining the alternative dataType, such as
'json',
or a
datatype: 'json',
but after lots of searching, not a single example I could find could provide the actual syntax of using alternative dataTypes in the .post method.
I would have just used the .ajax method but after pulling my hair out I cannot figure out why that one isn't working, and .post was, so I just stuck with it.
If someone could give me a little push in the right direction I would appreciate it so much!!
EDIT: Here is my .ajax attempt, can't figure out why it's not working. Maybe i've been staring at it too long.
<script type'text/javascript'>
$('#selection_project').change(function(event) {
$.ajax({
type: 'POST',
url : 'pvnresult.php',
data: { selected: $('#selection_project option:selected').val()},
dataType: 'json',
success: function(data){
$('#CTN').html(data);
}
});
});
</script>
Try to log what exactly returned from info.php. Possible there are no data at all&
$('#selection_project').change(function(event) {
$.post('info.php', {
selected: $('#selection_project option:selected').val()},
function(data) {
console.log(data);
$('#CTN').html(data);
}
);
});
--- Update. Sorry, I can't leave comments
You shold parse your json with JSON.parse before use:
$('#selection_project').change(function(event) {
$.post('info.php', {
selected: $('#selection_project option:selected').val()},
success: function(data){
var result = JSON.parse(data);
$('#CTN').html(data);
}
});
});
Point to note: In your Javascript, you were doing:
dataType: 'json',
success: function(data){
$('#CTN').html(data);
}
This implies, you expect JSON Data - not just plain HTML. Now in your to get your JSON Data as an Object in Javascript you could do:
success: function(data){
if(data){
// GET THAT selected KEY
// HOWEVER, BE AWARE THAT data.selected
// MAY CONTAIN OTHER DATA-STRUCTURES LIKE ARRAYS AND/OR OBJECTS
// IN THAT CASE, TO GET THE EXACT DATA, YOU MAY JUST DO SOMETHING LIKE:
// IF OBJECT:
// $('#CTN').html(data.selected.THE_KEY_YOU_WANT_HERE);
// OR IF ARRAY:
// $('#CTN').html(data.selected['THE_KEY_YOU_WANT_HERE']);
$('#CTN').html(data.selected);
}
}

Accessing an array in PHP from Javascript/jQuery

I have all my html, php and javascript/jquery code in a single file. I have an array $arr in php (json_encode($arr)) which when printed shows the data in php. How do I access it in javascript. The array contains all the rows from the resultset of a query execution. I have looked up jsonParse and var json_obj = but have not got any results. I am newbie so any help is appreciated. My code so far in php :
$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0)
{
$resultarray = array();
while($row_again = $result_again->fetch_assoc())
{
$resultarray[] = $row_again;
}
}
echo json_encode($resultarray);
My code in the .js file :
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(data) {
alert("Result: " + data);
}
});
});
Step 1:
Render json_encode($arr) into javascript string variable.
var json = '<?= json_encode($arr) ?>';
Step 2:
Parse JSON string into javascript object.
var obj = JSON.parse(json);
Or if you're using jQuery:
var obj = jQuery.parseJSON(json);
You now have a javascript object which you can access properties of like below :)
alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column
Edit -- in reply to slugspeeds update
Ok, so looks like you're doing this the AJAX way using jQuery. Since your PHP script is using json_encode() the jQuery $.ajax() should return an javascript array object.
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(arr) {
console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)
$.each(arr, function( index, row ) { // loop through our array with jQuery
console.log('array row #'+index, row); // show the array row we are up to
// you can do what you want with 'row' here
});
}
});
});
For reference:
https://developer.chrome.com/devtools/docs/console

jQuery AJAX refresh page content after success

I'm updating my database with jQuery .click() and then calling my AJAX; my question is once the SQL has ran what is the best way to refresh the content on the page so I'll be able to do the previous action again, currently I'm using window.location.reload(true); but I don't like that method because I don't want to have the page reloading all I want is for the content on the element I used to update it with to be to match the database field after the AJAX was successful
Here's my jQuery:
$(document).ready(function(){
$("span[class*='star']").click(function(){
var data = $(this).data('object');
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success: function(data){
if(data == false) {
window.location.reload(true);
} else {
window.location.reload(true);
}
}
});
console.log(data.art_featured);
});
});
PHP:
<section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column one">
<?php if($row['art_featured']==0){
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star"></span>
<?php
} else if($row['art_featured']==1) {
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star-color"></span>
<?php
}
?>
</div>
</div>
<?php
}
} else {
echo "FAIL";
}
?>
</section>
EDIT:
I need to update the class .star or .star-color with art_featured depending on what the value of a art_featured is at the time, basically where ever I'm echoing out art_featured I need that to reload once the Ajax is successful.
EDIT:
$("span[class*='star']").click(function(){
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success:function(art_featured){
//remember $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object')),{
art_featured: art_featured
});
}
});
console.log(data.art_featured);
});
If you can just return art_featured after the MySQL database success, it'll send it back to the ajax success function. here, we can manipulate data, however, first we should store reference to the element that was clicked on.
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
Now in our success function, instead of using data just use art_featured because that's all we are returning. Now we can update the existing data object on the target.
success:function(art_featured){
//remmeber $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object'),{
art_featured: art_featured
}));
}
The above will extend the existing data object, allowing key:value pairs to be redefined based on the object we are extending.
You should find this working as intended.
I don't fully understand your question so let's assume the content you want to change is a div with class div, and you want to replace the content with the content just sent i.e. the data. Then you would need to return the data (probably using JSON would be easiest), then your call would be
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
for(n in data){
$('.div').append('<p>'+data[n]+'</p>');
}
}
});
Note addition of dataType return as being json, then iterating over the json data by for n in data, then using n to call the data from the array. So if the third item was name then you could do something like
$('.div').append('<p>Name is '+data[3]+'</p>');
You will have to return the data from the PHP form by json encoding it which can be done with the json_encode php function. If it's cross domain you'll have to use jsonp
EDIT:
If you already know the data you want to replace before you send the form (i.e. don't need a response) then you can just put those variables into the success call back. This will wait for the ajax to return successfully, then update your div.
So you could have this
var updateText = yourDataFromForm
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
$('.div').append('<p>'+updateText+'</p>');
}
});

Posting form data with .serialize() PHP error

I'm posting form data that includes some checkboxes and other input to a PHP script with jQuery's .serialize().
post.js:
$(function(){
$("#button").click(function(){
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
success: function(data){
$.getJSON('post.php', function(data) {
$.each(data, function(key, val) {
})
})
}
})
})
})
post.php:
$tags = array();
foreach($_POST['checkboxes'] as $key => $value){
$tags[] = "$value";
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
If I point the getJSON to post.php I get a PHP warning in my error log that says "PHP Warning: Invalid argument supplied for foreach()" and this causes the data from the input form to not be properly passed (i.e. a fwrite after the foreach doesn't write anything). If I reference another file for the getJSON, say data.php, or if I don't include it at all, the post works fine. Why is this happening? I could just store the data and make a second script to return the JSON data but it would be easier to do it all in one script.
Here's the deal:
success: function(data){
In the above piece, the data you are recieving is the returned json_encoded string containing key:value pairs of $tags, as you defined.
$.getJSON('post.php', function(data) {
Now, in your getJSON request you are passing over no values, and your foreach statement expects you to post the values of checkboxes so they can be parsed, and the tags be made. I'm not really sure I understand why you would want to do this, as the success: function(data) will natively parse the JSON being returned from the server and will be ready for you.
$.each(data, function(key, val) {
If you just simply lose the $.getJSON request, and use the each function, you will be iterating over the tags that you return from the server. I believe this is the intended functionality you want.
your code is breaking when checkboxes are not posted
$tags = array();
if( array_key_exists('checkboxes', $_POST) && is_array($_POST['checkboxes']) ) {
$tags = array_values($_POST['checkboxes']);
}
$json = array(
array(
"tags" => $tags,
),
);
echo json_encode($json);
You're getting Invalid argument supplied for foreach because it expects a value in $_POST['checkboxes'] which you're not sending in your $.getJSON call.
$.getJSON sends another AJAX call, a GET request to get a JSON file. You already sent a POST request to post.php, you don't need to send another call.
Add dataType: 'json' to your 1st call, and the JSON response will be parsed for you.
$.ajax({
type: "POST",
url: "post.php",
data: $("form#input").serialize(),
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
// code here
});
}
});
you don't have to invoke "getJSON" because you already have what you want. Everything you need is in data. So your "success" callback should look something like this:
function(data){
var jsonData = $.parseJSON(data);
$.each(jsonData, function(key, val) {
})
}

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

Categories