How to upload an image to server directory using ajax? - javascript

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.

You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});

If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

Related

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

sending jquery string via AJAX and saving it to html file using PHP

I am trying to send a string via AJAX to a PHP file. I have two lottery wheels, each of them has a result (if you press on "spin"). I wish to receive the results and print them to an HTML file. Please see here:
http://zeevm.co.il/rollet/
This is the AJAX code that is sending the first wheels result:
function sendwinnertophp(){
var winner = $("#winner").html();
$.ajax({
type: "POST",
url: "getwinner.php",
data: {
"winner": winner
},
cache: false,
success: function(data){
// alert(data);
},
error: function(err){
alert(err);
}
});
}
This is the PHP code that is saving it to the HTML file:
$file = fopen("log.html", "a");
$ip=$_SERVER['REMOTE_ADDR'];
$winner = $_POST['winner'];
//write the data
$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/><b>ip:</b> $ip<br/><b>score:</b> $winner<br/><hr/>" );
fclose( $file );
But, I have two wheels that each of them has its own result. I wish to duplicate the Ajax code so it will send the second wheel's result and print it to the HTML file using the PHP.
I have tried adding this after the first function:
function sendwinnertophp222(){
var winner222 = $("#winner222").html();
$.ajax({
type: "POST",
url: "getwinner.php",
data: {
"winner222": winner222
},
cache: false,
success: function(data){
// alert(data);
},
error: function(err){
alert(err);
}
});
}
And this to the PHP file:
$file = fopen("log.html", "a");
$ip=$_SERVER['REMOTE_ADDR'];
$winner = $_POST['winner'];
$winner222 = $_POST['winner222'];
//write the data
$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/><b>ip:</b> $ip<br/><b>score:</b> $winner<br/> $winner222<br/><hr/>" );
fclose( $file );
But it doesn't work.
Instead of Duplicating the same code twice you can simple increse the number of post variables :
function sendwinnertophp(){
var winner = $("#winner").html();
var winner_two = $("#winner222").html();
$.ajax({
type: "POST",
url: "getwinner.php",
data: {
"winner": winner,
"winner_two" : winner_two
},
cache: false,
success: function(data){
// alert(data);
},
error: function(err){
alert(err);
}
});
}
And in PHP File :
$file = fopen("log.html", "a");
$ip=$_SERVER['REMOTE_ADDR'];
$winner = $_POST['winner'];
$winner_two = $_POST['winner_two'];
//write the data
$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/><b>ip:</b> $ip<br/><b>score:</b> $winner<br/><hr/>" );
fwrite($file, "<b>Time:</b> $time<br/><b>ip:</b> $ip<br/><b>score:</b> $winner_two<br/><hr/>" );
fclose( $file );

Return the output of html id to php string

I like to make an advertisement base on the visitor state/region. And also to display language based on visitor country.
I am trying to get data from this website and works well in ( only displaying the output) :
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// example where I update content on the page.
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
}
} );
of course this will give the visitor state data on browser :
<div id="region-name"></div>
Problems :
How can I get the id output save in php string.
I want to ave it to database using PDO prepare statement.
I have tried to save it by doing:
$state='<div id="region-name"></div>';
$pages->testsavestate($state); // save to database PDO
public function testsavestate($state) {
$ses_id = session_id();
$country='mycountry';
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES
(?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
It didn't save the state result, but only the above the tag.
Thanks
In order for that data to travel from your first AJAX call to get location values. You can also call another ajax on top of that to your PHP processing. Consider this example:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
// after your .html() below
// after your successful ajax outside, call your php file
var country = location.country_name;
var state = location.region_name;
// call your php file
jQuery.ajax({
url: 'index.php', // <-- name of the php file that will handle such request
type: 'POST',
dataType: 'JSON',
data: { country: country, state: state },
success: function(response) {
alert(response);
}
});
}
});
Then on your php file, process the values
if(isset($_POST['save'])) {
$country = $_POST['country'];
$state = $_POST['state'];
$ses_id = session_id();
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES (?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try {
$query->execute();
if($query->rowCount() > 0) {
echo "Save complete!";
exit;
}
} catch(PDOException $e){
die($e->getMessage());
}
}

How to pass the value of php to javascript using ajax

i have an array , which has to be passed from backend to frontend using ajax, i am new to ajax i know the syntax but got stuck , below is my code
backend(PHP)
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$s_res = mysql_query($s_q, $db2);
while($row= mysql_fetch_array($s_res))
{
echo $row['ans'];
}
$result = array('ans' => $row['ans'] );
Javascript code
function get_solution()
{
$.ajax({
url: 'waiting.php',
dataType: 'json',
type: 'GET',
timeout: 30 * 1000,
data: {sol:row},
success: function(json){
$('#saved').html(json.ans);
},
error: function(){}
});
}
i am getting an error in this code data: {sol:row}.
The response data from php is not in json format..
$result = array('ans' => $row['ans'] );
echo json_encode($result);
add this in your php code
Create a JSON on the PHP Side and catch it with $.getJSON jquery
Server Side:
$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());
while($r = mysql_fetch_assoc($result)) {
$row_1[] = $r;
}
$post_data = json_encode(array('ans' => $row_1));
echo $post_data;
Client Side:
$.getJSON("result.php", function(json) {
console.log(json)
$.each( json, function( key, data ) {
//loop through the json if necessary
});
});

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources