Data Saving: Write to MySQL Database with Ajax and Json - javascript

I am total lost. What is wrong? I try to INSERT INTO mysql.
It add a row in MySQL , but it does not fill in data.
I am sitting since some days on it and dont understand it. I checked hundreds of web pages.
How can I send data to the PHP part? What is wrong in this code?
...
Here is the full code:
Javascript:
function jsRecordInsertWrite()
{
var jsObject = {
"ID": document.form_articles.ID.value,
"Item": document.form_articles.Item.value,
"ItemNo": document.form_articles.ItemNo.value,
"Material": document.form_articles.Material.value,
"Age": document.form_articles.Age.value,
"ItemSize": document.form_articles.ItemSize.value,
"Price": document.form_articles.Price.value,
"Info": document.form_articles.Info.value,
"InfoRed": document.form_articles.InfoRed.value,
"ArrivalDate": document.form_articles.ArrivalDate.value,
"ArrivalDateShown": document.form_articles.ArrivalDateShown.value,
"MainPicLink": document.form_articles.MainPicLink.value,
"ItemCondition": document.form_articles.ItemCondition.value,
"ItemTimestamp": document.form_articles.ItemTimestamp.value,
"ItemCategory": document.form_articles.ItemCategory.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'insertarticle.php',
dataType : 'json',
contentType: 'application/json; charset=UTF-8',
// This is the money shot
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
insertarticle.php
<?php
$link = mysql_connect('localhost', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//read the json file contents
$ID = $_POST['ID'];
$Item = $_POST['Item'];
$ItemNo = $_POST['ItemNo'];
$Material = $_POST['Material'];
$Age = $_POST['Age'];
$ItemSize = $_POST['ItemSize'];
$Price = $_POST['Price'];
$Info = $_POST['Info'];
$InfoRed = $_POST['InfoRed'];
$ArrivalDate = $_POST['ArrivalDate'];
$ArrivalDateShown = $_POST['ArrivalDateShown'];
$MainPicLink = $_POST['MainPicLink'];
$ItemCondition = $_POST['ItemCondition'];
$ItemTimestamp = $_POST['timestamp'];
$ItemCategory = $_POST['ItemCategory'];
//insert into mysql table
$sql = "INSERT INTO articles(ID, Item, ItemNo, Material, Age, ItemSize,
Price, Info, InfoRed, ArrivalDate, ArrivalDateShown, MainPicLink,
ItemCondition, ItemTimestamp, ItemCategory)
VALUES(NULL,'$Item','$ItemNo','$Material','$Age',
'$ItemSize','$Price','$Info','$InfoRed','$ArrivalDate',
'$ArrivalDateShown','$MainPicLink','$ItemCondition',
'$ItemTimestamp','$ItemCategory')";
if(!mysql_query($sql))
{
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
//}
?>
//+++++++++++++++++++++++++++++++++++++++++++++++++
//The first NULL is for autoincrement ID,
//the other NULL is for automatic timestamp

Related

How to upload an image to server directory using ajax?

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...');
};
?>

Little problem with ajax. Error-function is executed

i have a little problem with ajax and mysql.
I want to save same data to a database via ajax.
Javascript:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item : nr, var : text },
success: function(result_save){
if (result_save.includes('Error')) {
alert("!!! Error !!!");
}
},
error: function(xhr, textStatus, errorThrown) {
alert("!!! Error !!!");
}
});
My PHP-File looks like:
PHP:
<?php
require "config.inc.php";
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die ('Error');
$db->set_charset("utf8");
$sql="INSERT INTO tbl (item, var) VALUES ('$_POST[item]','$_POST[var]')";
if (!mysqli_query($db,$sql))
{
return 'Error';
die();
}
mysql_close($db);
return 'i.O.';
?>
It saves to the database, but the error-function of ajax is executed every time. What is wrong?
A few observations:
jcubic is correct- you don't want to use a JS keyword as a parameter name.
catcon is also correct. Using a prepared statement is FAR preferable to reading the variable directly into your SQL text.
Even if mysqli_query() returns 0, you still want to do a mysql_close($db), don't you?
You would also like to know the specific error, wouldn't you?
SUGGESTION:
PHP:
<?php
require "config.inc.php";
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO tbl (item, var) VALUES (?, ?)");
$stmt->bind_param("is", $_POST[item_id], $_POST[item_value]);
if (!$stmt->execute()) {
$result = "Execute failed: (" . $stmt->errno . "): " . $stmt->error;
}
$stmt->close();
$conn->close();
return ($result) ? 'Success' : $result;
...
JS:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item_id: nr, item_value: text },
success: function(result_save){
if (result_save === 'Success') {
console.log('Insert was successful', nr, value);
} else {
alert('mySql Error: ', JSON.stringify(result_save));
}
},
error: function(xhr, textStatus, errorThrown) {
alert('XHR Exception: ' + textStatus + ', ' + JSON.stringify(errorThrown));
}
});

Retrieve parts of jquery response to populate inputs and selects

I send a jQuery request (incorporating a business_id) to a php file to retrieve all values in the database to populate the fields and selects that are in my form and correspond to this id. However, how am I able to retrieve the response from the database in pieces? So that I can provide the fields and selects that are in the form with the values from the database. My javascript function looks as follows:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response);
}
});
}
});
},
My businessdata.php looks as follows:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo $row['uitgevoerd_door_naam'];
echo $row['hoev_gev_stof_score'];
}
}
mysqli_close($mysqli);
?>
What I want to achieve is:
$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];
etc.....
Fix:
Use json encode:
function:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
dataType: "json",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response.a);
$("#riskpot_scorefield3").val(response.b);
}
});
}
});
},
php file:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}
}
mysqli_close($mysqli);
?>

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
});
});

How can I dynamically post my message in CodeIgniter?

I just want to tell the user either with AngularJS or AJAX or JQuery, or whatever is easiest, that the username and email are already registered.
I already have AngularJS implemented for other checks, just not those that need php.
Here is my php function:
public function user_exists() {
$username = $this->db->escape($this->input->post('username'));
$data = array(
'username' => $username,
'email' => $this->db->escape($this->input->post('email')),
'password' => crypt($this->db->escape($this->input->
post('password'))),
'user_id' => md5('I really like pie, '. $username)
);
$does_user_exist = "SELECT COUNT(`user_id`) FROM `users` WHERE
`username` = " . $data['username'] . " || `email` = " .
$data['email'] . "";
$query = $this->db->query($does_user_exist);
if($query->num_rows() > 0) {
return true;
}
}
Please and thank you.
Why you use $data array in method? To check exists user or not you need use MVC architecture and something like this code.
For model:
class User_Model extends CI_Model
{
public function is_exists($username, $email)
{
$this->db->select('user_id');
$this->db->where(array(
'username' => $username,
'email' => $email
));
$this->db->limit(1);
return $this->db->get('users')->row('user_id');
}
}
This code for controller:
class User extends CI_Controller
{
public function is_exists()
{
$email = $this->input->post('email');
$username = $this->input->post('username');
$this->load->model('user_model');
if(!$this->user_model->is_exists($username, $email))
{
$result = array('status' => 200, 'message' => 'Username and email are free');
}
else
{
$result = array('status' => 400, 'reason' => 'User already exists');
}
echo json_encode($result);
}
}
Ajax query:
$.ajax({
url: 'user/is_exists',
type: 'POST',
dataType: 'JSON',
data: {username: username, email: email},
success: function(data, status, jqXHR){
if(data.status == 200){
alert(data.message);
}
else{
alert(data.reason);
}
}
});
username and email js variables you need get from your regisration form.
Also you can use Ion Auth or Tank Auth extensions
When the user clicks the submit button on the registration form submit it using $.post() in jQuery. The action attribute of the form should map to the appropriate controller/method. The method you call can return a JSON encoded message to display in the browser.
It could look something like this:
$(function() {
$('#registration', 'input[type="submit"]').on('click', function(event) {
event.preventDefault();
var action = $(this).closest('form').attr('action');
var form = $(this).closest('form').serialize();
$.post(action, form, function(data) {
alert(data.message);
});
});
});
In the above example the ID of the form is #registration. The JS var 'data' is the JSON object returned by your PHP method and 'message' is a property of that object containing a message to display to the user.

Categories

Resources