Issue with using a value in JQuery/Javascript - php

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>

Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}

It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.

There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Related

function loads only on change, i would it to load on document load

My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state

jQuery ajax request awkward issue

So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});

jscrollPane disappear when continuously Ajax GET

PROBLEM SOLVED
updated the jscrollpane to the latest version which support jquery 1.8 !
https://github.com/vitch/jScrollPane/blob/master/script/jquery.jscrollpane.min.js
I'm trying to refresh a div with content for a certain period. It will fire an Ajax GET call to a php script which render the content. For the first time ajax GET called, the ScrollPane is there, but for the second time Ajax GET(refresh) JScrollPane disappeared. Any how to reinitialize the jscrollpane?
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}
).data('jsp');
api.getContentPane().html(data);
api.reinitialise();
}
});
setTimeout(callback,10000);
}
$(document).ready(function(){
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
Right now, my scrollpane is there after every Ajax call, but it shows buggy, the jscrollpane will keep moving left after every Ajax Call and slowly, it will hide the content. How is this happened?
foreach ($list as $notification) {
echo "<div class='feeds' id='$notification->notification_id'>";
$userObj = $user->show($notification->added_by);
echo $userObj->first_name.":<span class='text'>".$notification->activity."</span>";
echo " <span class='time'>".$notification_obj->nicetime($notification->created_at)."</span>";
echo "</div>";
}
something like this , that is my activity.php
here is my screenshot , anyone pls do help me #_#
http://img31.imageshack.us/img31/6871/jscrollpane.png
change the order of your commands. make a global variable that caches the ID like this:
var $activity, $activity_pane; // outside the dom ready
function getActivity(callback){
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
success: function(data) {
$activity_pane.html(data);
}
});
setTimeout(callback,10000);
}
$(function(){
$activity = $('#activityLineHolder');
$activity.jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
autoReinitialise: true
});
$activity_pane = $activity.data('jsp').getContentPane();
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
My understanding is that a callback should be executed when the code within your method completes. If you are then wanting to run the getActivity() method again, shouldn't that be used in setTimeout(). Something like this:
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
$('#activityLineHolder').html(data);
}
});
setTimeout(function(){getActivity(callback);},10000);
if($.isFunction(callback)) {
callback();
}
}
I just take a look at http://jscrollpane.kelvinluck.com/ajax.html
I had tried and works. i change setTimeout into setInterval (function from scrollpane).
you can try this (i had tested)
$(document).ready(function(){
var api = $('#activityLineHolder').jScrollPane(
{
showArrows:true,
maintainPosition: false,
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12,
autoReinitialise: true
}
).data('jsp');
setInterval(
function()
{
$.ajax({
url: '../../views/main/activity.php',
success: function(data) {
api.getContentPane().html(data);
}
});
},
10000
);
});
I've faced this problem before, here is a snippet so you can get the idea. Good luck!
attachScroll = function(){
return $('.scroll-pane').jScrollPane({
verticalDragMinHeight: 17,
verticalDragMaxHeight: 17,
showArrows: true,
maintainPosition: false
});
}; // in this var I store all settings related to jScrollPane
var api = attachScroll().data('jsp');
$ajaxObj = $.ajax({
type: "GET", //set get or post
url: YOUR_URL,
data: null,
cache: false, //make sure you get fresh data
async: false, //very important!
beforeSend: function(){
},
success: function(){
},
complete: function(){
}
}).responseText; //$ajaxObj get the data from Ajax and store it
api.getContentPane().html($ajaxObj); //insert $ajaxObj data into "api" pane previously defined.
api.reinitialise(); //redraw jScrollPane
You can define the ajax call as a function and put it into a setInterval.
An example from official docs can be found here
Hope it helps!
Well I suppose that your HTML content coming from AJAX is long and you have problem with decreasing area size because it takes some time to render content by .html():
api.getContentPane().html(data);
And when it goes to the next line api.reinitialise() - HTML rendering isn't complete yet, but jScrollPane already catches current DIV width / height, initializes by those width / height, and then remaining html content is being inserted - and it appears outside of jScrollPane boundaries.
Read similar question: Wait for jquery .html method to finish rendering
So my adice:
1) Add a DIV at the end of your PHP code which will mark end of HTML coming from Ajax:
foreach ($list as $notification) {
...
}
echo '<div id="end-of-ajax"></div>';
2) Add periodical (200ms) check for "end-of-ajax" in your JS code - when it finds the end is reached, it calls for api.reinitialise():
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
EDIT
This is full JavaScript code:
function getActivity()
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{verticalDragMinHeight: 12,verticalDragMaxHeight: 12}
).data('jsp');
api.getContentPane().html(data);
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
}
});
}
$(document).ready(function(){
setInterval(getActivity,10000);
});
Im not sure about what your content is but just make sure that you reset the widths and heights accordingly before reinitlizing. as i had the same issue, and that was the problem
var origHeight =$('#GnattChartContainerClip').height();
var GanttChart = $('#EntireGnattWrapper').get(0).GanttChart;
$('#GnattChartContainerClip').find('#PaddingGnatt').remove();
$('#HeadersCol').find('#PaddingHeaders').remove();
var pane = $('#GnattChartContainerClip');
$('#GnattChartContainerClip').height(origHeight+height);
$('#GnattChartContainerClip').append('<div id="PaddingGnatt" style="width:'+GanttChart.TotalWidth+'px;height:25px"></div>');
$('#HeadersCol').append('<div id="PaddingHeaders" class="header" style="height:25px"></div>');
var paned = pane.data('jsp');
paned.reinitialise();

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

One function to load varrious php pages with jQuery and AJAX

I have the following code that i need some help with, i am trying achieve the same thing with jQuery. I have found some solutions that come close but as yet i am still searching for the perfect solution.
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
Right now i am triggering the function with:
<input type = "button" value = "TEST" onclick = "getData('subject_selectAJAX.php?course_id=1', 'ajax')">
I would like to achieve the same thing with jQuery. I think the following function although wrong gets close, my problem is that the url changes depending on where the user is within the course. course_select.php is initially loaded into the #ajax div, which then would be replaced with subject_select.php?course_id="whatever" followed by topic_select.php?subject_id="whatever"
function getData() {
//generate the parameter for the php script
$.ajax({
url: "something.php", //i want this to be passed to the function
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #ajax div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
I would love some help with this, i'm currently getting confused pretty sure it is something that would help other Ajax jQuery newbies.
This seems to work although i'm sure it could be much cleaner and i would still like to add some sort of loading graphic for slower connections.
<script type="text/javascript">
function getData( url, id ){
$.ajax({
type: "GET",
url: url,
data: "id=" + id,
cache: false,
success: function(html){
$('#ajax').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('fast');
})
};
</script>

Categories