How to select json data before loop in php - php

I echo JSON data in PHP like this.
echo json_encode($row,JSON_PRETTY_PRINT);
Then I use ajax in jquery and do for loop to loop the json data.
for(var i=0; i<data.length; i++) {
var img = data[i].url;
}
Ok, now here my problem.
I have a get_thumb(parem1, param2) php function and I want to use this function to
get the thumbnail image. How can I select the json url in php?
Like this
Edited
get_thumb($row[i]['url'], param2);

Related

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaƱa en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

Jquery JSON in PHP

How do I get all the filenames in the php file with jQuery getjson?
Json encoded data from PHP
[{"Filename":"941-2"},{"Filename":"941"}]
My code:
$.getJSON('json.php',{id: id, ajax: 'true'}, function(j){
$('#filename').append(j[0].Filename);
})
Do a simple forloop on j.
For example:
for (var i = 0; i < j.length; i++)
$('#filename').append(j[i].FileName);

using an array from PHP in a JS file

I have an array in my index.php which is created by a foreach:
foreach ($events as $eventkey =>$event)
{
echo "<li class='desktop-2 tablet-1 mobile-1'>".$event->title."<span class='eventLetter'>A</span><br/><span class='eventLocation'>".$event->city."</span></li>";
$LocationArray[]= $event->latlng;
}
json_encode($LocationArray);
Now I want to use this array, in my javascript ( which is written in a different file..). But CAN I do this? and if so, how? (I'm new to php, and I'm really bad at AJAX stuff etc.. I've been looking around here and other sites but I can't really find the solution.)
The plan is to be able to loop over the array in my javascript and place markers at a google map which I have on my site.
The simplest solution would be to insert a new script tag with a javascript variable, and then assign the php array to that variable with json_encode. JSON (JavaScript Object Notation) is a text format for data-interchange between programming languages. Because JSON is based on the JavaScript decoding is not needed on the client side.
echo '<script>var myarray = '.json_encode($LocationArray).'</script>';
You would ideally use AJAX and fetch the output of json_encode($LocationArray)...
so your last line needs to be
echo json_encode($LocationArray);
Once this is taken back by the JS function that initiated the AJAX call, you can convert it into an array and loop it around. (expecting you are using jQuery, the code would look something like this...)
$.ajax({
url: 'index.php',
success: function(response) {
var resData = $.parseJSON(response);
for (var i = 0; i < resData.length; i++)
{
alert(resData[i]);
}
}
});
The easiest way I can think of is to do an echo before you link to the JS file.
echo"<script type='text/javascript'>\n var array={";
for($i=0;$i<sizeof($array);$i++){
echo "'".$item."'";
if($i<(sizeof($array)-1)){
echo",";
}
}
echo"};\n</script>"
That has not been debugged or tested, but it should give you the idea.
You are expecting a valid json output right?
<?php
foreach ($events as $eventkey =>$event)
{
echo "<li class='desktop-2 tablet-1 mobile-1'>".$event->title."<span class='eventLetter'>A</span><br/><span class='eventLocation'>".$event->city."</span></li>";// remove this thing or maybe place it in a variable. do not echo it.
$LocationArray[]= $event->latlng;
}
echo json_encode($LocationArray);
on your script
$.ajax({
url:"",
success: function(data){
var json = jQuery.parseJSON( data );
for (var i = 0; i < json.length; i++) {
alert(json[i]);
//Do something
}
}
})

json object usage with ajax returned array

I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}

Categories