Convert form data from json to php mysql - javascript

I am new to json, I have tried to post my form values from json to update mysql database. When I submit I have a success alert but when I view my database seems my values are not been passed through infact leaving my most of my fields blank. Need assistance in passing my form data to my database using json and php.
JAVASCRIPT
$('#save').on('click', function () {
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data: {
detailid: id,
titleid: $('#selectmenu').val(),
name: $('#txtname').val(),
surname: $('#txtsurname').val(),
contact_no: $('#txtcontact_no').val(),
email: $('#txtemail').val(),
category:$('#txtcategory').val(),
package: $('#txtpackage').val(),
password: $('#txtpassword').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
alert("Your details we not saved");
} else {
//alert a success message
alert("Details Updated");
location.href='profiledetails.html?id='+id;
}
}
});
});
PHP
require_once("database.php");
$mydb = new MySQLDatabase();
//set varables from json data
$id = json_decode($_POST['detailid']);
$titleid = json_decode($_POST['titleid']);
$name = json_decode($_POST['name']);
$surname = json_decode($_POST['surname']);
$contact_no = json_decode($_POST['contact_no']);
$email = json_decode($_POST['email']);
$category = json_decode($_POST['category']);
$package = json_decode($_POST['package']);
$password = json_decode($_POST['password']);
$mydb->query("UPDATE tblprofile SET title_fk = '$titleid',`name` = '$name',surname = '$surname',contact_no ='$contact_no',email = '$email',category_fk = '$category',package_fk = 'package_fk' ,`password` = 'password' WHERE id = '$id' ;");
$mydb->close_connection();

No need to decode the data. They will be posted as normal post data. Access them by simply -
$id = $_POST['detailid'];

you dont need to json_decode the value from the $_POST.
change you code to this
$id = $_POST['detailid'];
$titleid = $_POST['titleid'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$contact_no = $_POST['contact_no'];
$email = $_POST['email'];
$category = $_POST['category'];
$package = $_POST['package'];
$password = $_POST['password'];
Although you are sending json via the ajax call but in doesn't come encoded in the server

Unless you send the data in JSON format from client side, don't use json_decode()
Ex:
In ajax call, instead of the data:{}
if you try to send in this way,
var Jdata = JSON.parse("{'detailid':'"+id+"'");
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data:Jdata,
datatype: "json",
success: function (status) {
//your stuff..
}
});
then go for using json_decode() in php

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

retrieve json array from php json decode

i have a javascript to create json array and it has a ajax post method, i have to know how this json array should decode in the php side?
My javascript function:
var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"datee" : "2017-09-09" ,"total" : tot }], invoiceLine: []};
for(i=1; i<=count+arr.length-1; i++){
var ss = String(i);
if(arr.includes(ss)){
continue;
}
invoices.invoiceLine.push({
"itemName" : document.getElementById('item'+i).value ,
"qty" : document.getElementById('inputQty'+i).value ,
"value" : document.getElementById('value'+i).value
});
}
$.ajax({
type: "POST",
url: "saveInvoice.php",
data: {json : JSON.stringify(invoices)},
cache: false,
success: function(data) {
alert(data);
location.reload();
}
});
and this is my php:(it will not save data to the database. I want first invoice data to save in the database for now. Then i can use invoiveLine data to another table inserting.)
$dbhost = "localhost";
$dbuser = "root";
//$dbpass = "dbpassword";
$dbname = "inventory";
$jsonInvoice = json_decode($POST['invoices'],true);
$customerName = $jsonInvoice.["invoice"][0].["customerName"];
$reciptionName = $jsonInvoice.["invoice"][0].["reciptionName"];
$date = $jsonInvoice.["invoice"][0].["datee"];
$total = $jsonInvoice.["invoice"][0].["total"];
mysql_connect($dbhost, $dbuser, '');
mysql_select_db($dbname) or die(mysql_error());
$query = "insert into invoice (customerName,reciptionName,date,total) values ('$customerName','$reciptionName','$date',$total)";
$qry_result = mysql_query($query) or die(mysql_error());
$insertId = mysql_insert_id();
echo $insertId;
Could you try this:
$customerName = $jsonInvoice["invoice"][0]["customerName"];
I think that you are getting sintax errors, caused by dots.
json_decode returns an array, you have to access the attributes in the way that I wrote above. (see this for further info)
Also, take care of the recommendations that other users gave you about mysqli

ajax can i use ajax to send a variable which is use in mysql perform some query then result back to me as return

this is my code for in php file from which i recall a refresh php again nd again its working fine but now i have $id which i get while performing some query now i want to send it refresh.php page where some query will be performed then i get result back as return
function repeatAjax(){
var arrPoints;
$.ajax({
url: 'refresh.php',
cache: false,
success: function(result) {
if(result){
var resultJson = $.parseJSON(result);
refresh_point(resultJson["latitude"],resultJson["longitude"]);
}
}
}); }
this is my refresh.php page
<?php
$hostname_localhost ="localhost";
$database_localhost ="map";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
//i want $id here so i can use it instead of 6
$query_search1 = "SELECT lat ,lng FROM van WHERE id =6";
$query_exec2 = mysql_query($query_search1) or die(mysql_error());
$row = mysql_fetch_assoc($query_exec2);
$row1= $row['lat'];
$row2= $row['lng'];
$advert = array(
'latitude' => $row['lat'],
'longitude' => $row['lng'],
);
echo json_encode($advert);
?>
code is working awesome if i don't want to send some thing to refresh php if i just type id 6 i get the return OK fine but i want to post some thing but how ??
function repeatAjax(){
var arrPoints;
var id = '6';
$.ajax({
url: 'refresh.php',
data: id,
cache: false,
success: function(result) {
if(result){
var resultJson = $.parseJSON(result);
refresh_point(resultJson["latitude"],resultJson["longitude"]);
}
}
});
}
In php file you can recive vairable like below
$id=$_POST['id'];

fetch rows from mysql using Ajax

I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?
to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));
You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck

Categories