• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
An AJAX How?

[eluser]Kyle Johnson[/eluser]
Hey everyone,

I'm really new to Javascript and AJAX, the latter of which I just started with today.

I'm sure this has been asked a thousand times, but I honestly don't know what it's called and my few searches have been unsuccessful.

Essentially, I am getting data from the database, filtering it and returning two values. I then make it into a string using this code:
echo $suggest['id'] . "\t" . $suggest['suggest'] . "\n";

function handleSearchSuggest() {
    if (searchReq.readyState == 4) {
        var ss = document.getElementById('search_suggest')
        ss[removed] = '';
        var str = searchReq.responseText.split("\n");
        if (str.length > 1)
            ss.style.display = "block";
            ss.style.display = "none";
        for(i=0; i < str.length - 1; i++) {
            //Build our element string.  This is cleaner using the DOM, but
            //IE doesn't support dynamically added attributes.
            var suggest = '<div ';
            suggest += 'on mouse out="[removed]suggestOut(this);" ';
            suggest += '"[removed]setSearch(this . inner html, this . somehow get id);" ';
            suggest += 'class="suggest_link">' + str[i] + '</div>';
            ss[removed] += suggest;

How do I get the second parameter for setSearch to equal the ID in the returned portion of the data? Currently the list is showing the entire string with the "ID (tab) Text I want (newline)" The setSearch command is supposed to make a hidden field value = to the ID and the other field = to the text returned.

Hopefully you can understand what I'm trying to do. Javascript tends to frustrate me (<-- see my display image???)

The board is taking out some of the Javascript commands, so I had to put some spaces in it so you can see...

I would first recommend getting used to a JavaScript framework. I used to use my own homebrew Ajax implementation, but these days I'd much rather rely on jQuery. Not only will the framework ensure that your ajax requests work on all modern browsers (implementation varies between browsers), but it will help with things like executing code onsuccess.

With jQuery, it's as simple as:
$.post(url, data, callback, type);

So as an example:
$.post("serverside.php", //server-side script url
       {user_id : 12345, password : "apples", rand : "7AGHSIU"}, //data being sent as $_POST variables
       function(info){  //the callback function (executes on completion of ajax call
       "json"); //type to return data as

The syntax looks ugly at first but after you get used to it, it's a lifesaver. The documentation is great as well.

[eluser]Kyle Johnson[/eluser]

it looks close to what i want... but it looks very confusing now.

the ajax i'm using so far has worked on all the browsers i've tested it with (chrome, ie 6, ie 7 and firefox)...

I'll peek around some more, but how would the info.id and info.username know what data i want?

Yeah, when I first started to use some of the JavaScript frameworks I was VERY intimidated by the syntax. The second parameter is a list of key=>value pairs that get send to your php script. The return type in this case would be a JSON object, with properties 'id' and 'username'. The return type can be other things as well, like xml. Whatever your comfortable with using basically. JSON is lightweight and it's native JavaScript so your don't have to extract the data from XML nodes first before inserting it into your page. Check out jQuery.com or just google for a few more examples, it'll sink in slowly.

By using jQuery you'll significantly cut down on the amount of code you write, and the entire framework is a surprisingly small 20k.

[eluser]Kyle Johnson[/eluser]

I went to www.visualjquery.com and followed their examples of the $.post code, but it doesn't seem to return anything, and the "alert('Data returned' + data)" doesn't seem to do anything either.

Am I missing something? I have included the jquery-1.3.2-min.js

Here is my code

In head element within script tag:
language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"

In body element:
&lt;input type="button" value="Test Button"&gt;

Every now and then IE 7 says I have a syntax error on the above line of code, but it doesn't always say that. I'm very confused. So far what I have read has not helped me get this part working.

The code in test.php is as follows:
echo json_encode(array("name"=>"John","time"=>"2pm"));

[eluser]Kyle Johnson[/eluser]
Ok.. so adding a script section at the bottom with some functions in it seems to get me in the right direction.

function findData()
        $.post("test.php", { name: "Tyler", time: "2pm" },
                alert("Data Loaded: " + data);

And it does popup with the data in test.php (currently the POST doesn't do anything in test.php but I will make it)

It may be because visualjquery.com is dated. The site was for version 1.2.6 and your using 1.3.2. I suggest checking the official documentation to see if anything has changed.

You'll get it eventually (<-helpful, right?). Just a note, the 'language' attribute in the script tag is deprecated, and I would recommend including jQuery through google code/api as most users will already have it cached. Like this:
&lt; script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'&gt;&lt;/ script>

They host all the different versions of most popular JS frameworks.

[eluser]Kyle Johnson[/eluser]
garmardell, thank you for pointing that out. I am going to use the JQuery documentation now.

slowgary, I would like to always use the google code, but sadly a portion of this app will be intranet only.

Alright!!! Here we go!

I found out some stuff, currently I don't know javascript, so it is all rather difficult even though I know the logic needed.

I found out I can only return a single data value at a time. I also have to specify a header:

header('Content-type: application/json');

Now I just need to figure out how to loop the values in javascript, or alert if an error occurred. I specified a "LIMIT 1" in the query for now so that I can at least check the db connection is working.

Not sure how I'm going to tie it in with CI yet. New languages are very intimidating, especially when you're skipping the "Hello World" guides.

Crazy crazy things.

You should be able to return as much data as you need. You could even just return a huge chunk of markup and inject it into the page (or the innerHTML of a specific element).

I'm not too comfortable with json yet but when I'd looked at examples it seems flexible enough to be able to return many 'rows' of data.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.