Currently I am using MySQLi to parse a CSV file into a Database, that step has been accomplished. However, My next step would be to make this Database searchable and automatically updated via jQuery.ajax().
Some people suggest that I print out the Database in another page and access it externally.
I'm quite new to jquery + ajax so if anyone could point me in the right direction that would be greatly appreciated.
I understand that the documentation on ajax should be enough to tell me what I'm looking for but it appears to talk only about retrieving data from an external file, what about from a mysql database?
The code so far stands:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<input type="text" id="search" name="search" />
<input type="submit" value="submit">
<?php
show_source(__FILE__);
error_reporting(E_ALL);ini_set('display_errors', '1');
$category = NULL;
$mc = new Memcache;
$mc->addServer('localhost','11211');
$sql = new mysqli('localhost', 'user', 'pword', 'db');
$cache = $mc->get("updated_DB");
$query = 'SELECT cat,name,web,kw FROM infoDB WHERE cat LIKE ? OR name LIKE ? OR web LIKE ? OR kw LIKE ?';
$results = $sql->prepare($query);
$results->bind_param('ssss', $query, $query, $query, $query);
$results->execute();
$results->store_result();
?>
</body>
</html>
I understand that the documentation on ajax should be enough to tell me what I'm looking for but it appears to talk only about retrieving data from an external file, what about from a mysql database?
Close. It fetches data from a URI. You need to provide a URI that the data can be requested from (so you need a server side script to get the data from the database and expose it over HTTP — you can't talk directly to the database from the browser).
You have got your data already, so you just need to write views for it.
Usually, people will write an HTML view first so they can build on something that works.
Then you just need to write an alternative view that generates data in a fashion that is easy to parse with JavaScript. JSON is popular, and PHP comes with facilities for generating JSON output.
jQuery will set an X-Requested-By header that you can use to choose between returning HTML or JSON output.
Related
I've created a classification model using AutoML Vision and tried to use this tutorial to make a small web app to make the model classify an image using the browser.
The code I'm using is basically the same as the tutorial with some slight changes:
<script src="https://unpkg.com/#tensorflow/tfjs"></script>
<script src="https://unpkg.com/#tensorflow/tfjs-automl"></script>
<img id="test" crossorigin="anonymous" src="101_SI_24_23-01-2019_iOS_1187.JPG">
<script>
async function run() {
const model = await tf.automl.loadImageClassification('model.json');
const image = document.getElementById('test');
const predictions = await model.classify(image);
console.log(predictions);
// Show the resulting object on the page.
const pre = document.createElement('pre');
pre.textContent = JSON.stringify(predictions, null, 2);
document.body.append(pre);
}
run();
This index.html file above is located in the same folder of the model files and the image file. The problem is that when I try to run the file I'm receiving this error:
error received
I have no idea what I should do to fix this error. I've tried many things without success, I've only changed the error.
models built with AutoML should not have dynamic ops, but seems that yours does.
if that is truly model designed using AutoML, then AutoML should be expanded to use asynchronous execution.
if model was your own (not AutoML), it would be a simple await model.executeAsync() instead of model.execute(), but in AutoML case, that part is hidden inside AutoML library module inside classify call and that needs to be addressed by tfjs AutoML team.
best to open an issue at https://github.com/tensorflow/tfjs/issues
btw, why post a link to an image containing error message instead of copying the message as text here??
I need to upload image and video files to the server in an Angular application using Laravel 5.1 as the back end. All Ajax requests need to go to the Laravel controller first, and we have the code there for how the file gets handled when it gets there. We have previously done normal HTML forms to submit file uploads to the controller, but in this case we need to avoid the page refresh of a form, so I am attempting this in Ajax through Angular.
What information do I need to send to the Laravel controller with Ajax that was being sent to the controller via an HTML form previously?
This is the code in the Laravel controller that handled the file information once it got there. That's what I need to figure out how to send, so I can hopefully reuse this code:
$promotion = Promotion::find($id);
if (Input::hasFile('img_path')){
$path = public_path().'/images/promotion/'.$id.'/';
$file_path = $path.'promotion.png';
$delete = File::delete($file_path);
$file = Input::file('img_path');
$uploadSuccess = $file->move($path, 'promotion.png');
$promotion->img_path = '/images/promotion/'.$id.'/promotion.png';
}
if (Input::hasFile('video_path')){
$path = public_path().'/video/promotion/'.$id.'/';
$file_path = $path.'promotion.mp4';
$delete = File::delete($file_path);
$file = Input::file('video_path');
$uploadSuccess = $file->move($path, 'promotion.mp4');
$promotion->video_path = '/video/promotion/'.$id.'/promotion.mp4';
}
As you can see above, we are converting whatever file we get to a PNG with the file name promotion.png so it's easy to fetch, and we are only accepting .mp4 video format. Because of that, we don't need to worry about checking if the file exists and is it ok to overwrite it. That's why you can see in the code we delete any existing file of that name before saving.
The HTML was just an input with a type of "file:
<input type="file" id="img_path" name="img_path" class="promo-img-path" accept="image/*">
We are using Angular now so I can't just send the above through an HTML form anymore. That's what I need to figure out how to do.
We are two developers just doing our best, so I'm sure there is a better way of doing this. However before I refactor this whole thing, I'm hoping I can use Angular (or jQuery as a last resort) to just send the controller whatever file data Laravel needs in order to make the above code work. The answer may be as simple as "send a PUT to the method in that controller above, but instead of a normal JSON payload, use file info in this format and you can gather that info with..."
I would also appreciate any tips on better ways I can do this in the future.
How to POST FormData Using the $http Service
When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined.
var fd = new FormData()
for (var i in $scope.files) {
fd.append("fileToUpload", $scope.files[i]);
}
var config = {headers: {'Content-Type': undefined}};
var httpPromise = $http.post(url, fd, config);
By default the AngularJS framework uses content type application/json. By setting Content-Type: undefined, the AngularJS framework omits the content type header allowing the XHR API to set the content type. When sending a FormData object, the XHR API sets the content type to multipart/form-data with the proper boundaries and base64 encoding.
For more information, see MDN Web API Reference - XHR Send method
How did you get the file information into $scope.files?
How to enable <input type="file"> to work with ng-model
This directive also enables <input type="file"> to automatically work with the ng-change and ng-form directives.
angular.module("app",[]);
angular.module("app").directive("selectFilesNg", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-files-ng ng-model="fileArray" multiple>
<code><table ng-show="fileArray.length">
<tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
<tr ng-repeat="file in fileArray">
<td>{{file.name}}</td>
<td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td>
<td>{{file.size}}</td>
<td>{{file.type}}</td>
</tr>
</table></code>
</body>
RECOMMENDED: POST Binary Files Directly
Posting binary files with multi-part/form-data is inefficient as the base64 encoding adds an extra 33% overhead. If the server API accepts POSTs with binary data, post the file directly.
See How to POST binary files with AngularJS (with DEMO)
Firstly, I am new to Spring MVC and I am really sorry if this seems like a duplicated question however I am struggling to find a break down guide/tutorial on how to display images on a JSP page after receiving them as blobs from the database. Most of the responses I've read just give you small snippets which confuse me more.
I have a MySQL DB which has a table full of images stored as blobs. I have a Service which retrieves the blob images from the database and populates an arrays of CommonsMultipartFile. I also have a Controller which passes the array to the JSP page where a loop iterates over each image which I'm trying to display.
CONTROLLER
#RequestMapping(value = { "/my/images" }, method = RequestMethod.GET)
public String getAllImages(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
final List<CommonsMultipartFile> images = new ArrayList<CommonsMultipartFile>();
myService.getAllImages(images);
model.addAttribute("myImages", images );
return getUrl(request);
}
JSP
<c:forEach items="${myImages}" var="image">
<img src="${image}">
</c:forEach>
This is as far as I got. The images are not displaying. Please can someone help?
Many Thanks in advance!
The best is to save those binary-files to harddisk (using pk as filename) and directly serve them to the browser.
You can write a Servlet too but its quite hard to write asynchron Servlets.
I have searched the internet for a way to use our history database on our drupal 7 site. I have a database built with names, marriage dates, etc. I would like to have a basic page to do a search. I found a site that helped with the code, but it is not working. I am not a programmer, but I can follow directions. Here is the code I have:
On a basic page using php code as my input format,
<html>
<body>
<script language=”javascript” type=”text/javascript”>
<!–
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e) {
try{
ajaxRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e){
// Something went wrong
alert(“Your browser broke!”);
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var lastphp = document.getElementById("lastphp").value;
var queryString = “?lastphp=” + lastphp;
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
ajaxRequest.send(null);
}
//–>
</script>
<form name="myForm">
<table border=”0″>
<tr>
<td width = 100>Last Name: <br /></td>
<td><input type="text" id="lastphp"> </td>
</tr>
</table>
<br />
<input type="button" onclick="ajaxFunction()" value="Search" />
</form>
<div id="ajaxDiv"></div>
</body>
</html>
Then, I created a php file:
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","root","") or die('Cannot connect to the database because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db(“genealogy”) or die(“Unable to select database”); //select which database we’re using
// Retrieve data from Query String
$last = $_GET['lastphp'];
// Escape User Input to help prevent SQL Injection
$last = mysql_real_escape_string($last);
//Build and run a SQL Query on our MySQL tutorial
$query = “SELECT * from columbus_ledger_enquirer_obituary_db”; //just grab every row from our table
$results = mysql_query($query)or die(mysql_error());
//print what the user entered (eventually I’m sure you’ll want to use this data in your query)
echo “You Entered: ” . $last . “<br><br>”;
//print the results
echo “Database Results: <br>”;
while($row = mysql_fetch_array($results)){
echo “$row[lastname]<br>”; //NOTE: Here we are printing all the data from the ‘lastname’ column of our database, either change this name, or make sure you have a lastname column with some data in it
}
?>
I placed the php file in a folder called php under /sites/default.
The basic page has a nice box and search button, but when I type in a name, nothing happens.
Can anyone here tell me what's wrong?
Thanks
As #SpaceBeers mentions this is really not a good way to do this kind of thing in Drupal (Google "bootstrapping Drupal" or "access custom database in Drupal" for some ideas).
The reason your code probably isn't working, though, is because you're calling your AJAX in using the following code:
ajaxRequest.open(“GET”, “/php/check.php” + queryString, true);
The problem is in the path...you mention you've put your "php" folder in '/sites/all', so surely the path from your AJAX call needs to be the same:
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);
These days "there is a module for it" (to query external databases in formats such as Oracle, MS SQL, Postgress, SQLite, or just any PDO compliant format). It's the Forena module (disclosure: I'm a co-maintainer of it).
Head over to its demo site to see it as work, and refer to its community docu for way more details. Here is a quote from its docu:
... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.
Quick question about CI.
I have a view with a form, several text input fields and a file upload.
I want to be able to take the input from the text fields, save it to the DB, and then upload the image.
I've achieved this by having the upload code in a controller, and if the upload is successful, a call to my Model is made to update the database.
Is this "best practice", or indeed an acceptable way of doing it? Or should the File Upload go in the Model. Does it matter?
Essentially my code is:
function edit_category()
{
$config['upload_path'] = 'images/category/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '300';
$config['max_height'] = '300';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$this->session->set_flashdata('status', $this->upload->display_errors());
redirect('admin/category/edit/'.$this->input->post('catID'), 'location');
}
else /*no errors, upload is successful..*/
{
$fInfo = $this->upload->data();
//$this->_createThumbnail($fInfo['file_name']);
//process form POST data.
$data = array(
'catName' => $this->input->post('catName'),
'catDesc' => $this->input->post('catDesc'),
'catImage' => $fInfo['file_name']
);
/* update the database */
$category = $this->category_model->edit_category($data, $this->input->post('catID'));
I would put this in a model because I like to keep my controllers as slim as possible. I think of the controller as the link between the views and the back-room processing, not the processing itself.
I'm not sure if this is "best practise" or not. It will certainly work the way you're doing it too. CodeIgniter allows you to be quite flexible in how you apply mvc theory.
Use your models to interact with data whether it's a database interaction, an api call, or a file upload and download. Use your controller to run the show and make calls to that data. Do your best to keep them all separate in case the method for interacting with that data ever changes. Most of the time we think of the model as a database function, but it really should be ANY data no matter how it's retrieved.
I came out with this same dilemma, should I put the file upload functionality in controller or model.
After few trial and error I decided to put it under model for reusable purposes as calling controller from another controller is against the MVC concept.