Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
iwato

$.ajax( ) Strategy Question

Recommended Posts

BACKGROUND:  I now know how to produce dynamic HTML populated with the values of Javascript variables obtained from a database and processed with PHP.  Unfortunately, this method of integrating Javascript and HTML is somewhat awkward.  What I would much rather be able to do is to read the variables into a dynamically produce <script> tag and then manipulate them on the importing page. 

REQUEST:  To this end, please comment on the veracity and accuracy of the following statements:

  1. When an AJAX call is made only the Javascript contained in the success and complete functions is executed.
  2. It makes no difference that the HTML with which the Javascript interacts is already on the page when the AJAX call is made.
  3. Unless the AJAX call is made while the page is loading, all Javascript already contained within the page will have been executed before that contained within the AJAX statement. 
  4. Javascript variables imported via AJAX can be accessed by other Javascript on the same page after the variables have been imported.

Please advise.

Roddy

Share this post


Link to post
Share on other sites

1. Success and complete are just a jQuery thing, but if you're using jQuery that is correct. Those functions get called once the request is complete. In the case of plain AJAX, the readystatechange event handler is what's executed when the request is done.

2. The HTML must already be loaded if Javascript should interact with it, but that usually is the case since AJAX is usually called after the page has finished loading. Note that if you change the DOM using innerHTML or jQuery's html() method any references to HTML elements from that page region that were stored in variables will no longer work even if they have the same ID or class name as before. You will need to load them again using a jQuery selector or DOM methods such as getElementById().

3. That's correct.

4. AJAX doesn't import Javascript variables. It can return data that may be interpreted as a Javascript object. jQuery will automatically parse JSON for you into an object, but that object is only accessible as a parameter in the complete() method of the AJAX request.

  • Thanks 1

Share this post


Link to post
Share on other sites

Good morning, Ingolme!

Thank you for responding to my statements.  I believe that your responses will help me in avoiding certain kinds of pitfalls.  This said, I would like to elaborate a little more on Item #4.  What i have in mind is the following:

1) Use AJAX to retrieve data

2) Use the $.ajax() success function to assign the data to javascript variables included in a dynamically generated <script> tag.

3) Access those Javascript variables at will.

Please consider the following sketch and comment on its feasibility.

The HTML:  (flexible manual placement of HTML independent of the configuration of the AJAX success function)

<div id='js_script'></div>
<div>
	<p id='pod_num1'>Podcast No.: </p>
	<p id='pod_num2'>Podcast No.: </p>
</div>

The jQUERY READY() FUNCTION: (flexible variable placement independent of the configuration of the AJAX success function)

$(document).ready(function() {
	$('#pod_num1').append(var1);
	$('#pod_num2').append(var2);
});

 

The AJAX: (automatically generated variables on call)

$('#some_trigger').on('click', {podType:$(this).attr(id)}, function(event) {
  event.preventDefault();
  podtype = event.data.podType;
  $.ajax({
    url: 'some_php_file.php',
    method: 'GET',
    data: {'podType', podtype},
    dataType: 'json',
    success: function(jsonData) { 
        $.each(jsonData, function(key, object){ 
            $('#js_script').append('<script>var var1 = object.varname1; var var2 = object.varname2;</script>');
        });
    }
  });
});

 

 

Edited by iwato

Share this post


Link to post
Share on other sites

You could do that, that should make those variables available in the global scope, but that's kind of a roundabout way to do that, to use Javascript to append a script block.  Javascript is already running, you can just set things directly.  I mentioned this in another topic, but if you start by declaring those variables in the global scope then you can just set them directly later.  So put a script block on the page and define those variables when the page starts, and then in the ajax callback just set the variables directly instead of writing a new script block.  It just seems like a roundabout way to have Javascript write a script block when you can do things in Javascript directly, it's already running.

Instead of global variables, you might also consider using sessionStorage or localStorage to store things like that.

  • Thanks 1

Share this post


Link to post
Share on other sites

Yes, I understand.  I will write the <script> element directly into the page.  It does make better sense for my ultimate formatting goal.  In this way, the only job of AJAX is to send the data needed to obtain the data.  in this way the actual use of the data is a separate matter.

Yes, I now no how to implement the $_SESSION superglobal, but I will save its further use for other occasion.  Soon I must start putting the pieces together and am reluctant to add any more large pieces for the moment. 

Roddy

Share this post


Link to post
Share on other sites

sessionStorage and localStorage aren't in PHP, they're in Javascript.  You can use them to save data between pages, or in this case storing values that would have been global variables.

Share this post


Link to post
Share on other sites

Yes variables in a page are accessed by JavaScript code on that page only. To access variable values in different pages you can use:

1. Cookies

2. Local storage of browser.

3. Pass variables values in query string (like url?var1=2&var2=myvarvalue)

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×