uploade image to mysql data base failure - php

hey i have following codes:
index.php
select.php
and you can also find whole project in GitHub (simple-online-library)
which works fine and save bookname bookauthor bookpages in mysql database but its just save image name and image path in database i just want to move image in to new folder called images and try several ways but none of them works for me.

Should be fixed as below
<?php
require_once("db.php");
$file = addslashes(file_get_contents($_FILES["images"]["tmp_name"]));
$sql = "INSERT INTO test1(name, lastname, age , images) VALUES('".$_POST["name"]."', '".$_POST["lastname"]."', '".$_POST["age"]."', '".$file."')";
if(mysqli_query($connect, $sql))
{
echo 'infos saved';
}
?>
UPDATE
your AJAX script only sending filename, not the image. Correct JS should be similar to one below.
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// do something ex. $('#loading').hide();
}
});

Related

external PHP echo in a local HTML file

I have an external PHP, located on a hosting server. The app that I want to build is using Cordova, so I have a HTML on my phone local storage. I have a login form that POSTS to that external php the name and the password of the user. I want that when I click on submit, to stay on my current page, and display the values recieved by the PHP below the form, in a <p> or <h1> tag.
I will be grateful if you can help me with this.
You can make use of Ajax to get the content/data to your view from an external file.
You will need jQuery to use $.ajax().
//Get form Data
var form_data = $('#form').serialize();
$.ajax({
url:'http://something.com/dosomthing.php',
type:'POST',
data: form_data,
success:function(data){
// See what data was returned
console.log(data);
if(data.success == "1"){
$('#err-element').html("User Authenticated");
// Fade in new Page
}else{
$('#err-element').html("User Not found");
}
}
});
It is good practice to return a JSON object from your back-end.
if($user_matches){
echo json_encode(["success"=>"1", "OtherInfo"=>"Kitty"]);
}
post the data to the same page using query or something, use post or get variable to store it in a variable and append with javascript.
//post using query
$.ajax({
type: "POST",
data:{ whatyouwant: yourdata }
})
//in php
$data = $_GET['whatyouwant'];
//in javascript
data = '<?php echo $data;?>'; // if it's a string or you can use json_encode for arrays and such
$('#targetDiv').html('<p>'+data+'</p>');

Upload image via Ajax

Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.

Write non form data to xml using php

I am coding a video platform. When anyone sees the video and hit the like button the like should be incremented by one and should be written to xml file - I want to do this with php. And when the like symbol is clicked, the php should not be loaded but it should be executed.
Here is my code:
HTML:
<a href='#' onclick='doLike(id)'><i class='material-icons' style='float:bottom'>thumb_up</i></a>
JavaScript:
function doLike(id){
$.ajax({
type: "POST",
async: true,
url: "likup.php",
cache: false,
contentType: false,
processData: false,
error: function(){alert('Cannot reach file');},
success:
function(){
alert("Saved Successfully");
}
});}
PHP:
error_reporting(E_ALL);
$file = 'xml/shortfilm/filmname.xml';
$xml = simplexml_load_file($file);
$xml->Shortfilm[0]->like= 2;
But I am still unable to achieve what I want.
onclick='doLike(id)'
On click doList(id) will be called. What is id? Is it defined? You need to make sure that this parameter has the correct value. Your doLike does not send the id to the server. You need to send it, otherwise your server will not receive it. Your server, in turn should process the request and save the like into the xml.

Save Variables to Localstorage and then send to Mysql DB

At first sorry for my bad english but i hope you will understand my request.
Im working on a Phonegap App. User can buy via an payment provider a vip Status. I would like to work with local storage and mysql but im stuck with problems because of missing knowledge of mine. I googled a lot but because everything is on english its really hard for me to learn things.
What i want is, that on the first app start on the phone after download the application generates an random unique username or numeric value and saves it on the local storage as variable. Also it should save a variable called "vip" to the local storage and set it to 0. And it needs to check if the variables are already set, then the application need nothing to do.
These to Variables should be send to an mysql table, lets call it "user".
Example: User Table
+---------+-------------+
| username| vip |
+---------+-------------+
A7w893579 0
So the variables are saved on the local storage and in the mysql database.
After the user makes an payment over the payment provider the variable "vip" needed to set to 1 and fetch it to the right username and saves the 1 into the vip row for the user on the user table.
And i need any way to do a function like: If the vip status is 1 show in a iframe vip.html on a site. If its 0 show novip.html on the site.
Have you any ideas how i can do that? I read something about Ajax Calls but i dont understand it right. If somebody have a few code snippets i would be very thank full. I dont need full code i just need to read it and try to understand.
Thank you!
I am not sure how your view is but you can follow these steps to do what you want.
Load Cordova properly when application get started. Fire onDeviceReady
Calculate your username, any random combination and save them in localStorage
Send username and vip status via ajax call to your php server
Depending upon your server response show user iframe i.e vip.html or novip.html
Step 1:
Load all required features of cordova with the help of below code.
// this call and loads all cordova function which are required.
//Device ready is fired when it is loaded successfully.
document.addEventListener("deviceready", onDeviceReady, true);
// Handle what your application wants to do first
// Save username and vip status, call ajax using to php server
function onDeviceReady() {
var username="calculate username";
var vipStatus=0; //or 1
}
Step 2: Store data in localstorage. There are two ways to use localstorage. Native cordova way of doing.
// set value
window.localStorage.setItem("key", "value");
// get value back
var value = window.localStorage.getItem("key");
But what i prefer to do directly store in localStorage i dont use key value pair. Its easy to store and access.
//store in localStorage
localStorage.vipStatus=0; // or 1
// to get back the value
var Status=localStorage.vipStatus;
Step 3: Make ajax call to your php server. Refer Jquery Ajax here sample code is below
$.ajax({
type: "POST",
url: "http://localhost:3001/",
dataType: 'json',
data: JsonData,
async: false,
crossDomain: true,
success: function(data) {
alert('success');
},
error: function(response, text, err) {
alert(err);
}
});
Step 4: Display proper page as per vip status
I think you need to implement all the things at the start so you should implement them in onDeviceReady as below
document.addEventListener("deviceready", onDeviceReady, true);
// Handle what your application wants to do first
// Save username and vip status, call ajax using to php server
function onDeviceReady() {
// calculate username
var username = "calculate username";
// set status
var vipStatus = 0; //or 1.
// store in localstorage
localStorage.vipStatus = vipStatus;
// set up json i.e send username and vipstatus to server
// make ajax call
$.ajax({
type: "POST",
url: "http://localhost:3001/",
dataType: 'json',
data: JsonData,
async: false,
crossDomain: true,
success: function(data) {
alert('success');
if (status == 0) {
// its 0 so show novip.html
window.location.href = "novip.html";
} else {
//its 1 so show vip.html
window.location.href = "vip.html";
}
},
error: function(response, text, err) {
alert(err);
}
});
}

Reading blob data using PHP and JavaScript

I have an application where a user is allowed to save some text data into a MYSQL database through a web interface. In addition, they can also attach a file to this text and I save this into a blob field. The file types that get attached are simple .txt files.
I am able to save this data into the database but I am having trouble retrieving it. This is what I am doing to retrieve it right now:
//Events that take place when trying to retreive an attached file
function getFile(rowid){
//Make an AJAX Request to fetch the file
$.ajax({
type: 'get',
url: 'point-of-contact.php',
data: 'page=attachment&row='+rowid,
dataType: 'text',
success: function(data) {
console.log (data);
}
});
}
The AJAX request above leads to the following PHP code:
$attachments = $poc -> getPOC($_GET['row']);
header('Content-type: text/plain');
echo $attachments;
The problem I face is that when I console log the data received from the AJAX request I get this:
How do I go about getting the data in simple text format?
Could it be that the way I am uploading the file to the database is incorrect? This is how the file is uploaded to the DB:
//File upload code
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
//Hide the save button
$("#save-button-1").hide();
//Make the AJAX request
$.ajax({
type: 'post',
url: 'point-of-contact.php?page=add',
data: 'point_of_contact=' + $("#textarea1").val() + '&point_of_contact_attachment=' + file,
success: function(data) {
$('#done-1').show();
setTimeout(function() {
$('#done-1').fadeOut();
}, 2500);
$('.loader').fadeOut();
}
});
There is problem in your upload section. The line
var file = fileInput.files[0];
assignes file object into file variable. Later, when you add it to
"point_of_contact_attachment="
it gets converted to string. So you will have
"point_of_contact_attachment=[object file]"
And that is it.
try pointing the browser directly to the file instead of using ajax.
Like this
document.location = point-of-contact.php?page=attachment&row='+rowid;
Since it is not a file the browser can read, it will just download it.
However you will still need to get the TXT via ajax, because document.location redirect to the user to a plain text page.

Categories