Solved

Return data with AJAX, JQUERY and PHP

Posted on 2016-11-29
13
77 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
[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
  • 4
  • 4
  • 3
  • +1
13 Comments
 
LVL 56

Expert Comment

by:Julian Hansen
ID: 41905865
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
ID: 41905910
Thanks man! Congratulation.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41905935
0
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 41905943
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
ID: 41907986
Wow Lvl 82  greats!!
0
 

Author Closing Comment

by:eduardo12fox
ID: 41907987
Thaks man! Very easy
1
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 41908002
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 56

Expert Comment

by:Julian Hansen
ID: 41908213
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
ID: 41908546
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
ID: 41908561
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
ID: 41908602
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 56

Expert Comment

by:Julian Hansen
ID: 41908635
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
ID: 41909105
... 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
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 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 how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

749 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