here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<?php
$url = "http://api.wunderground.com/api/7d5339867b063fd0/geolookup/conditions/q/UK/".$area.".json";
?>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : ,
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("This is an example of a web service outputting using Json. The current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
How can i add the "$url" variable into the javascript code at the location " url : "here",
Thanks
You just need to put it like that:
url : "<?=$url?>",
OR (best way):
url : "<?php echo $url; ?>",
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<?php
$url = "http://api.wunderground.com/api/7d5339867b063fd0/geolookup/conditions/q/UK/".$area.".json";
?>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "<?=$url?>",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("This is an example of a web service outputting using Json. The current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
url : "<?php print $url ?>",
Use json_encode():
var jsVar = <?=json_encode($phpVar)?>;
or in your case:
$.ajax({
url: <?=json_encode($url)?>,
dataType: "jsonp"
// ...
});
This is the safest way, and works with any data (arrays etc.).
Related
I know this has been discussed before but I can't seem to make anything work. I'm trying to pass the variable $thedate from PHP file mainclass.php to the variable datestr in a JS function from the file footer_script.php
JS:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = <?php echo json_encode($thedate); ?>;
$("#" + str).html(data);
}
}).error(function() {
alert(data);
});
}
PHP:
case "getsched":
//some code
//some query
while($row = mysql_fetch_array($result))
{
//more code
$thedate = $_POST['date'];
}
//other code here
break;
When I alert datestr, I get undefined. How to fix this?
You can't use PHP like this. You should obtain the response from PHP and use it. In your PHP, you should output a response similar to this (just an example of JSON response):
echo json_encode(array('thedate', '2018-4-3'));
and you can obtain the value of 2018-4-3 in your JS with:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = data.thedate;
$("#" + str).html(datastr);
}
}).error(function() {
alert(data);
});
}
You need to replace the line:
var datestr = <?php echo json_encode($thedate); ?>;
with
var datestr = JSON.stringify(date);
alert(datestr);
It will convert the server response to a JSON encoded string. The encoded string is then displayed in the alert. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Assign a global variable in HTML/PHP file before includeing JS file.
var datestr = <?php echo $thedate; ?>;
Then you can access the datestr variable from your JS file.
The filter contained Refine search button and the page loads the product according to search.But I want when i check the checkbox the product should display.This can be acheived by ajax..
Original script Of opencart 2.1.0.2 product filter
`<script type="text/javascript"><!--
$('#button-filter').on('click', function() {
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
});
//--></script>
`
And I tried using ajax
`$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
$('.products-block').html(data);
}
});
console.log;
return false;
});`
I am getting the desired result .But It loads the whole page. And how can i use any loader if possible.
location is global and changes the browser url. To avoid using global location you need to define location using var
$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
var location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
$('.products-block').html(data);
}
});
console.log;
return false;
});
It was just little change in code.In success function i removed the specific id and its working fine
<script type="text/javascript">
$(document).on('change','.sort_rang',function(){
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
$.ajax({
type: "POST",
location: location,
success: function(data)
{
html(data);
}
});
console.log;
return false;
});
I get some data using JSON array. I want to append each data in a div. But I don't get what's wrong in that?
controller
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
script
function get_performers(id,exam)
{
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
// alert("haii");
console.log(result);
result = JSON.parse(result);
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
for(var i=0;i<result.student_details.length;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + result.student_details[i]["subject_name"]+ "</span></div> ";
}
jQuery("#subjectNames").append(tab);
}
});
}
Any problem in this?
Try html not append
jQuery("#subjectNames").html(tab);
Also if jQuery("#subjectNames") equal with null in your console this mean that you don't have element with id="subjectNames" in html not id="#subjectNames" or other. May be you use classes then try $(".subjectNames") with . not #
The Loop should work... Seems to be another problem with your result.
var tab= "<div class='col-xs-2 blk-ht'><span class='hd'>Names</span> </div>";
for(var i=0;i<20;i++)
{
tab=tab+"<div class='col-ds-1'><span class='subjNames'>" + "test: " + i + "</span></div> ";
}
jQuery("#subjectNames").append(tab);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="subjectNames"><div>
dataType: 'json' in $.ajax options - automaticaly parse your json
and USE JQUERY )))
IN SUCCES AJAX FUNCTION
$.each( result.student_details, function( key, value ) {
alert( key + ": " + value );
});
<?php
function get_performers()
{
$id = $this->input->post('id');
$exam = $this->input->post('exam');
$datas=$this->job->get_top_ten_st_data($id,$exam);
$out['student_details'] = $datas;
echo json_encode($out);
}
?>
<script>
$.ajax({
url:"<? echo base_url();?>class_analysis/get_performers",
dataType: 'json',
type: "POST",
data: {id:id,exam:exam},
success:function(result) {
$.each(response.student_details, function(key,value){
appendHtml(key,value);
});
}
});
function appendHtml(key,value)
{
var tab= "<div class='col-xs-2 blk-ht'> <span class='hd'>Names</span> </div>";
tab = tab+"<div class='col-ds-1'><span class='subjNames'>" +value+ "</span></div> ";
jQuery("#subjectNames").append(tab);
}
</script>
i have javascript like this
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
var menu_id = this.value;
if(this.checked) var statusvalue = "On";
else var statusvalue = "Off";
$.ajax({
type : "POST",
url : "admin/menu/editstatus",
data : "id=" + menu_id + "&value=" + statusvalue,
success : function(data){
$("#testing").html(data);
}
});
});
});
and my controller named menu and have function editstatus()
public function editstatus()
{
$data = "asd";
echo $data;
}
but textbox with id testing not writen anything
change ajax function like below
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
var menu_id = this.value;
if(this.checked)
{
var statusvalue = "On";
}
else
{
var statusvalue = "Off";
}
$.ajax({
type : "POST",
url : "<?php echo base_url()?>admin/menu/editstatus",
data :{
id:menu_id,
value:statusvalue
}
success : function(data){
$("#testing").val(data);
}
});
});
});
I think your url did not found.Try using base url
<?php echo base_url()?>admin/menu/editstatus
You need to use .val() instead of .html()
Corrected code:
$("#testing").val(data);
http://api.jquery.com/val/
https://api.jquery.com/html/
public function editstatus()
{
$data = "asd";
echo json_encode($data);
}
if $data is an array form e.g $data=array('name'=>'abd','id'=>'12') then ,
in Java script access like ,data.name or data.id
below code working fine but I need to append option1 in href,
$(document).ready(function () {
$("#head_drop .dd-option").click(function () {
var option = $('.dd-option-value',this).attr('value');
var option1 = $('.dd-option-text',this).text();
// alert(option1);
$.ajax({
type: 'get',
url: '<?php echo $this->getBaseUrl();?>categories/index/city/',
data: {option: option},
success: function(data) {
$(location).attr('href',"<?php echo $this->getBaseUrl()?>");
}
});
});
});
now its return
http://example.com/
I want like http://example.com/option1
I tried $(location).attr('href',"<?php echo $this->getBaseUrl()?>"option1); but failed to get, Thanks...
If option1 is a variable all you need is to concatenate with a + -
$(location).attr('href',"<?php echo $this->getBaseUrl()?>" + option1)
You have your " at the wrong place, it should read:
$(location).attr('href',"<?php echo $this->getBaseUrl()?>option1");