Solved

Return data with AJAX, JQUERY and PHP

Posted on 2016-11-29
13
27 Views
Last Modified: 2016-12-01
Hello guys,

I´m novice in jquery but would like learning ajax. I need create a table and population each line with return on PHP

HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
<table width="369" border="1" cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td width="175" align="center" style="font-family: Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: bold;">DATE</td>
      <td width="188" align="center" style="font-family: Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif; text-align: center; font-weight: bold;">ORDER</td>
    </tr>
    <tr>
      <td>HERE</td>
      <td>HERE</td>
    </tr>
  </tbody>
</table>
</body>
</html>

Open in new window



AND MY PHP

<?php

$Conn = mysql_connect("127.0.0.1", "root", "");
$Db = mysql_select_db("flexyou04");


$sql = mysql_query("SELECT VENCIMENTO, NUMERO_DOC FROM financeiro_conta WHERE VENCIMENTO between '2016-03-01' and '2016-03-01'");
/*while($resposta = mysql_fetch_array($sql)){
	
	$VENCIMENTO = $resposta['VENCIMENTO'];
	$NUMERO_DOC = $resposta['NUMERO_DOC'];
	
}*/

$arr = array();
if(mysql_num_rows($sql) > 0) {
    while($row = mysql_fetch_assoc($sql)) {
        $arr[] = $row;  
    } 
}

$json_response = json_encode($arr);
echo $json_response;


?>

Open in new window

0
Comment
Question by:eduardo12fox
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
First up you need to migrate away from the mysql library - it has been deperecated and will be removed from future PHP releases - rather use MySQLi

Secondly - avoid putting styling inline - rather use a stylesheet - it makes the code easier to manage and in most cases involves less typing. If you are going to be building rows dynamically with AJAX - you don't want to have to do the CSS as well - that is just painful.

Third - headings in tables should be in the <thead> section with cells enclosed in <th>

Handling AJAX can be done in one of two ways

1. You render the html on the server and send it back as HTML and then use JavaScript simply to replace the html on the page with the new html
2. You send back the JSON and construct the elements on the fly in the browser

Here is a sample that demonstrates both (based on your code above)
HTML
    <h2>Server side render</h2>
    <button class="btn btn-primary" id="serverside">Load</button>
    <table class="table" id="server-render">
      <thead>
        <tr>
          <th>DATE</th>
          <th>ORDER</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    <h2>Client side render</h2>
    <button class="btn btn-primary" id="clientside">Load</button>
    <table class="table" id="client-render">
      <thead>
        <tr>
          <th>DATE</th>
          <th>ORDER</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

Open in new window

jQuery
<script>
$(function() {
  $('#serverside').click(function() {
    $('#server-render tbody').load('t1909server.php');
  });
  
  $('#clientside').click(function() {
    $.ajax({
      url: 't1909client.php',
      type: 'GET',
      data: {param1: 1, param2: 2},
      dataType: 'JSON'
    }).then(function(resp) {
      if (resp) {
        $('#client-render tbody').empty();
        for(var i in resp) {
          var tr = $('<tr/>');
          for(var j in resp[i]) {
            var td = $('<td/>').html(resp[i][j]);
            tr.append(td);
          }
          $('#client-render tbody').append(tr);
        }
      }
    });
  });
});
</script>

Open in new window

Working sample here
1
 

Author Comment

by:eduardo12fox
Comment Utility
Thanks man! Congratulation.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
check how to do that with Angular instead jQuery (we still use Ajax in the background) :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script>
  var app = angular.module("myApp", []);
  var ctrl = app.controller("MyCtrl", ["$scope", "comptaService", function($scope, comptaService) {
      $scope.lines = [];
      comptaService.getLines().then(function(xhr) {
        $scope.lines = xhr.data;
      });
  }]);
  var svc = app.factory("comptaService", ["$http", function($http) {
    return {
      getLines: function() {
         return $http.get('/path/to/your/page.php');
      }
    }
  }]);
</script>
</head>
<body>
<table width="369" border="1" cellspacing="0" cellpadding="0" ng-app="myApp" ng-controller="MyCtrl">
  <tbody>
    <tr>
      <td width="175" align="center" style="font-family: Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: bold;">DATE</td>
      <td width="188" align="center" style="font-family: Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif; text-align: center; font-weight: bold;">ORDER</td>
    </tr>
    <tr ng-repeat="line in lines"><td>{{line.VENCIMENTO}}</td><td>{{line.NUMERO_DOC}}</td></tr>
  </tbody>
</table>
</body>
</html>

Open in new window

1
 

Author Comment

by:eduardo12fox
Comment Utility
Wow Lvl 82  greats!!
0
 

Author Closing Comment

by:eduardo12fox
Comment Utility
Thaks man! Very easy
1
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Just a note for going forward -- if you want an AngularJS solution instead of a jQuery solution, it might make sense to put the question in the  AngularJS Zone instead of jQuery!
1
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Note2 - Angular is a framework - jQuery is a library

1) You should not mix the two
2) If you are going to use Angular then you should consider building your entire application using Angular not just bits of it.

If you are beginning with JavaScript then I would not recommend you start with Angular unless you have some JavaScript / jQuery experience under your belt - it is quite a learning curve moving into the Angular environment.

Personally I don't think Angular was the right call on this question - but if it is working for you ...
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
what you need to know :
Angular use a light version of jQuery if jQuery is not available. That mean, it's jQuery compatible but, you need to know to don't play with DOM (page content) inside a controller. With jQuery or any other framework or library used with AngularJS.
Here some code of AngularJS 1.5.7, the goal is to check if jQuery is already loaded and use it instead jQuery light/lite :
  // Use jQuery if it exists with proper functionality, otherwise default to us.
  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  // versions. It will not work for sure with jQuery <1.7, though.
  if (jQuery && jQuery.fn.on) {
    jqLite = jQuery;
    extend(jQuery.fn, {
 

Open in new window


I disagree with Julian on the complexity of AngularJS especially if you're new to JS.
If you're familiar with (or open to) MVC concepts and object programming, I think it's a very good thing to start with AngularJS as it allow you to separate coding, design and data services without knowing nothing about DOM programming.
Today with CSS we can do complex animation, again it was jQuery purpose.

More, if you start and know nothing about Javascript... go to TypeScript and Angular 2.
0
 

Author Comment

by:eduardo12fox
Comment Utility
Hey Guys!

I´m programmer in Adobe Flex and actionscript but this time I need create a solution in HTML because this I have this doubt. between tecnology, sorry I be with FLEX (Adobe)  Lol... But fot this work how do this in html the Angular show me more easy.

I know that some say that Flex is tecnology dead "bla bla bla" But still today is very robust and greated power.

But thanks a lot for help me.
Begin in AngularJs
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
I had some funny time creating a liquid crystal game library with Flex.
It's near Javascript, same for me, just the way we declare object.

Also check this, that may be helpful : http://dailyjs.com/2015/01/08/as3-typescript/
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
If you're familiar with (or open to) MVC concepts and object programming, I think it's a very good thing to start with AngularJS as it allow you to separate coding, design and data services without knowing nothing about DOM programming

... and when you need to use / write a directive?

Angular in the form presented here makes things look simple - but when you start getting into writing real applications (routing, nested views and components, trascluded elements, isolate scope) it suddenly looks like a whole big learning curve.

If what you want to achieve is just minor DOM manipulation (as in this example) - Angular works but is not always the right choice.

One of the criticisms of Angular over React has been the learning curve. Personally I think it is is worth it but if you are just getting started don't be misled by this simple example that the rest of Angular is that easy.
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
... and when you need to use / write a directive?

when you need, it's very simple to use and most of time, you're just pushing template representing your object, scope and controller do most of job that why a jquery lite is enough, DOM manipulation, I mean select/append/copy/animate/play, should be limited.
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

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
This article discusses how to create an extensible mechanism for linked drop downs.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

743 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

17 Experts available now in Live!

Get 1:1 Help Now