Ajax - Getting Null Value if no new data - ajax

I'm building a notification system and I'm just in need of one last part to make it work perfect.
When the ajax first loads it uses the php variable against the server side script to look for new content and if it does find something new it uses that new notification_id and updates the var for the next set of results, if it doesn't find anything the second time around the url notification_id becomes null and inserts null values into the div.
How would I stop this from happening?
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id'] ;?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
global: true,
dataType:"json",
cache: false,
success: function(data){
if(notification_id < data.notification_id){
$("#notif_actual_text-"+data.notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
notification_id = data.notification_id;
}
});
}
setInterval(loadIt, 10000);
</script>

Try this (if the code above is from viewajax.php):
// Simply use isset() to check if $_GET['notification_id'] is set or not
var notification_id="<?php echo isset($_GET['notification_id']) ? $_GET['notification_id'] : $notification['notification_id']; ?>";
or if you are sending it to another file:
<?php
// Let's just say that this is viewajax.php
$notification_id = $_GET['notification_id'];
echo json_encode(array("notification_id" => $notification_id));
?>

Related

Using ajax to update the currently page with Laravel

I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}

Ajax post executed twice and adding up

I'm facing an issue with ajax that several users here also encountered but the proposed solution do not seem to work for my case.
in my index.php file, I have:
<pre>
<script>
function ButtonManager()
{
$( "button" ).click(function()
{
var context = $(this).attr('type');
var page_type = $(this).attr('page');
var referrer = $(this).attr('referrer');
var form_type = $(this).attr('form');
var object_id = $(this).attr('object');
var postData = 'page_type='+page_type+'&form_type='+form_type+'&referrer='+referrer+'&id='+object_id;
$( '#indicator' ).css( "display", "block" );
if (context == 'post_form')
{
var formData = $('#submit_content').serialize();
postData = postData+'&context=post_form&'+formData;
}
if ((context == 'load_form') || (context == 'filter_form'))
{
postData = postData +'&context=load_form';
if (context == 'filter_form')
{
var filter1 = $('select[name=filter1]').val();
var filter2 = $('select[name=filter2]').val();
var filter3 = $('select[name=filter3]').val();
postData = postData + '&filter1='+filter1+'&filter2='+filter2+'&filter3='+filter3;
}
}
$.ajax
({
type: 'POST',
url: 'php/sl.php',
data: postData,
cache: false,
async: false,
dataType: 'html',
success: function(result)
{
ManageLayer(form_type+'_content');
$('#'+form_type+'_content').html(result);
$( '#indicator' ).css( "display", "none" );
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
$( '#indicator' ).css( "display", "none" );
},
});
});
}
</script>
<button type="load_form" page="home" referrer="navigation" form="edit" object="">test</button>
</pre>
when a click on the test button, the script calls sl.php to retrieve some html with other buttons in it.
in the output I get from the server I have added:
<pre>
<script>
var myvar=ButtonManager();
</script>
<button type="post_form" page="home" referrer="navigation" form="edit" object="">test2</button>
</pre>
The goal of the ButtonManager function is to manage all my buttons in one function so it needs to be available/known everywhere (in index.php where it's loaded and in all the output I can get from sl.php).
I have added the var myvar=ButtonManager() line because it's the only way I have found to make sure the function is known by the server output. The drawback is that the function is executed multiple times instead of one even if I don't click on the test2 button.
So I'm looking either for a way to prevent my function from being executed multiple times or an alternative to make the function available everywhere.
I don't know what approach would be the best, I'm a casual developper programming for fun and javascript / ajax is not the language I know the best.
Thanks
Laurent
I got the answer from another forum but I wanted to share it in case others are having the same problem.
Code to be used should be like this:
<pre>
$( document ).on("click", "button", function() {
</pre>
It makes the function available to objects that do not exist yet.

Wordpress - Admin-AJAX is not saving meta data

Trying to use the built in AJAX functions with the Wordpress Admin. I've been following this tutorial, but when I run the jQuery script, the data isn't being saved to the user meta.
<?php
add_action( 'admin_footer', 'ring_jquery' );
function ring_jquery() {
?>
<script type="text/javascript">
jQuery('.ring-submit').on('click', function(){
var u = jQuery(this).attr('user'),
c = jQuery('.agt_ringc[user="'+u+'"]').val(),
x = jQuery('.agt_ringx[user="'+u+'"]').val(),
formData = 'ringu='+u+'&ringc='+c+'&ringx='+x;
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: formData,
success: function(e){
jQuery('.success[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
},
error: function(){
jQuery('.fail[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
}
});
});
</script>
<?php
} //End ring_jquery()
add_action('wp_ajax_my_action', 'ring_callback');
function ring_callback() {
global $wpdb; // this is how you get access to the database
$ringu = $_POST['ringu'];
$ringc = $_POST['ringc'];
$ringx = $_POST['ringx'];
update_user_meta($ringu,'agt_ringc',$ringc);
update_user_meta($ringu,'agt_ringx',$ringx);
die(); // this is required to return a proper result
}
?>
You will need to have action : my_action in the data string , or as per codex :
var data = {
action: 'my_action',
whatever: 1234
};
Issue was, as #ObmerkKronen pointed out was that I was missing an action definition in the data string (which tells the AJAX page which function to run).
formData = 'action=ring_callback&ringu='+u+'&ringc='+c+'&ringx='+x;
I also changed the name of the action hook to match the name of the function. I don't know if this was necessary, but some other things I found did it and I wanted to fit in.
add_action('wp_ajax_ring_callback', 'ring_callback');

if .get() data same on setInterval do nothing if different reload data

I have a DIV which is populated from $.get data on doc ready, I then call setInterval every 5 seconds. What im trying to do is on success of the setInterval $.get if the html data for #are_friends is the same as before do nothing but if its different then load the data to #are_friends again.
Does anybody have any idea how I would do this or a better way than Im trying to implement.
<div id="are_friends"></div>
<script type="text/javascript">
$(document).ready(function() {
$.get('<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>', function(data) {
$("#are_friends").html(data);
});
var auto_refresh = setInterval(
function ()
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
var oldcontent = $("#are_friends").html();
if(oldcontent != newdata) {
$("#are_friends").html(newdata);
}
}
});
}, 5000); // refresh every 5000 milliseconds
});
</script>
At least, you could reuse the function getting the data like this:
function getData(callback)
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
callback(newdata);
}
});
}
$(document).ready(function()
{
getData(function(data)
{
$("#are_friends").html(data);
});
var auto_refresh = setInterval(function ()
{
getData(function(newdata)
{
if($("#are_friends").html() != newdata) {
$("#are_friends").html(newdata);
}
});
}, 5000);
});
Practically, the initial call and the subsequent call is the same, so why don't reuse it?
That is related a lot to data you are workign with. Right now you are just producing a lot of useless trafic. I would recommend to send also some marker of current state when you are requesting are_friends.php. PHP will check if something changed using that marker and return "no changes" or updated HTML. Here you should lower server load during if nothing is changed and less trafic(suppose most request will return "no changes"). But again. It depends on what you are doing in are_friends.php, what data do you need etc.

Jquery and ajax

I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);

Resources