Parse JSON object created by a PDO statement - php

Here is my problem
I looked through Stak overflow and other websites but can't find an answer that solves my actual problem...
I call a php file from an AJAX request, my php file gets data from my db.
I'm making a pdo statement to get data from my db :
//initialize vars such as $db ...
$get = $db->prepare("SELECT * FROM myTable WHERE myTable_id=1");
$get->execute();
echo json_encode($get->fetchAll(PDO::FETCH_ASSOC));
//COLUMNS IN MY TABLE ARE ID, NAME, PHONE, INFO
so that object is returned to my ajax query
BUT I don't know how to fetch this object into my ajax/jquery statement to use its data...
Response from console :
[Object{id="1",name="myname",phone="8888888",info="information"}]
code...
success : function(response){
var id = '';
var name = '';
var phone = '';
var info = '';
}
please tell me how to parse, i tried json.parse(response), but can't display any data from this...
thanx

Do it like this
success : function(response){
var data = JSON.parse(response);
var id = data.id;
var name = data.name;
var phone = data.phone;
var info = data.info;
}
That should do the trick.

Related

Give autonumber Id MySQL back with an AJAX call? [duplicate]

Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!

Ajax post to php to update mysql

I've built an admin page for my site, that contains numerous forms that save, update, delete data into different tables in my database.
Currently i have one PHP file for each function that does the mysql query according to my ajax post command. which is getting a bit out of control.
for example i have a file for saving a new category
$cataddname = $_POST['name'];
$area = $_POST['area'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "INSERT INTO clet_faq_category (id, name, nickname, area) VALUES ('', '$cataddname', '$shortname', '$area')";
mysqli_query($db_connect, $update_category);
my save new category command posts to this file:
then i have a file that saves a category edit:
$cataddname = $_POST['name'];
$area = $_POST['area'];
$id = $_POST['cid'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "UPDATE clet_faq_category SET name='$cataddname', nickname='$shortname', area='$area' WHERE id = '$id'";
mysqli_query($db_connect, $update_category);
And another one to delete a category:
$c_id = $_POST['delete_id'];
$sql_del = "DELETE FROM clet_faq_category WHERE id = '$c_id'";
$del_question = mysqli_query( $db_connect, $sql_del );
then i have an jQuery ajax call that calls the page:
function newcat(){
var id = "answer";
tinymce.execCommand('mceRemoveEditor', true, id);
var category = document.getElementById('newcategory').value;
var area = document.getElementById('area').value;
var dataString = 'name=' + category + '&area=' + area;
$.ajax({
type: "post",
url: "newcat.php?area_id=" + areaid,
data : {
'name': category,
'area': area,
'query' : query
},
cache: false,
success: function(html){
$('#category_table').html(html);
$('#cat-form').text("Category Saved");
}
});
return false;
}
And When you look at them it's pretty much the same thing it's just a mysql query running.
What i'm trying to do is streamline this a little bit, i thought about passing the entire query via ajax to my php file, but that's not an option as anyone that can see my js file will be able to figure out all my queries and table names, and all they need to do is post a query to my php page and damage my entire DB.
so my question is, is there a way to do this in a smarter way maybe creating php functions inside the same file, that has category_delete(), category_add(), category_edit() on the same file and using ajax target each one of those categories, at least all my functions and queries will be on the same spot not in multiple separate files if you know what i mean.
You can do like this create a separate class which perform options for insert delete and update. and on your ajax page call these function like this
$func = new CUD();
switch($_POST['action'])
{
case 'delete':
$func->delete($values..)
case 'update':
$func->update($values..)
case 'delete':
$func->insert($values..)
}
You can have to send extra parameter in ajax as action, this parameter specifies the action
in php
switch($_POST['action'])
{
case 'delete':
.....
}

Insert Data mysql using Ajax and PHP

I am want insert data to MySQL Database using Ajax and PHP
My Ajax Code
$(function(){
$('#submit').click(function(){
var Name = $('#InputName').val();
var Email = $('#InputEmail').val();
var Phone = $('#InputPhone').val();
var Username = $('#InputUser').val();
var Status = $('#selectStatus').val();
//Ajax for add Dealer
$.ajax({
url : "../page/addnewDealer.php",
type : "POST",
async : false,
data :{
Submit:'adduser',
Name : Name,
Email:Email,
Phone:Phone,
UserName:Username,
Status:Status
},
success :function(result){
alert(result);
}
});
});
});
and PHP code is
if(isset($_POST['Submit'])=='adduser')
{
$pass= get_rand_id();
$time= get_currunt_Time();
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
$result = mysql_query($insertData);
}
It is a registration page when i am add a user using this program . program replies success massage but in database nothing happen
change
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
to
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('".$_POST[Username]."','".$pass."','".$_POST[Status]."','".$_POST[Name]."','".$_POST[Phone]."','".$_POST[Email]."','".$time."','".$time."')";
Add braces { } around your $_POST variables in the query. Also, check your spelling of your field names - is "contEmaill" correct? (Two 'l's).
You can simply take post data to a variable and append it to the sql query.

Error passing variable from AJAX to PHP for MySQL query

I am getting an error when trying to pass a variable from AJAX to PHP for a MySQL query. I have tried hardcoding to make sure that the query works and it does, but when I try to dynamically pass the variable it is telling me the following "Error: Unknown column '$searchid' in 'where clause'". I am trying to send the value of a dropdown box to ajax to pull back data from a MySQL database. The returned data will then be put into 2 text boxes to be edited. Note: I am trying not to use the jQuery framework for this so I can get a better understanding of what the AJAX is actually doing.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
It's been a while since I have had time to work with code so I believe everything I used is still relevant. Also I know I havent put any sanitizing in yet, I wanted to make sure I can get the function working first, and I am the only one with access currently.
Thanks in advance for any help.
To solve your immediate issue, you'll want to change this:
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
Into this:
$sql = "SELECT * FROM orginfo WHERE id = $searchid";
Since your string is in single quotes, it is literally passing the string '$searchid' into the query rather than the value of $searchid.

Returning a JSON object from PHP in AJAX call?

Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!

Categories