Get Javascript variable inside json - php

I have a json file that has about twenty objects like this:
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "http://www.example.com/wp-content/themes/mytheme/images/profile/user1.jpg",
"contact": {
"email" : "user1#example.com"
}
}
I have a javascript code to display images/description from these objects to a page. I want this site to be uploaded in more than one place. So it doesn't make sense for me to use absolute url in this json file. I overcame the issue in js by passing a variable templateUrl from header.php file and calling it inside the javascript file.
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And in javascript:$.getJSON(templateUrl+"/scripts/file.json", function(file){....}
I want a way to pass this templateUrl variable to json file too. So I can have image path set to just images/profile/user1.jpg, and I can prepend the url to this depending on where the site is uploaded.

#json.php
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "<?= $_GET['var']; ?>/images/profile/user1.jpg",
"contact": {
"email" : "user1#example.com"
}
}
#main page
<script type="text/javascript">
var templateUrl = encodeURI("http://example.com");
$(function(){
$.getJSON(
'json.php?var=' + templateUrl,
function(data){
$.each(data, function(key, val){
console.log(key + ": " + val);
});
}
);
});
</script>
Output:
firstName: User1
lastName: UserLname
title: Human
description: Something Facinating
photoURL: http://example.com/images/profile/user1.jpg
contact: [object Object]

Related

Live search suggestions

I used ajax to create a live search connected to the database(site e-commerce). when there is a value in the input several suggestions are fetched in the screen . I want to take the id when the client click in a suggestion. The suggestions cant be clickable i dont know why!! here is my jquery code :
$('.clicked').click(function() {
console.log($("#input_value").val());
});
var x;
var value = $("#input_value").val();
$('.clicked').click(function() {
$.ajax({
type:'GET',
// // url: 'test.php?name=' + $("#testo").val(),
data: { name : value },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function()
{
window.location.href = 'un_produit.php?id=' + $("#input_value").val();
}
});
I tried to add the class to a div and it works when i click but it doesnt work with the suggestions of the live search .
Instead of using an AJAX request you could use JQUERY autocomplete.
This is an easy example on how this works, your URL source should return the data in this format:
[{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}]
I used this url as reference: https://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
$(function() {
$("#autocomplete").autocomplete({
source: [{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}], // this can be an url as well
select: function( event, ui ) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
$("#autocomplete").val(ui.item.label);
event.preventDefault();
// or get the id
$("#autocomplete").val(ui.item.value);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<input type="text" id="autocomplete">
The problem is solved, I had to add the class="clicked" into the the child element of the suggestion div and not to the div itself. thank you

How do I post multiple parameters to a URL

I need to post to this URL
https://liceoeuroamericano.territorio.la/webservices/persona.php
I need to post 2 different Parameters
method
param
method=activateUser
param
{
"auth_key": "123456",
"user": "[email]",
"active":"[0/1]"
}
string(JSON)
What I have Tried - AM I doing anything right?
<button id="activateUser">GO</button>
<script>
$('#activateUser').on('click', function(){
$.post('https://liceoeuroamericano.territorio.la/webservices/persona.php',
{
method=activateUser&params={
"auth_key": "123456",
"user": "[email]",
"active":"[0/1]"
}
string(JSON)
}, function(data){
})
});
</script>
If I've understood your requirements you need to pass method as a string, then JSON encode the params object. If so, this should work for you:
$.post('https://liceoeuroamericano.territorio.la/webservices/persona.php', {
method: 'activateUser',
params: JSON.stringify({
auth_key: "123456",
user: "[email]",
active: "[0/1]"
})
}, function(data){
console.log('request completed successfully');
})

How to prevent old data print when onclick in Json

I have simple trouble in json
This is my Json code
{ "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" }
And this it the ajax code I am getting the data
function load_res()
{
$.ajax({
url: 'data.js',
type: 'POST',
dataType: 'json',
success: function(data) {
var div_data='';
$.each(data, function(index, element) {
div_data +="<div ><a href='"+data.name+"'>"+data[index].name+"</a></div>";
});
$('#9lessonsLinks').append(div_data);
}
});
}
HTML part
<a onclick="load_res()">Button</a>
<div id="9lessonsLinks"></div>
Above code it working well and data retrieve and display. But my problem is, when I add a new row to JSON file and I click on load_res() function, it will show old printed data with new data again, multiple printing with multiple clicking. I only want to get the newly added data as last line.
please help me to resolve this. appreciate your great ideas.
Thanks!
Easy fix: change .append to .html
$('#9lessonsLinks').html(div_data);
Empty the list before adding the items to it...
$('#9lessonsLinks').empty().append(div_data);
With javascript like this:
document.getElementById("9lessonsLinks").innerHTML = div_data;

ammaps / amcharts using dataLoader and passing post

Using ammaps' dataLoader, is there a way to pass post parameters to an external file?
I'm creating a report that contains a map, which when clicked, will provide a list of news articles from a MySQL table. I'm pulling in json data using dataLoader. However, I need to be able to pass a value (reportId) to the script that generates the json file.
here's my code:
var map = AmCharts.makeChart("mapdiv", {
type: "map",
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false//,
// tried this:
//"type" : "post",
//"data" : {"reportIdFromPost" : 1}
},
. . . //the rest of the map config
And this is maparticlesfeed.json.php:
<?php include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$POST['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"_comment" : "Here, instead of hard-coding the headlines, we will iterate through $articlesList",
"areas" : [
{ "title" : "Virginia",
"id" : "US-VA",
"selectable" : true,
"numArticles" : 4,
"articles" : [
{ "headline" : "This is the first headline",
"link" : "link url"
},
{ "headline" : "This is the second headline",
"link" : "link url"
},
{ "headline" : "This is the third headline",
"link" : "link url"
},
{ "headline" : "This is the fourth headline",
"link" : "link url"
}
]
},
{ "title" : "Tennessee",
"id" : "US-TN",
"selectable" : false,
"numArticles" : 6
}
]
}
I went the jQuery route to solve this. I'd still like to know if there's a way to do this with dataLoader, but here's a workaround in case anyone else has this issue in the future:
$.ajax({
dataType: "json",
url: "maparticlesfeed.json.php",
data: { reportIdFromPost: 1 },
type: "post",
success: function(data){
console.log(data); // for debugging
makeMap(data);
},
error: function(data) {
console.log('it did not work.');
console.log(data.responseText);
}
});
function makeMap(theData) {
var map = AmCharts.makeChart("mapdiv", {
type: "map",
/* DON'T NEED THIS ANYMORE:
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false
},*/
// replace instead with this:
"dataProvider" : theData,
// ... the rest of the map config ...
}
});
And, in maparticlesfeed.json.php:
<?php
include('database-connect.php');
$con=Database::connect();
if(!empty($_POST) && isset($_POST['reportIdFromPost']) ) {
$postedReportId= $_POST['reportIdFromPost'];
}
include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedReportId ");
$query->execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"areas" : [
// Code to json_encode the results from $articlesList
]
}
It may be that you're posting json data and then not decoding it when you're trying to use the value in your php script.
Try this at the top of maparticlesfeed.json.php:
<?php
include('database-connect.php');
$postedValues = json_decode($POST['reportIdFromPost'], true);
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedValues['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
You'll also need to uncomment the two lines in the map config:
"type" : "post",
"data" : {"reportIdFromPost" : 1}
Maybe you could add the parameters in the "url" parameter of the dataloader.
"url": "urlA.do?param1=" + $('.selector').val()
and then in some trigger (ie. button click) modify the url and reload
var url = "same URL with different parameters values";
chart.dataLoader.url = url;
chart.dataLoader.loadData()

How do I iterate over a JSON array using jQuery/AJAX call from PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Loop through Json object
I have a PHP function, data.php, which fetches JSON data from an external server URL like such:
<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>
The JSON array retrieved looks like the following:
[
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
]
I'm now trying to write an AJAX call to that PHP function, iterate through the JSON array, and display it in the browser in non-JSON formatting. My AJAX code looks like the following:
$.ajax({ url: 'data.php',
type: 'POST',
dataType: 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
My issue is that code is currently displaying alert boxes that show the individual characters within the array like such: 0 --> [ , 0 --> , 0 --> { ... etc etc
Is there a problem with how I'm passing the data using json_encode(); and dataType: 'json' or does the issue resolve with how I'm iterating through the array?
Thanks.
Other responders missed the sneaky but still obvious bit, that what's coming back from the resource being polled in the PHP is probably already valid JSON, and re-encoding it is causing the browser to interpret it merely as a string. In this case, the javascript never had a chance.
Remove the json_encode() bit in the PHP and just echo what comes back, and see if that doesn't improve things.
I think your problem is the this in the second each. Try:
$.each(output, function(key, value) {
$.each(value, function(key, value){
alert(key + " --> " + value);
});
});
var jsonArray = [
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
];
$.each(jsonArray, function() {
for (var key in this) {
if (this.hasOwnProperty(key)) {
console.log(key + " -> " + this[key]);
}
}
});
take a look at this
How do I loop through or enumerate a JavaScript object?

Categories