Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Ajax Call PHP File On Load

    Hello,

    I'm new to javascript & ajax. What I'm trying to achieve is, when my page loads, I want a ajax script to send data to a php file and then I want the php file to echo the data sent to it. Later I'll insert this ajax data into the database but for testing I want it to echo.

    For example let's say the javascript collects the user's browser info, On page load I want the ajax to send this browser info to a php script, the php script should echo back the browser info sent to it and it displayed on the calling html page. (this is example I know this can be done with just javascript or php but it will be simple enough to show me how the 2 interact)

    Can you advise me please?

  • #2
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    Isn't this something PHP can do before the page load?

  • #3
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Yes in this exact example like i said it can be done with php or just javascript.

    But my needs are much more and this simple example will show me how to get javascript to interact with php on page load.

    I try my best to keep things as simple as possible to I can understand. thanks for your reply

  • #4
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Maybe it help you guys help me if I gave more infos.

    Im going to have some javascript--that is not written yet, detect some client information and then pas that to php. This logic can only be executed by javascript and needs to run on page load. I guess I can call a javascript function with php.

    Code:
    <?php
    echo <script>myjavascropt.js</script>;
    ?>
    Php is going to grab info from the mysql database and then based on some logic echo an image back to the calling page; html or php.

    The part I'm stuck on is how do I get this info to php and have get the data back from php (<?php echo "<img src=\"$someImgVar\" />";?>)

  • #5
    Regular Coder
    Join Date
    Jul 2006
    Posts
    399
    Thanks
    33
    Thanked 7 Times in 7 Posts
    so your new to js but have php/mysql knowledge?

  • #6
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    yep I've got some php/mysql background.
    Totally lost with javascript except the basics.
    I can create basic variables, functions for loops with javascript. I just don't understand the interaction part as I described above.

    So I think will have 2 files:

    index.php (this is the file with the javascript)
    callback.php (this is the php file that gets' called by javascript to lookup from db and return to index.php with img tags)

    Client hits index.php, javascript runs and sends some info to callback.php

    callback.php hits the database with info supplied from javascript and then echo <img src="something.jpg"/> tags.

    index.php renders the <img src="something.jpg"/> info.

    Can you help me?
    Last edited by robertov; 03-29-2009 at 05:31 PM.

  • #7
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    That's just a basic XHR implementation, easy enough to do, I'm just asking if it's necessary or relevant. The sole reason to use XHR is to send data to the user without having to perform a page reload, not necessarily to just send data back and forth arbitrarily.

    If this is what you want to do, that's fine. Read up on Ajax and the XMLHttpRequest object. There are plenty of examples out there. Although there are some really good JS frameworks, i.e. prototype, jQuery and YUI that give you an easy Ajax implementation, I recommend using them only after you have some experience with straight JavaScript.

  • #8
    Regular Coder
    Join Date
    Jul 2006
    Posts
    399
    Thanks
    33
    Thanked 7 Times in 7 Posts
    yep looks like you dont need ajax here, all user info can be collected with php(user agent etc..). then sent to a db.

  • #9
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Yeah I followed the w3 schools ajax tutorial and got a little stuck.

    here's what I have so far for testing:
    index.php file
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function ajaxFunction()
    {
    var xmlHttp;
    try
      {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
      }
    catch (e)
      {
      // Internet Explorer
      try
        {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
      catch (e)
        {
        try
          {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        catch (e)
          {
          alert("Your browser does not support AJAX!");
          return false;
          }
        }
      }
      xmlHttp.onreadystatechange=function()
        {
        if(xmlHttp.readyState==4)
          {
          document.myForm.time.value=xmlHttp.responseText;
          }
        }
        
            // Send array to php
            var myList = new Array('1','2','3','4');
      	var url="callback.php";
    	url=url+"?q=";
    	for (i in myList){
    		url=url+"?q="+i;
    		xmlHttp.open("GET",url,true);
    		xmlHttp.send(null);
    	
    	}
    
      }
    </script>
    </head>
    <body>
    <script>ajaxFunction();</script>
    
    </body>
    </html>
    in callback.php I have
    Code:
    <?php
    $data=$_GET["q"];
    //$img = "<img src=\"$data\"/>";
    echo $data
    ?>
    I'm not sure how it get this php data echod on the index.php calling page. I'm also not sure if this is the right way to do it.

  • #10
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    I don't want user agent. sorry i am not asking clearly.

    I want to run javascript send data from javascript to php and then have the php echo back to the calling page an image tag or something similar.

    See my code example above.

    Am I still not clear? I try to explain again

  • #11
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    Now we're getting somewhere.
    Code:
    if(xmlHttp.readyState==4)
          {
          document.myForm.time.value=xmlHttp.responseText;
          }
        }
    
    ...
    
    <body>
    <script>ajaxFunction();</script>
    </body>
    Your document doesn't contain any elements, i.e. there is no form element or nothing named 'myForm' with a subelement 'time'. The callback function is attempting to return the data to an element that isn't there. If you add an element into your document body this will at least get you to a place where you can see the data being returned.

  • Users who have thanked bdl for this post:

    robertov (03-29-2009)

  • #12
    New Coder
    Join Date
    Mar 2009
    Posts
    18
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bdl View Post
    Your document doesn't contain any elements, i.e. there is no form element or nothing named 'myForm' with a subelement 'time'. The callback function is attempting to return the data to an element that isn't there. If you add an element into your document body this will at least get you to a place where you can see the data being returned.
    Sorry I no supply code earlier. i thought it would confuse the subject more.

    Ok do i have to have a form? Is there a way to for my callback.php file to echo the <img> onto the index.php page without the form.

    btw, the time stuff is from the w3 schools tutorial and i forgot to take it out.

  • #13
    Regular Coder nomanic's Avatar
    Join Date
    Feb 2009
    Location
    United Kingdom
    Posts
    255
    Thanks
    9
    Thanked 33 Times in 33 Posts
    how about this?
    shove it at the bottom of your page

    the function goer gets called at the bottom, it calls the page url (reserve.php) with the variable pars (x=4&y=3), then on return calls thanks

    thanks calls the alert window, with the text returned from the php page
    alternatively it could fill the contents of a div with something like

    $("divname").innerHTML=text;

    hope this helps, many thanks

    Code:
    <script type="text/javascript">
    
    function goer() {
    		var url = 'reserve.php';
    		var pars="x=4&y=3";
    		makeHttpRequest(url+"?"+pars, thanks);
    }
    
    function thanks(text) {
    
    	alert(text);
    }
    
    function $() {
    	if (arguments.length == 1) return get$(arguments[0]);
    	var elements = [];
    	$c(arguments).each(function(el){
    		elements.push(get$(el));
    	});
    	return elements;
    
    	function get$(el){
    		if (typeof el == 'string') el = document.getElementById(el);
    		return el;
    	}
    };
    
    function makeHttpRequest(url, callback_function, return_xml)
    {
     var http_request, response, i;
    
     var activex_ids = [
       'MSXML2.XMLHTTP.3.0',
       'MSXML2.XMLHTTP',
       'Microsoft.XMLHTTP'
     ];
    
     if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+...
       http_request = new XMLHttpRequest();
       if (http_request.overrideMimeType) {
         http_request.overrideMimeType('text/xml');
       }
     } else if (window.ActiveXObject) { // IE6 and older
       for (i = 0; i < activex_ids.length; i++) {
         try {
           http_request = new ActiveXObject(activex_ids[i]);
         } catch (e) {}
       }
     }
    
     if (!http_request) {
       alert('Unfortunately your browser doesnt support this feature.');
       return false;
     }
    
     http_request.onreadystatechange = function() {
       if (http_request.readyState !== 4) {
           // not ready yet
           return;
       }
       if (http_request.status !== 200) {
         // ready, but not OK
         alert('There was a problem with the request.(Code: ' + http_request.status + ')');
         return;
       }
       if (return_xml) {
         response = http_request.responseXML;
       } else {
         response = http_request.responseText;
       }
       // invoke the callback
       callback_function(response);
     };
    
     http_request.open('GET', url, true);
     http_request.send(null);
    }
    
    goer();
    
    </script>

  • Users who have thanked nomanic for this post:

    robertov (03-29-2009)

  • #14
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    No, you only have to use a form if you want to return something to a form element. I'm simply suggesting this because your code example uses what appears to be a form element. In your case I would do something like this:

    Code:
    <body>
    <div id="results"></div>
    <script>ajaxFunction();</script>
    </body>
    So your document body now contains an empty DIV element that you can return data to, in this case an image.

    Your XHR callback function then returns the image element from the PHP script to the empty div, e.g.
    Code:
    if(xmlHttp.readyState==4)
    {
        // target the empty DIV element
        document.getElementById("results").innerHTML= xmlHttp.responseText;
    }
    So whether you return a numeric value, a string or markup, you can insert it straight into the empty DIV element.

    This is basic DOM manipulation, which is typical behavior for Ajax. Aside from the Ajax tutorials, you should definitely read up on the Document Object Model.

  • Users who have thanked bdl for this post:

    robertov (03-29-2009)

  • #15
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    @nomanic> Great input, but don't you think the OP is on a very low level as far as understanding JavaScript / Ajax, and your code example is a much higher, abstract level that will not be understood?

    By the way, it is generally recommended to insert your JS code at the bottom of any other elements in the document body, as the page will load more quickly, and then execute once the DOM elements are ready. This in contrast to loading all the JS in the document head and then using a window.onload method to execute a function once the DOM is ready.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •