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);
});
}
Related
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
I am having a problem in fetching data from database using jQuery AJAX as json datatype I have read and tried JSON.parse in jQuery but it did not work. All I am returning in console.log(data) is object and the data from database in object but I don't know how to show it on view. Any suggestions please.
Here is my Controller.
function fetch(){
$data_fetch = array(
'id' => $this->input->post('txt_id')
);
$data['records'] = $this->form_model->fetch_model($data_fetch);
$results = json_encode($data);
$this->output->set_content_type('application/json');
$this->output->set_output($results);
}
Here is my jQuery AJAX
$.ajax({
type : 'POST',
url : base_url + 'index.php/form_controller/fetch',
data : {txt_id : id },
dataType : 'JSON',
success : function(data){
// var re = JSON.parse(data);
// var re = $.parseJSON(data);
// var data = JSON.parse(data);
alert(data.name);
console.log(data);
},
error : function(data){
console.log('erronr in fetch');
}
});
The data.name is showing undefined in alert. Any help will be appreciated.
You don't need to use JSON.parse the variable data is already a JSON, so just use it as a you would with any other JSON.
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.
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);
}
});
}