Jump to content

JQuery load php in div INCLUDING arguments


neuroxik
Go to solution Solved by neuroxik,

Recommended Posts

I've searched everywhere and just can't seem to find my answer, so here:

 

I'm powerful with php and that I can deal with, but I never really had the chance to develop my javascript skills. I want to use JQuery to load part of a page in a container div. The problem is every tutorial I check out, the target (or result) div where the content will load is already defined in the function. Is there a way to include 2 arguments like this : (pseudo-code, I don't know the real syntax, still a newb at JQuery)

function ajaxpage(url, containerid){
   // do the magic here
}
 
// and calling the page

<a href="javascriptTheJQueryWayHere:ajaxpage('page.php?id=12','load_in_this_div')">link</a>



<div id="load_in_this_div"></div>


I don't necessarily want a baked answer, just any link to any resource except RTFM would be of great help!
Link to comment
Share on other sites

There are more ways to do it than I'm showing, but this should cover your need without needing to post.

 

 

$(document).ready(function()
{
    // Our URL to load.
    var url = "http://example.com";
    
    /*
     * Option 1
     *
     * Use the $.load() function.  This will load the returned data
     * straight into the container.
     */
    
     $("#myDivID").load(url);
    
     /*
      * Option 2
      *
      * Same as option 1, but deal further with the data.
      */
      
      $("#myDivID").load(url, function(data)
      {
          alert(data); // Alert the returned data.
      });
      
      /*
       * Option 3
       *
       * $.get() function and manually add it to the container.  Usually
       * I wouldn't use this if I'm adding it to a container though.
       * Maybe if you're appending instead of replacing the data?
       */
       
       $.get(url, function(data)
       {
           var append = true;
           
           if (append)
           {
               // Append the data
               $("#myDivID").append(data);
           }
           else
           {
               // Replace the data
               $("#myDivID").html(data);
           }
       });
       
       /*
        * Better than a javascript: link in the href attribute of a link.
        *
        * HTML something like:
        * <a href="#" id="myLinkID">Click Here</a>
        */
        
        $("#myLinkID").click(function(e)
        {
            e.preventDefault();
            
            $("#myDivID").load(url);
            
            return false;
        });
});
Link to comment
Share on other sites

There are more ways to do it than I'm showing, but this should cover your need without needing to post.

 

Thanks for the reply!

 

I read and tested the code and the first ones loaded the content into the div on page load. I'm not looking to autoload content but rather load the content when the user clicks. The last part of your code did actually work for that, this part:

 

 

$("#myLinkID").click(function(e)
        {
            e.preventDefault();
            
            $("#myDivID").load(url);
            
            return false;
        });

 

Now two things as I've mentioned earlier :

 

1 - Can I put the url part (the one that in your code is declared as var url) in the link? I want this because my links are change depending on the context and get the context via GET variables, so I can have (in this case a calendar) "cal.php?sel_year=2013&sel_month=04". I'm trying to figure out how to pass the url string as an argument.

 

2 - I'll be using this on multiple links on multiple divs for different purposes. Do I have to write a function for each target div or can I (most logically) pass the Div ID as an argument too?

Link to comment
Share on other sites

You could just do var url = $(this).attr("href"); in the click function to get the URL in the link.  If different links go to different DIV's, I would probably use a class for all of the link that go to a certain DIV.  It all depends on what you are doing.

Link to comment
Share on other sites

You could just do var url = $(this).attr("href"); in the click function to get the URL in the link.  If different links go to different DIV's, I would probably use a class for all of the link that go to a certain DIV.  It all depends on what you are doing.

 

Thanks for you reply again!

 

I tried this like you said:

 

 

 $("#myLinkID").click(function(e)
        {
            var url = $(this).attr("href"); /* <-- added var url THIS */

            e.preventDefault();
            
            $("#myDivID").load(url);
            
            return false;
        });

/* and for test links : */

<div id="bla">links :
     <a href="ajaxtest.php?action=no&data=1" id="myLinkID">1</a>
     <a href="ajaxtest.php?action=no&data=2" id="myLinkID">2</a>
</div>
<div id="myDivID"><!-- load here --></div>

 

It works on the first click (thanks!) but doesn't when say I click on link 2, it loads the called (href) page instead of loading it in the div. I'm presuming because both links share the same Div ID.

 

Anyway, thanks alot for your input, I'll try figuring out from here on, atleast I have some base to work on.

 

Link to comment
Share on other sites

The ID needs to be unique across ALL elements in an HTML document. Instead of using id="myLinkID" in the anchor, use a class: class="myLinkClass". Then change the selector in your function to select by class instead of ID: $(".myLinkCLass").click(function(e). I think that will fix the problem.

Link to comment
Share on other sites

The ID needs to be unique across ALL elements in an HTML document. Instead of using id="myLinkID" in the anchor, use a class: class="myLinkClass". Then change the selector in your function to select by class instead of ID: $(".myLinkCLass").click(function(e). I think that will fix the problem.

 

Hm, great idea. Unfortunately it doesn't load anything. Atleast it solves the double ID and the 2nd link loading a new page doesn't do that anymore. Thanks nonetheless for having taken the time to check out my problem!

Link to comment
Share on other sites

That's what I was trying to say when I said I would use a class.  I figured you knew you couldn't use the same ID on multiple elements, so I didn't really bother to specify.  But, here's a little example.

 

 

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $(".myClass").click(function(e)
        {
            e.preventDefault();
            
            $.get($(this).attr("href"), function(data)
            {
                alert(data);
            });
            
            return false;
        });
    });
</script>

<a href="/index.php" class="myClass">Click Here</a>
Link to comment
Share on other sites

 

That's what I was trying to say when I said I would use a class.  I figured you knew you couldn't use the same ID on multiple elements, so I didn't really bother to specify.  But, here's a little example.

 

 

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $(".myClass").click(function(e)
        {
            e.preventDefault();
            
            $.get($(this).attr("href"), function(data)
            {
                alert(data);
            });
            
            return false;
        });
    });
</script>

<a href="/index.php" class="myClass">Click Here</a>

 

Yeah, I'm sorry about the class, I know you mentioned it now but I was so overwhelmed by the Javascript that I thought you meant writing a class as in OOP class.

 

Wow! This worked! But when I changed alert(data) to $("#myDivID").load(url); it doesn't load, I don't know what I'm doing wrong there. I did obviously include the div itself with #myDivID.

 

By the way, a huge thanks, I know this must seem like trivial stuff for you guys but it's helping me out alot.

Link to comment
Share on other sites

That would be loading it twice.  I used $.get() just to do something in the click function.  You would replace the whole $.get() or set $("#myDivID").html(data); inside of the function where you see the alert.  Also, you probably want to change the URL of the link or define a different URL.

 

It would be easier if you showed the code you currently have.  It don't matter if you did something wrong.  Showing what you've tried makes it easier to help.

Link to comment
Share on other sites

That would be loading it twice.  I used $.get() just to do something in the click function.  You would replace the whole $.get() or set $("#myDivID").html(data); inside of the function where you see the alert.  Also, you probably want to change the URL of the link or define a different URL.

 

It would be easier if you showed the code you currently have.  It don't matter if you did something wrong.  Showing what you've tried makes it easier to help.

Sorry, I've been really sick for the last couple of days and wasn't able to get back to you.

 

So I've just tested changing the load(url) to html(data) (I had actually tried load(data) as last resort the other day, which obvisouly didn't work either) and now this seems to work so far. Thank you! I'll post the code below as requested, only difference is the other day html(data) was load(url). There's not much, I only did test files apart without any sanitization because they're only tests :

 

test4.php :

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
    
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $(".myClass").click(function(e)
        {
            e.preventDefault();

            $.get($(this).attr("href"), function(data)
            {
                $("#myDivID").html(data);    /* chg'ed "load(url)" to "html(data)" */
            });
            
            return false;
        });
    });
</script>
</head>
<body>
    <a href="ajaxtest.php?data=1" class="myClass">Click Here 1</a>
    <a href="ajaxtest.php?data=2" class="myClass">Click Here 2</a>
    <div id="myDivID"><!-- load here --></div>
</body>
</html>

and ajaxtest.php :

<?php
$data = addslashes($_GET['data']);

if($data) {
    if($data=='1') echo '<p>some data one</p>';
    elseif($data=='2') echo '<h1>other data two</h1>';
}
?>

I'll just try to re-put some code you had suggested earlier so that some instances can have some content load by default on page load.

 

EDIT: I'm still trying to figure out how I could pass the target ID within the link so I can use different links (in other sections of the page) that would load in other divs rather than load them in #myDivID. Of couse, I wouldn't name those links with the "myClass" class, but would I have to create a different function for each case or can I just pass the target div (div to load content in) as an argument rather than hardcode it as #myDivID ?

 

Edited by neuroxik
Link to comment
Share on other sites

I would probably use a different class.

 

	$(document).ready(function()
	{
		$(".myClass").click(function(e) {
			e.preventDefault();
			loadToDiv($(this).attr("href"), '#myDivID');

			return false;
		});

		$(".myOtherClass").click(function(e) {
			e.preventDefault();
			loadToDiv($(this).attr("href"), '#myOtherDivID');

			return false;
		});
	});

	function loadToDiv(psUrl, psDivSelect) {
		$.get(psUrl, function(data) {
			$(psDivSelect).html(data);
		}
	}
Link to comment
Share on other sites

I would probably use a different class.

 

	$(document).ready(function()
	{
		$(".myClass").click(function(e) {
			e.preventDefault();
			loadToDiv($(this).attr("href"), '#myDivID');

			return false;
		});

		$(".myOtherClass").click(function(e) {
			e.preventDefault();
			loadToDiv($(this).attr("href"), '#myOtherDivID');

			return false;
		});
	});

	function loadToDiv(psUrl, psDivSelect) {
		$.get(psUrl, function(data) {
			$(psDivSelect).html(data);
		}
	}

 

Thanks, I'll try that out as soon as I can.

Link to comment
Share on other sites

It's a typo in the function definition. I forgot to close the parenthesis on the .get() function call. Man I really hate anonymous functions.

 

	function loadToDiv(psUrl, psDivSelect) {
		$.get(psUrl, function(data) {
			$(psDivSelect).html(data);
			}
		);
	}
[edit] If you watch the Conole, JavaScript should have reported an error when it loaded that script. Edited by DavidAM
Link to comment
Share on other sites

  • Solution

It's a typo in the function definition. I forgot to close the parenthesis on the .get() function call. Man I really hate anonymous functions.

 

	function loadToDiv(psUrl, psDivSelect) {
		$.get(psUrl, function(data) {
			$(psDivSelect).html(data);
			}
		);
	}
[edit] If you watch the Conole, JavaScript should have reported an error when it loaded that script.

 

Thanks! Now that works. Yes, should've checked the console. By the way, speaking of consoles, I use Console² and Firebug for Firefox, would you have any better suggestions?

 

A huge thank you to Xaotique and you, DavidAM, for having shed alot of light on this. I'll still try to manage passing the target Div through argument (maybe through the "rel" attribute? I was worried about semantics but again, it is sort of "related" if you take it into context). Atleast now I have some working ground to do this by myself, I just didn't know where to start, so a huge thank you again!

 

{marking as solved}

 

Link to comment
Share on other sites

I usually just use what's now built-in to Firefox. But then, I don't do a lot of JS.

 

In reference to passing the DIV ID. You could set the Anchor ID to whatever the DIV ID is adding a trailing sequence number. Then something like this might work:

 

<SCRIPT>
	$(document).ready(function()
	{
		$("A.reload").click(function(e) {
			e.preventDefault();

			// The DIV ID is the A ID without the trailing sequence number
			divID = $(this).attr('id');
			divID = '#' + divID.replace(/[0-1]*$/, '');

			loadToDiv($(this).attr("href"), divID);

			return false;
		});
	});

	function loadToDiv(psUrl, psDivSelect) {
		$.get(psUrl, function(data) {
			$(psDivSelect).html(data);
		});
	}
</SCRIPT>

	<A href="" class="reload Cats" id="reloadCats1">ABC</A>
	<A href="" class="reload Cats" id="reloadCats2">DEF</A>
	<A href="" class="reload Cats" id="reloadCats3">GHI</A>

	<DIV id="reloadCats"></DIV>
	
	<A href="" class="reload Dogs" id="reloadDogs1">ABC</A>
	<A href="" class="reload Dogs" id="reloadDogs2">DEF</A>
	<A href="" class="reload Dogs" id="reloadDogs3">GHI</A>

	<DIV id="reloadDogs"></DIV>
* Not tested

 

Then you could style all of the .reload links exactly the same using CSS.

Link to comment
Share on other sites

I usually just use what's now built-in to Firefox. But then, I don't do a lot of JS.

 

In reference to passing the DIV ID. You could set the Anchor ID to whatever the DIV ID is adding a trailing sequence number. Then something like this might work:<DIV id="reloadDogs"></DIV>

* Not tested

 

Then you could style all of the .reload links exactly the same using CSS.

 

Hmm, it halfway works, but I see where you're getting at, great idea. Thanks!

 

I'm not trying you to solve it, I'll only explain what happens in case you were wondering :

 

 

<a href="ajaxtest.php?data=1" class="reload tDiv" id="tDiv1">Click Here 1</a> <!-- yeh, I had them named as tDiv by now, but same principle as you -->
<a href="ajaxtest.php?data=2" class="reload tDiv" id="tDiv2">Click Here 2</a>
<div id="tDiv"><!-- load here --></div>

What this does (with your functions) is the first link (Click Here 1) loads the data correctly in tDiv, but link 2 loads it, somehow, where "Click here 2" itself was. At first I thought the data was only appending itself until I saw the 2nd link itself dissapear.

 

Again, no big deal, I'm trying to figure this out myself. I suck at Javascript to be honest, but I think that's clearly been made obvious. Thanks again for your input! Great insights.

Link to comment
Share on other sites

Sounds like the replace may not be working (or you left the "2" off the Anchor's ID). I don't do a lot of JS so the expression might not be write. Try an alert(DivID); right after this line

divID = '#' + divID.replace(/[0-1]*$/, ''); to see if it is working as expected (should show the DIV's ID).

Link to comment
Share on other sites

Sounds like the replace may not be working (or you left the "2" off the Anchor's ID). I don't do a lot of JS so the expression might not be write. Try an alert(DivID); right after this line

divID = '#' + divID.replace(/[0-1]*$/, ''); to see if it is working as expected (should show the DIV's ID).

Sorry for replying late again, pretty busy week + sick but I really appreciate your help and input.

 

I thought it might be the regex. I did use the as different trailing ID numbers as quoted in my previous post. I'll try the alert and put it on my server so you can see by the source, if ever you have the time that is.

 

My test of the previous example can be seen here : http://arraykey.com/ajaxtests/test9.php . The reason the second link makes it jump a line is because the strings I fetch are embedded in <p></p> tags, so that's what's creating the break-line (not an issue, I was just mentioning in case you were wondering)

 

And here's with alert(divID) as you suggested :

 

http://arraykey.com/ajaxtests/test10.php

 

 

Link to comment
Share on other sites

Gees, I'm an idiot!

 

divID.replace(/[0-1]*$/, '')

 

That should be 0-9 (zero through nine) not 0-1. And the * should probably be a + (* means zero or more, + means one or more).

 

Sorry about that.

Hooo! It works now! Thank you so much for all your time!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.