Trying to make work this code.
Using the function to convert XML 2 JSON
Sample Here:
<?php
class XmlToJson {
public static function Parse($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$getXML = "http://api.devstate.de/json/divisas.xml";
print XmlToJson::Parse($getXML);
?>
(By the way , the original code have some issues of malformed JSON so we add strict to the function)
Seems that everything works correctly until this step.
We get a valid JSON, but when we tried to call it via jQuery or Angular we always get a UNDEFINED Data.
If I use:
$(document).ready(function() {
$.getJSON('convertedXML.php', function(json) {
console.log(json.row);
});
});
I get:
https://www.dropbox.com/s/oq5a8av2etcwvo3/Screenshot%202015-04-08%2020.02.56.png
But what about json.row.$WHATTHEHELL.Divisa
Nothing happen , nothing is given back just UNDEFINED
What do you think? , what are we doing wrong.
thanks
Inside the $.getJSON block, if you're getting the correct response, then just use $.each to iterate inside it:
$.each(json.row, function(i, e){
console.log(e['#attributes'].Divisa); // and other properties
});
Sample Demo
#Ghost the solution was fantastic! thanks.
Just , any suggestion for a simplification here:
<div>
<ul id="currency-USD">
<li class="currency-USD--name"></li>
<li class="currency-USD--buy"></li>
<li class="currency-USD--sell"></li>
</ul>
<ul id="currency-UE">
<li class="currency-UE--name"></li>
<li class="currency-UE--buy"></li>
<li class="currency-UE--sell"></li>
</ul>
<ul id="currency-CAD">
<li class="currency-CAD--name"></li>
<li class="currency-CAD--buy"></li>
<li class="currency-CAD--sell"></li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: document.URL,
type: 'POST',
dataType: 'JSON',
success: function(json) {
var group = json.row;
// alert('check the browser console');
$('.currency-USD--name').html(group[0]['#attributes'].Divisa);
$('.currency-USD--buy').html(group[0]['#attributes'].Compra);
$('.currency-USD--sell').html(group[0]['#attributes'].Venta);
$('.currency-UE--name').html(group[1]['#attributes'].Divisa);
$('.currency-UE--buy').html(group[1]['#attributes'].Compra);
$('.currency-UE--sell').html(group[1]['#attributes'].Venta);
$('.currency-CAD--name').html(group[2]['#attributes'].Divisa);
$('.currency-CAD--buy').html(group[2]['#attributes'].Compra);
$('.currency-CAD--sell').html(group[2]['#attributes'].Venta);
// console.log(group[0]['#attributes'].Divisa);
}
});
});
</script>
Related
I have a navbar defined in a html file called slick.html. I am trying to pass the id of a clicked navbar tab to the untitled.php. The untitled.php has other data in it. I am trying to isolate navbar to slick.html. I am trying to use JQuery post to transfer the data and using $_POST to access it, but I am not getting the value. I understand that it is something related to client side and server side using. The following is the code. I tried using ajax post but I didn't get any results.
slick.html(relevant parts)
<body>
<ul class="nav nav-tabs ">
<li class="active">
<a id="soilProfile" href="#tab_default_1" data-toggle="tab">
Soil Profile </a>
</li>
<li>
<a id="productivityIndex" href="#tab_default_2" data-toggle="tab">
Productivity Index </a>
</li>
<li>
<a id="Wetlands" href="#tab_default_3" data-toggle="tab">
Wetlands </a>
</li>
</ul>
//More Code
</div>
<script>
$(function () {
$('[data-toggle="popover"]').popover()
$('#soilProfile').click(function(event) {
console.log("About to post");
var data = {id : event.target.id};
console.log(data);
var request = $.ajax({
url: "untitled.php",
method: "POST",
data: { id : data },
});
console.log("AFTER POST");
});
$('#productivityIndex').click( function(event) {
var data = {id : event.target.id};
$.post( "untitled.php", data );
});
$('#wetlands').click( function(event) {
var data = {id : event.target.id};
$.post( "untitled.php", data );
});
});
</script>
</body>
untitled.php
<?php
$var = $_POST['id'];
echo var_dump($var);
// this fetches your post action
echo "this is my variable: " . $var; // this outputs the variable
?>
<html>
<body>
<object width=100% data="slick.html"></object>
<script>
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});
</script>
</body>
</html>
I don't understand why it's not working. Please inform me why or suggest me a better solution to go about this problem.
Noticed the in the ajax request you are using "untitled.php", but the page is titled "Untitled.php". Case makes a difference on Linux.
Are you sure the slick.html isn't just refreshed by the click on the anchor before the javascript is executed? Don't you need to prevent the default event?
if you say u want to pass the id that clicked.
try this and se the console.log
$('#soilProfile').click(function() {
console.log("About to post");
var data = $(this).attr("id");
console.log(data);
$.ajax({
url: "untitled.php",
type: "POST",
data: { id : data }
});
console.log("AFTER POST");
});
Updated the question as per #Jonathan Kuhn's feedback and it works like a charm
I am building a messaging system for my web application.
where the users should be able to communicate with me via messages (ajax)
I am being able to append <ul> with additional <li> from jQuery
$('#send').click(function(e){
e.preventDefault();
var reply = $('#reply').val();
var project_id = 44; // just for reference
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>messages/send",
data:{ msg:reply, project_id:project_id },
success: function (response) {
if(response=="success"){
$(".messages").append('<li class="message" id="message">'+reply+'<a id="delete">delete</a></li>');
var clearText = "ture";
}else{
}
}
});
Which is working perfectly fine. But I am having problem while deleting the dynamically added list element.
I tried bind() and on() jQuery functions but as I am not much good at it, I am facing a lot of issues.
$("#messages").on('click', '#delete', function(event) {
event.preventDefault();
var id = 22 ; // just for reference
$.post( "<?php echo base_url(); ?>messages/delete", { type:'single', id:id } )
.done(function( data ) {
});
$(this).closest('li').remove();
});
My HTML structure is as below
<ul class="messages" id="messages">
<li class="message" id="message">sdaghds<a id="delete">delete</a></li>
</ul>
You have id="#messages" on the <ul>. Remove the # and then the .on one should work.
Also, ids are supposed to be unique throughout the page. So you shouldn't have multiple message ids throughout. If you need multiple, use classes. Remove the id from the <li>.
I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)
Trying to make drop down update a graph which is build by Google Chart API.
Few issues I have right now.
It is sending request to a wrong url, instead of /graph/ it is sending data to the page it is on right now which is /services/. So i cant continue debugging it, since it doesnt even send out POST to where it is needed. /graph/(ajax.py) is the one that contains data for AJAX
I know that right now it is not passing down any data, but I wasnt able to figure out even how to access correct view. If 1 is fixed, what would be the best way to pass down value from the drop down menu of twitter bootstrap
HTML
Cred goes to this
<form id="select-graph" name="select-graph" method="POST">
{% csrf_token %}
<div class="btn-group">
<button type="submit" class="btn btn-default dropdown-toggle" data-toggle="dropdown" formmethod="POST">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a onclick="$('#select-graph').submit()">Option 1</a></li>
<li>Option 2</li>
<li class="divider"></li>
<li>About</li>
</ul>
</div>
</form>
AJAX script
Cred goes to this
<script type="text/javascript">
var graphid = 1;
$('#select-graph').submit(function() {
$.ajax({
url: 'https://www.google.com/jsapi?callback',
cache: true,
dataType: 'script',
success: function(){
google.load('visualization', '1', {packages:['corechart'], 'callback' : function(){
$.ajax({
type: "POST",
dataType: "json",
url: '/graph/',
success: function(jsondata) {
var data = google.visualization.arrayToDataTable(jsondata);
var options = {title: 'My Daily Activities'};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
})
}
})
}
})
return true
})
</script>
/graph/ - ajax.py
def insider_graphs(request):
if request.method == 'POST' :
#code that works, this json.dumps with
#special encoder works in all others parts
#of the code and charts look fine
return HttpResponse({'array':json.dumps(data, cls=SpecialEncoder)}, content_type="application/json", context_instance=RequestContext(request))
Solution
Based on accepted solution, I had to make small modification to make it work:
jsondata item that was being passed had the item I needed inside, so rather than call jsondata I needed jsondata['jsondata'], where 'jsondata' is the object name i passed down from django
new line:
var data = google.visualization.arrayToDataTable(jsondata['jsondata']);
Actualy you are firering two submits: one posts to /graph/ (ajax) and the other posts to /services/ (not ajax). The second one reloads the page.
What you need to change is prevent second submit from triggering. You can archive it by calling preventDefault() method of event in submit callbak:
$('#select-graph').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'https://www.google.com/jsapi?callback',
cache: true,
/* rest of your code */
....
});
UPDATE
jsfiddle
UPDATE 2: Valid Django view returning json
return HttpResponse(
json.dumps({'array': data}, cls=SpecialEncoder),
content_type="application/json",
context_instance=RequestContext(request)
)
Friends I created a drop-down list using the following code using js .
<script>
$('.menu').dropit();
</script>
<ul class="menu">
<li>
Product_name
<ul>
<? foreach($customer_details as $details){?>
<li><?echo $details->name;?></li>
<?}?>
</ul>
</li>
</ul>
The problem is that when the user clicks on the link of the dropdown list I need to send the result ie is the
$details->name
through an ajax request to a function in the controller (using codeignitor framework).Hoe this is done ??
JS SOURCE : http://codepen.io/anon/pen/Eoxhp
try this
$('.menu ul li a').on('click', function(e) {
e.preventDefault(); // prevent the link from triggering a pageload
var productName = $(this).html();
$.ajax({
type: "POST",
url: url, // the url you want to send it to
data: {name: productName },
success: function() {
// do whatever you need to do on success
}
});
});
on the server side you'll be able to access the product name using $_POST['name'];
You can try something like this...
// In your HTML replace the line with this
<li><a onclick="sendInfo(this);" href="#"><?echo $details->name;?></a></li>
// JS
function sendInfo(aEl){
var val = $(aEl).text();
$.ajax({
url : "your url",
data : {"name" : val}
}).done(function(){
// Success. Do something
});
}
This is an ajax request on change of drop down it works fine for me
i hope that it will also solve your problem.
<select name="all_users" id="all_users" onchange="Mehdi_ajax(this.value);">
<option value=""><?=$this->lang->line('global_all')?></option>
<?php if($all_users)
{
foreach($all_users->result() AS $item=>$val)
{
?>
<option value="<?=$val->uid?>"><?=$val->username?></option>
<?php
}
}
?>
</select>
script code:
<script type="text/javascript">
var surl = '<?=secure_xss()?>';
function Mehdi_ajax(id)
{
$.ajax({
type:"POST",
url: surl+"movable/jewelry/get_all",
data: "userid=" + id,
success: function(result){
$("#Mehdi_ajax").html(result);
}
});
}