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");
});
Related
I am trying to send click id of item to Django view on every click so that I can update count against every item.
I achieved this by using ajax and javscript but there is some issue when id is sending id to Django view.
what actually happening-
when I click on any item(1)(first time) - nothing happen
but when I click on any item(let suppose 2) - then it send 1 and 2
again when I click on item 3 - it send 1,2,3
I don't know why it is behaving like this.
it should send only one item it which is clicked
my code is-
{% for solution in item %}
<ul>
<li >{{solution.solution_name}}
<a href="#"><i value="{{solution.id}}" class="fa fa-download down" aria-hidden="true" onclick="count(document.getElementById('fname_{{solution.id}}').value)">
<input type="text" id="fname_{{solution.id}}" value="{{solution.id}}"></i></a>
</li>
</ul>
{% endfor %}
my ajax part-
<script>
function count(a) {
var id = parseInt(a);
$('.down').click(function(e){
console.log("clicked item id is")
e.preventDefault();
console.log(id);
$.ajax({
type:'POST',
url: '/solutions/count',
data: {
'id': id
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
})
}
</script>
You are calling your function on click and in that function you got another click event, this will create you problems, so you need only one click event
use:
<script>
$(function(){
$('.down').click(function(e){
e.preventDefault();
var id = $(this).attr('value');
$.ajax({
type:'POST',
url: '/solutions/count',
data: {
'id': id
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
})
});
Remove the onclick attribute form your html
I have the following Code :
<ul>
<li>
<a href="index.php?page=quiz" class="cat" >
<h3>Category 1</h3>
<p>(explain here)</p>
</a>
</li>
<li>
<a href="index.php?page=quiz" class="cat" >
<h3>Category 2</h3>
<p>(explain here)</p>
</a>
</li>
</ul>
What I need is to send the category number to the page index.php?page=quiz
via $_POST or anything else
without sending it via $_REQUEST like this index.php?page=quiz&cat=1
OR assigning the category number value to a $_SESSION variable according to current clicked link
to get the value at destination page index.php?page=quiz.
I have already tried this solution:
Via javascript by sending the variable value to the page
var num=1; /*or put the current clicked category number */
$.ajax({
url: 'index.php?page=quiz',
type: 'post',
dataType: 'json',
data: {
category_no: num,
}
})
There seems to be a problem with the sending process and the value of page=quiz
is not send to the destination and we are still on the current page where page=home.
Do you have any helpful ideas?
NOTE: My problem is not getting the category id from current clicked (button/link) to javascript, but sending it to destination page with any of the ways mentioned above.
Explaining Solution:
The problem was there is no exit() and json_encode() as results into my function which cannot be applied inside page index.php code which mean that
the whole function must be moved to another file
the problem solved like following:
my page:
<ul>
<li>
<a href="" data-no="1" class="cat" >
<h3>Category 1</h3>
<p>(explain here)</p>
</a>
</li>
<li>
<a href="" data-no="2" class="cat" >
<h3>Category 2</h3>
<p>(explain here)</p>
</a>
</li>
</ul>
JavaScript:
$('.cat').on('click', function (e) {
// Prevent default action of link click
e.preventDefault();
var cat = $(this).data('no');
var curr='set_var.php';
$.ajax({
url: curr,
type: 'POST',
dataType: 'json',
data: {
category: cat
}
}).done(function(res) {
if (res.valid) {
document.location.href = 'index.php?page=quiz';
}
});
});
set_var.php :
<?php
session_start();
if(isset($_POST['category'])){
$_SESSION['cat']=$_POST['category'];
$result['valid'] = TRUE;
}
echo json_encode($result);
exit();
?>
Thanks for all your answers
Add the category id as a data attribute like this:
<ul>
<li>
<a data-category-id="1" href="index.php?page=quiz" class="cat" >
<h3>Category 1</h3>
<p>(explain here)</p>
</a>
</li>
<li>
<a data-category-id="2" href="index.php?page=quiz" class="cat" >
<h3>Category 2</h3>
<p>(explain here)</p>
</a>
</li>
</ul>
Then handle the click event like this to make your ajax call (dynamically get the clicked category link's url and it's id):
// When page loads
$(document).ready(function()
{
// Handle category click event
$('a.cat').click(function(e)
{
// Prevent default action of link click
e.preventDefault();
// Get the url
var categoryUrl = $(this).prop('href');
// Get the category id
var categoryId = $(this).data('category-id');
// Make ajax call
$.ajax({
url: categoryUrl,
type: 'post',
dataType: 'json',
data: {
category_no: categoryId
}
})
.done(function() {
location.href = categoryUrl;
});
})
});
This way, when you click the link (default action of going to the url doesn't run). Instead; an ajax POST request is made to clicked url (in your case always index.php?page=quiz) first and when the request completes, then you are redirected to that page.
If num is your clicked category, I think it should work like:
var num=1;
$.ajax({
url: 'index.php?page=quiz',
type: 'post',
dataType: 'json',
data: {
num,
}
});
And in your 'index.php':
session_start();
$_SESSION['catID'] = $_POST['num'];
If this doesnt' work, it would be helpful to see your index.php.
Edit: Lets try it with another side .. just for testing.
Create a new php called getCatID.php and change AJAX to:
var num=1;
$.ajax({
url: 'getCatID.php',
type: 'post',
dataType: 'json',
data: {
num,
}
});
window.location = "index.php?page=quiz"
In the getCatID.php:
<?php
session_start();
$_SESSION['catID'] = $_POST['num'];
?>
And in your index.php try to
echo $_SESSION['catID'];
PS: You need to trigger the Ajax Call in a way
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>
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);
}
});
}