I've only every used json to fetch data to use on pages or set as variables. But now I would like to search json for a matching name then fetch its views from the json
[{"id":1,"name":"Pale","description":"This is a description","url":"http://domain.com//1/pale","views":2212,"createdBy":{"name":"Bill Lumbergh","url":"http://domain.com"},"createdOn":"2013-10-24T22:54:34.183"},
Above is a little example and using the below code only console.logs the entire json which has about 20 id's
$.getJSON( "content.php", { name: 'Pale' } ,function(data){
console.log(data);
});
$.ajax({
url: 'content.php',
dataType: "json",
success: function (data) {
$.each(data, function(k,v){
if (v.name == theme){
console.log(v.views);
}
});
}
});
The Object you put in the code is the one you are passing to the Server, not receiving. {name:'Pale'} is being sent to the server. If you want the name from the JSON file, it's like:
$.getJSON('content.php', function(data){
console.log(data.name);
});
However, if my guess is correct try the following:
$.getJSON('content.php', function(data){
var ary = data.arrayThatHoldsYourObjects, store;
$.each(ary, function(i, v){
if(v.name === 'Pale'){
store = v.views;
}
});
});
store now holds v.views.
Related
Hey guys I'm using a rating system in my project and I'm trying to filter announcers according to their level
I used ajax for that
I get my data properly in the console( Array of objects) but I'm wondering how can I loop through them and display them in my blade?
my jquery code :
$(document).ready(function()
{
$('.star-rating input[type=radio]').click(function() {
var text = $(this).val();
$.ajax({
url: 'filterAnnouncer',
type: 'GET',
data: { text, },
success: function(data)
{
console.log(data);
}
});
});
});
My Laravel Controller
public function handleFilterBagageAnnouncer(Request $request){
$data = $request->text;
$filter = BagageAnnouncement::whereHas(
'announcement.user.profile.profileSetting',
function ($q2) use ($data) {
$q2->where('level',$data);
}
)->get();
return json_decode($filter);
}
There is an issue in your controller function code here.
return json_decode($filter);
this is wrong. json_decode() is to convert(decode) json data to php objects.
but you need to convert(encode) php objects to json data. so
return json_encode($filter);
now in your ajax success this how you can loop
success: function(data){
// convert json data to js objects.
// to make your we get js objects from json data.
var dataArray = JSON.parse(data);
dataArray.forEach(announcer => {
// your code goes here.
console.log(announcer);
});
}
use like this
success: function(data){
// convert json data to js objects.
// to make your we get js objects from json data.
var dataArray = JSON.parse(data);
items.forEach(function(item){
$('selecter').append(item);
});
}
I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery
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);
}
}
I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.
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);
}
});
}