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
Related
I have the data that want sent to backend, its look like
function lihat(){
let id = "12345678";
let profile = [{name:"dave", department : "Engginering"},
{name:"Tedd", department : "Engginering"}]
$.ajax({
type:'POST',
url:'pages/dashboard/dashboard_be.php'
data:{
cekload : true,
keys : id,
dataList : profile
},
success:function(data){
console.log(data);
}
})
the question, how can I receive all of datas sent by ajax in php script
this what I've tried
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'];);
//I wanna parsing the dataList object and then loop it, how to make it ?
thanks, before
If you're trying to send/receive javascript objects, you need to convert the object to a string before sending and decode it back in php (into an array maybe) before reading.
<script>
let id = "12345678";
let profile = [{name:"dave", department : "Engginering"},
{name:"Tedd", department : "Engginering"}]
$.ajax({
type:'POST',
url:'pages/dashboard/dashboard_be.php',
data:{
cekload : true,
keys : id,
dataList : JSON.stringify(profile)
},
success:function(data){
console.log(data);
}
});
</script>
PHP code:
<?php
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'], true);
echo $id;
echo $cekload;
print_r($data);
?>
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);
}
}
}
});
});
I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";
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
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