Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2012-04-11
8
471 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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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
 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

839 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