Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, March 5, 2019

Ajax: Simplest json call

The simplest of all:

var url = 'http://test.com/php/getnews.php';

  $.getJSON(url, function(result) {
    console.log(result);
    $.each(result, function(i, field) {
      console.log(i + ':' + field.title);
    });
  });

and the corresponding php on the server:

$query = "SELECT * FROM news";
  $rows = array();

  if($result = mysqli_query($link, $query)) {
      while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
      }
   
      header('Content-Type: application/json');
      print json_encode($rows,
      JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_FORCE_OBJECT );
   
  }

Monday, March 4, 2019

Ajax with Cross Domain


Another ajax example:


var url = 'http://test.com/php/getnews.php';


$.ajax({
   type: 'GET',
   url: url,
   crossDomain: true,
   cache: false,
   success: function(result) {

        / / var obj = $.parseJSON(result[0]);
        console.log(result);
 
         $.each(result, function(i, field) {
              console.log(i + ':' + field.title);
         });
     }
});

Fetching Blobs from MySQL

Here is the php script to fetch blob from MySQL database:


<?php

  header('Access-Control-Allow-Origin: *');

  $link = mysqli_connect("host","username","passwd", "database");

  mysqli_set_charset($link, "utf8");

  if(mysqli_connect_error()) {
    die("There was an error");
  }

  $query = "SELECT pic FROM news WHERE id=1";

  $rows = array();

  if($result = mysqli_query($link, $query)) {
      while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
      }
      echo '<img src="data:image/jpeg;base64,'.base64_encode( $rows[0]['pic'] ).'"/>';
  }

?>

Wednesday, February 27, 2019

How to create your own Web API using PHP and access it using a PhoneGap app

In this tutorial, we will create a simple end-to-end system consisting of MySQL database and also a php script to access the database with some simple API. Then, we will create a simple PhoneGap app to access the Database via the API.

Start HTTP web server and MySQL server of your xamp app. Then using phpmyadmin create a table consisting of:


Also, populate the table with some data as shown above.

In the xamp folder's htdocs folder, create a subfolder mysql and create a new file called jsonencode.php :

<?php
// This one is working
// The client is Phonegap app: PHP API Client
header('Access-Control-Allow-Origin: *');
$link = mysqli_connect("localhost","myuser","mypassword", "paul");
if(mysqli_connect_error()) {
die("There was an error");
}

//$query = "SELECT * FROM users";
$query = "SELECT * FROM users WHERE name = '".$_GET['name']."'";

$rows = array();

if($result = mysqli_query($link, $query)) {
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
}

?>

Create a client PhoneGap app called PHP API Client containing 2 files: index.html and app.js.

index.html :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"
/>
<title>Blank App</title>
<link
rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"
/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-position="fixed">
<h1>PHP Client</h1>
<div class="searchform" style="padding:6px">
<label for="text-basic">Enter Name:</label>
<input
type="search"
name="text-basic"
id="txtinputname"
value=""
placeholder="Enter Name"
/>
<input
type="button"
value="Search"
data-icon="search"
id="btnsearch"
/>
</div>
</div>
<div role="main" class="ui-content centered">
<div id="result">Search Results...</div>
<br />
<div id="list">
<ul data-role="listview" id="resultlist"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<h2>by PHP API Client Crew</h2>
</div>
</div>

<!-- <script type="text/javascript" src="cordova.js"></script> -->
<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js:

$('#btnsearch').click(function() {
var name = $('#txtinputname')
.val()
.toLowerCase();
console.log(name);
var url = 'http://192.168.137.84/mysql/jsonencode.php?name=' + name;
console.log(url);
//clear the listview
$('#list').html("<ul data-role='listview' id='resultlist'></ul>");

$.ajax(url)
.done(function(data) {
var obj = JSON.parse(data);
console.log(data);
//console.log(obj[0].name);
var output = '';
if (obj[0]) {
obj.forEach(function(record) {
console.log(record.name);
output +=
'<li>id: ' +
record.id +
' Name: ' +
record.name +
' email: ' +
record.email +
'</li>';
});
} else {
output += '<li>Not Found</li>';
}

$('#resultlist').append(output);
$('#resultlist')
.listview()
.listview('refresh');
})
.fail(function() {
$('#result').html(name + ' not found!');
});
});

The index.html will refer to the app.js

Then Run the PhoneGap app using PhoneGap Desktop App and connect to it with a Browser and try to access some record by keying in  a name: