Solved

Simple Ajax Jquery script. How can I get information show in table.

Posted on 2012-04-11
8
466 Views
Last Modified: 2012-06-27
I expect this element will be accessed by jquery and this text will be replaced by tables query result but it it did not show a result of students ID and firstName like this and My table is set up like this:

--------------
|  studentID  | firstName|
--------------
| 123             | Kermit      |
| 124             | Gonzo      |
| 125             | Cookie     |
--------------

  $host = "localhost";
  $user = "root";
  $pass = "root";

  $databaseName = "collegeData";  // collegeData.sql
  $tableName = "studentTable";    

I've included screen grab of MAMP for your convenience.      

html script called client.php
<!---------------------------------------------------------------------------------------------
Example client script for JQUERY:AJAX -> PHP:MYSQL example
by Trystan Lea : openenergymonitor.org : GNU GPL

I recommend going to http://jquery.com/ for the great documentation there about all of this
---------------------------------------------------------------------------------------------->
<html>
  <head>
    <script language="javascript" type="text/javascript" src="jquery.js"></script>
  </head>
  <body>

  <!---------------------------------------------------------------------------------------------
  1) Create some html content that can be accessed by jquery
  ---------------------------------------------------------------------------------------------->
  <h2> Module No2 </h2>
  <h3>Output: </h3>
  <div id="output">this element will be accessed by jquery and this text will be replaced</div>

  <script id="source" language="javascript" type="text/javascript">

  $(function () 
  {

    //-------------------------------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-------------------------------------------------------------------------------------------
    $.ajax({                                      
      url: 'api.php',                  //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
      dataType: 'json',                //data format      
      success: function(rows)          //on recieve of reply // change from data to rows
      {
		for (var i in rows)
         {
          var row = rows[i];          

          var studentID = row[0];				//get id //var id = row[0];	
          var vfirstName = row[1];			//get name // var vname = row[1];
	
        //--------------------------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------------------------
       			// $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);     //Set output element html
        //recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
      $('#output').append("<b>id: </b>"+studentID+"<b> name: </b>"+vfirstName)
                  .append("<hr />");
    } 
  } 
});
});
</script>
   
  </body>
</html>  

Open in new window




This is PHP api.php
<?php 

  //--------------------------------------------------------------------------
  // Example php script for fetching data from mysql database
  // by Trystan Lea : openenergymonitor.org : GNU GPL
  //--------------------------------------------------------------------------


  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------
  include 'DB.php';
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);

  //--------------------------------------------------------------------------
  // 2) Query database for data
  //--------------------------------------------------------------------------
  $result = mysql_query("SELECT * FROM $tableName");            //query
 // $array = mysql_fetch_row($result);                          //fetch result  
 // mysql_fetch_row() returns only 1 row. Put it into a loop
  $data = array();												//Change to array
	while ( $row = mysql_fetch_row($result) )
	{
 		$data[] = $row;
	}
	echo json_encode( $data );
  

  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($array);

?>

Open in new window



This is DB.php

<?php

//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
  $host = "localhost";
  $user = "root";
  $pass = "root";

  $databaseName = "collegeData";  //collegeData.sql 
  $tableName = "studentTable";		

?>

Open in new window

0
Comment
Question by:Redscrapbook
  • 5
  • 3
8 Comments
 
LVL 20

Assisted Solution

by:Proculopsis
Proculopsis earned 500 total points
ID: 37836981
See if this jsfiddle helps.
0
 

Author Comment

by:Redscrapbook
ID: 37837873
I'm using jQuery 1.6.4...I've tried to use jsiddle but not sure how to use it. Can you readjust please to jQuery 1.6.4?
0
 
LVL 20

Assisted Solution

by:Proculopsis
Proculopsis earned 500 total points
ID: 37838052
Just set the drop-down on the left to "jQuery 1.6.4" and hit the "Run" button.
0
 

Author Comment

by:Redscrapbook
ID: 37838139
------------------------------------------------------
|  studentID  | firstName| lastName  |  
--------------
| 123             | Kermit      | Frog           |
| 124             | Gonzo      |Great           |
| 125             | Cookie     |mosnter      |
------------------------------------------------------

I've run it http://jsfiddle.net/Proculopsis/9Wzp2/ and there is no space between firstName and lastName?  

And LIMIT to ten in a list.


var rows = [
    { studentID: 123, firstName: "Kermit", lastName: "Froh" },
    { studentID: 124, firstName: "Gonzo", lastName: "Great" },
    { studentID: 125, firstName: "Cookie", lastName: "Monster" },
];

var data = {
    json: JSON.stringify(rows),
    delay: 3
}

$.ajax({
    url: "/echo/json/",
    data: data,
    type: "POST",
    success: success
});

function success(rows) {
    $("#output").empty();

    $(rows).each(function() {
        $("#output").append($("<b/>").text("id: "));
        $("#output").append(this.studentID);
        $("#output").append($("<b/>").text("name: "));
        $("#output").append(this.firstName);
        $("#output").append($("<b/>"));
        $("#output").append(this.lastName);
        $("#output").append($("<hr/>"))
    });
}

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 20

Accepted Solution

by:
Proculopsis earned 500 total points
ID: 37841255
Seems okay:

var rows = [
    { studentID: 123, firstName: "Kermit", lastName: "Froh" },
    { studentID: 124, firstName: "Gonzo", lastName: "Great" },
    { studentID: 125, firstName: "Cookie", lastName: "Monster" },
    { studentID: 126, firstName: "Kermit", lastName: "Froh" },
    { studentID: 127, firstName: "Gonzo", lastName: "Great" },
    { studentID: 128, firstName: "Cookie", lastName: "Monster" },
    { studentID: 129, firstName: "Kermit", lastName: "Froh" },
    { studentID: 130, firstName: "Gonzo", lastName: "Great" },
    { studentID: 131, firstName: "Cookie", lastName: "Monster" },
    { studentID: 132, firstName: "Kermit", lastName: "Froh" },
    { studentID: 133, firstName: "Gonzo", lastName: "Great" },
    { studentID: 134, firstName: "Cookie", lastName: "Monster" }
];

var data = {
    json: JSON.stringify(rows),
    delay: 3
}

$.ajax({
    url: "/echo/json/",
    data: data,
    type: "POST",
    success: success
});

function success(rows) {
    $("#output").empty();

    $(rows).each(function() {
        $("#output").append($("<b/>").text("id: "));
        $("#output").append(this.studentID);
        $("#output").append($("<b/>").text(" name: "));
        $("#output").append(this.firstName);
        $("#output").append("&nbsp;");
        $("#output").append(this.lastName);
        $("#output").append($("<hr/>"))
    });
}

Open in new window

0
 

Author Comment

by:Redscrapbook
ID: 37845344
I've attached a screen grab This is a screen grab.
This is a result of a screen grab.
id: 123name: KermitFroh
id: 124name: GonzoGreat
id: 125name: CookieMonster
id: 126name: KermitFroh
id: 127name: GonzoGreat
id: 128name: CookieMonster
id: 129name: KermitFroh
id: 130name: GonzoGreat
id: 131name: CookieMonster
id: 132name: KermitFroh
id: 133name: GonzoGreat
id: 134name: CookieMonster

Open in new window


Is it possible to have space like &nbsp; in between id and names as example as below.
id: 123 name: Kermit Froh
id: 124 name: Gonzo Great
id: 125 name: Cookie Monster
id: 126 name: Kermit Froh
id: 127 name: Gonzo Great
id: 128 name: Cookie Monster
id: 129 name: Kermit Froh
id: 130 name: Gonzo Great
id: 131 name: Cookie Monster
id: 132 name: Kermit Froh
id: 133 name: Gonzo Great
id: 134 name: Cookie Monster

Open in new window

0
 

Author Comment

by:Redscrapbook
ID: 37845390
I've just revised my original question, ID: 37838139 and ID: 37841255 as above. The original question is about retrieving data from mysql in a database and not to supposed to know the names in a script yet until it is on clients side screen?

Can anyone enlighten? Is this code as query GET rsesult?
var rows = [
    { studentID: 123, firstName: "Kermit", lastName: "Froh" },
    { studentID: 124, firstName: "Gonzo", lastName: "Great" },
    { studentID: 125, firstName: "Cookie", lastName: "Monster" },
    { studentID: 126, firstName: "Kermit", lastName: "Froh" },
    { studentID: 127, firstName: "Gonzo", lastName: "Great" },
    { studentID: 128, firstName: "Cookie", lastName: "Monster" },
    { studentID: 129, firstName: "Kermit", lastName: "Froh" },
    { studentID: 130, firstName: "Gonzo", lastName: "Great" },
    { studentID: 131, firstName: "Cookie", lastName: "Monster" },
    { studentID: 132, firstName: "Kermit", lastName: "Froh" },
    { studentID: 133, firstName: "Gonzo", lastName: "Great" },
    { studentID: 134, firstName: "Cookie", lastName: "Monster" }
];

Open in new window

0
 

Author Closing Comment

by:Redscrapbook
ID: 37881886
Thank you Proculopsis for the replies.  Worth the points. It is not 100% solved. I'll post this as PART II if I decide to incorporate this at a later date?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now