Solved

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

Posted on 2012-04-11
8
473 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
[X]
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
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

710 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