I have an image hyperlinked as:
<a id="register" href = "javascript:void(0)"
data-fancybox-group="gallery"><img src="<cms:show my_image_thumb />" alt="" class="fade"></a>
I have a getsession.php class to get the session variable:
<?php
session_start();
if(isset($_SESSION['logged_in']))
echo "1";
else
echo "0";
?>
I want to read the session variable value on click of the image. I am trying to do this as:
<script type="text/javascript">
$(document).ready(function(){
$("#register").click(function(){
$.ajax({
url:'getsession.php',
cache:false,
success:function(data){
// Do something with the result
if(data=="1"){
window.location = "www.google.com";
}else{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
});
});
});
</script>
However, when clicking the image there is no effect. Any pointers?
First, make sure to log ( console.log('button clicked'); ) that the function is entered and then log the data ( console.log(data); ) when the response arrives.
Also, check that the php script is working by simply opening it in the browser.
By the way, window.location should have an absolute url assigned to it
window.location = "http://www.google.com";
Chances are your php file is not placed in the proper position. Try running the file directly from url. It should print 1 if session is set. And after this,try changing the url to absolute url of the file like http://localhost/getsession.php .
try this :
php:
<?php
session_start();
if(isset($_SESSION['logged_in']))
echo "1";
else
echo "0";
?>
js:
$.ajax({
url:'http://localhost/getsession.php',
cache:false,
type: 'POST',
success:function(data){
// Do something with the result
alert("ajax call success returns: "+ data);
if(data=="1"){
window.location.href = "http://www.google.com/";
}else{
window.location.href = "http://www.stackoverflow.com/";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
Related
I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>
Below is a piece of code that is placed inside for loop
for( some condition will go here )
{
echo "<td>
<a href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
}
On clicking over it the user gets directed to event.php page and along with it, event_id and action parameters are also carried forward,
but instead of this
i wish to call event.php page to the first page through ajax for this i tried this
<script>
function chk()
{
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
}) ;
return false;
}
</script>
echo
"<td>
<a onclick='return chk()'>". ($i - $startday + 1) . "</a>
</td>";
but its not working, and i also wish yo carry forward event_id and action parameters through ajax to event.php page on every click, can anyone tell how this can be done
Here is what you can do
<a href="#" class="myclass" data-id="'.$someID.'" data-action="'.$someAction.'">
and js will be
$(".myclass").on("click", function(){
var id = $(this).data("id");
var action = $(this).data("action");
$.ajax({
type : "post",
url : "event.php",
data : {
"id":id,
"action":action
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
});
It should be like this
$.ajax({
type : "post",
url : "event.php",
data : {
"event_id":"-id of the event-",
"action":"-0action paramter-"
},
cache : false,
success : function(html)
{
$('#msg').html(html);
}
});
Build your loop adding a class:
echo "<td>
<a class='anEvent' href='event.php?event_id=".$datee2. "&action=Details'>". ($i - $startday + 1) . "</a>
</td>";
Then use:
<script type="text/javascript">
$('.anEvent').on('click',function(e){
e.preventDefault();
$('#msg').load($(this).attr('href'));
})
</script>
You can use data attributes and $.post request, and better if you can avoid the inline-events and give your link an identifier (class ajax-link in my example because your code will be created from a loop so we don't have to use id since id should be unique in same document) then you can use it to attach click event to the a tag, check the following example :
PHP :
"<td>
<a class='ajax-link' data-event-id=".$datee2." data-action='Details'>". ($i - $startday + 1) . "</a>
</td>";
JS :
$('body').on('click', '.ajax-link', function(e){
e.preventDefault();
var url = $(this).data('action');
var event_id = $(this).data('event-id');
$.post(url, {event_id: event_id, action: action},
function(html)
{
$('#msg').html(html);
}
});
})
Hope this helps.
The problem is you are clicking the link which starts loading event.php.
You should use event.preventDefault() to avoid default action in chk() function.
function chk()
{
event.preventDefault();
$.ajax({
type:"post",
url: "event.php",
data:dataString,
cache:false,
success: function(html)
{
$('#msg').html(html);
}
});
return false;
}
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.).
This question already has an answer here:
Viewing data returned by ajax in IE9
(1 answer)
Closed 9 years ago.
I have tried to send an AJAX request and wanted to see what I've send.
But unfortunately I'm not able to do it.
There exists a select option element that I will fill later with the response if everything works.
<script type="text/javascript">
$(document).ready(function(){
$('select[name="domains"]').change(function(){
var requestStr = $(this).val();
// send Ajax request
$.ajax({
cache: 'false',
type: 'POST',
data: {select:requestStr},
url: 'myHandler.php',
dataType: 'json',
success: function(data){
var json = JSON.parse(data);
alert(json.response); // Here you get the value
if(data.status == 'success')
alert("Thank you for subscribing!");
else if(data.status == 'error')
alert("Error on query!");
var str = "<option value=''>Please Select</option>";
//$.each(data, function(i, items){
// str += "<option value='"+items.id+"'>"+items.name+"</options";
//});
$('select[name="countries"]').html( str );
},
// When an error occurs, the error function is called.
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
});
The PHP handler Looks like this:
<?php
require_once 'myClass.php';
if (isset($_POST['select']))
{
// log event
$filename = "log.txt";
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $_POST['select'];
fwrite($fd, $str . "\n");
fclose($fd);
$handler = new myClass();
$dataAjax = $handler->getName($_POST['select']);
echo json_encode($dataAjax);
}
<?php
class myClass {
function getName($data)
{
return $data;
}
}
I thought I can use the request parameter and return it but there is nothing I can see.
Oh, I use Internet Explorer so I can't use Firebug.
EDIT
I added a few rows to log my request.
But the log file is empty.
UPDATE
Now there is some progress:
I can see this in the request-text "select=QD".
But when I echo it with echo json_encode($dataAjax);
I get a error window with Error.Parsing JSON Request failed.
I don't get it why the 'success' function won't work!
The response is json encoded.
Oh btw. is it right that I can't use "return" in PHP to send my response back to AJAX?
You can print out request at server side and log it into file/syslog/etc.
if (isset($_POST['countries']))
{
$handler = new myClass();
$dataAjax = $handler->getName($_POST['countries']);
echo json_encode($dataAjax);
}
------------------------------------------------------
dataType: 'json'
if you just want to see the headers,post,response,html then try firebug
function IsJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
this will check whether the response is json or not
I have a enable and disable button. Each buttons returns a "success" message in the console when clicked. The enable button works in a single click, however, the disable button needs to be clicked twice before it prints the "success" message in the console in my developer tools. What is the problem with this? Can somebody helps me fixing this one? Thanks a lot. Here is my code:
<button class="btn_mode" value="1">Enable</button>
<button class="btn_mode" value="0">Disable</button>
<script type="text/javascript">
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
</script>
my controller function
function change_mode(){
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
echo json_encode(array('notify'=>$notification));
}
model
function change_mode($mode){
$id = 1;
$data = array('mode' => $mode);
$this->db->where('id',$id);
$this->db->update('maintenance_mode',$data);
return true;
}
Output when adding the console.log('Posting mode_val: ' + mode_val); in the javascript
Clicking the enable button output in the console
Output in the console when clicking the disable button
As your event hook-up looks fine, i suspect that something is going wrong on the server side, which means that your success handler isn't firing. Try logging prior to your ajax call, to see if the click event fires at all:
$(".btn_mode").click(function(){
var mode_val = $(this).val();
var postdata={'mode':mode_val};
console.log('Posting mode_val: ' + mode_val);
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
}
});
});
If the above logs the expected values when you click the buttons, that means that your php script is failing the first time you call it with mode_val = 0.
You could try catching whatever exception might be thrown like so:
function change_mode(){
try{
$mode = $this->input->post('mode');
$query = $this->course_booking_model->change_mode($mode);
if($query){
$notification = "Success";
}
else{
$notification = "Failed";
}
}
catch(Exception $e){
$notification = $e->getMessage();
}
echo json_encode(array('notify'=>$notification));
}
Edit:
The images you have uploaded indicate that there is a problem with the server-side code, and your button click is firing just fine. If you update your php to catch the error and return it, you should be able to get a hint as to what is going wrong. To see the call completing, you could implement the 'complete' and/or 'error' callbacks:
$.ajax({
type:"POST",
url:"<?php echo base_url();?>superadmin/change_mode",
dataType:'json',
data:postdata,
success: function(data){
if(data.notify=="Success")
{
console.log(data.notify);
location.reload();
}
else{
console.log(data.notify);
}
},
error: function(jqXhr, txtStatus, errThrown){
console.log('Call failed with status:' + txtStatus);
if(errThrown)
console.log('and error:' + errThrown);
},
complete: function(jqXhr, txtStatus){
console.log('Call completed with status:' + txtStatus);
}
});
});
hmmm maybe something like this
$(".btn_mode[value='1']").on("click", function(){ do something });
$(".btn_mode[value='0']").on("dblclick", function(){ do something });
Try to change your model to return the real outcome of the update.
Like:
return $this->db->update('maintenance_mode',$data);
depending on what the db wrapper return after an update.