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

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!

Related

Update a variable without refresh in PHP

I need to update a variable named $count (in the below code) automatically. When my database update, $count be update immediately because i need to use value of $count in android app so i can't refresh count.php file every time.
<?php
$con=mysql_connect("","","");
mysql_select_db("u607509006_bd1",$con);
$query = "select * from content where status='a'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
echo $count;
mysql_close($con);
?>
Just use a Jquery Ajax Request on the client side like so:
$.ajax({
url: "path/to/code/file.php" // change this to your path to your code
}).done(function(data) {
// This is executed after the ajax request is complete
// data should be the updated value. You can also return other data // types e.g. JOSN
$('#counter').text(data);
});
JS Fiddle Example: https://jsfiddle.net/anik786/nvkdLhv2/2/

Assign ajax Response Values to PHP Variables

I'm calling ajax from AddSomething.php file as follows
<script>
var dataValue;
$("#schedule").change(function () {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST',
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
dataValue = data;
console.log(dataValue);
}
});
});
</script>
Getting response in Network as follows
[{
"id": "2",
"scheduleName": "abc",
"subject": "Patho",
"university": "xyz",
"facultyName": "Dr",
"scheduleStartDate": "2015-06-05",
"scheduleEndDate": "2015-06-09"
}]
And in console it is showing [Object]
How can I assign the above values to the following PHP variables present in the same page
<?php
$scheduleStartDate ='';//Here How can i assign respected ajax responsevalue
$scheduleEndDate = '';//Here How can i assign respected ajax response value
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''//Here How can i assign value
ORDER BY `university` DESC,student_name ASC";
?>
processClg.php file code
<?php
include "config.php";
$qry = "SELECT * FROM `schedule` WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link, $qry);
//echo $res;
while($row = mysqli_fetch_assoc($res))
$test[] = $row;
echo json_encode($test);
?>
You can't assign the result of an Ajax call to PHP variables. The PHP has already run on the server, done it's bit and sent the HTML / JavaScript to the browser. At that point you can no longer use PHP as it's a server side language and will only run on the server. Ajax uses JavaScript, which is a client side language. It only runs after the PHP has finished and the server has sent the HTML / JavaScript to the users browser. JavaScript is executed in the clients browser.
You need to rethink what you're doing and where you're doing it. If you need the results of the Ajax call to do something in PHP then do it in your processClg.php file. You do all your PHP first, then send a response to the browser to display something to the user. If the user doesn't need any sort of confirmation or acknowledgement then you can just send the Ajax request and not bother with a response.
It looks like you're trying to dynamically load some University information. What you should do is put this part:
$scheduleStartDate ='';//Here How can i assign respected ajax responsevalue
$scheduleEndDate = '';//Here How can i assign respected ajax response value
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''//Here How can i assign value
ORDER BY `university` DESC,student_name ASC";
into processClg.php after the first query. Then you get the results of the query and pass them back to your HTML page, like this:
$results = array();
$qry = "SELECT * FROM `mytable`
WHERE `university` LIKE ''
ORDER BY `university` DESC,student_name ASC";
$result = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
echo json_encode($results);
You can store ajax result in php variable by embedding ajax result div into php tag
<?php
$result='<div id="result"></div>';// Here you embed div in php tag and store in php varible
?>
You cann't do this job as you think the way.
For that , you need to assign the return values to any hidden field form value and submit the form.
Also keep in mind for ajax response data keep in the js variable, you need to pass the parameter async:false

Parse JSON object created by a PDO statement

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.

Returning JSON not working properly

I am trying to return data from a database and convert it into json and send it back to my javascript. However its not working as planned, it returns as an array on the javascript.
Javascript
function getData(id) {
$.ajax({
url: 'some url',
crossDomain: true,
type: 'post',
data: {
id: id
},
success: function (data) {
var json = jQuery.parseJSON(data);
alert(data);
},
});
};
PHP
<?php
header("access-control-allow-origin: *");
$dbhost = 'you dont need this info';
$dbuser = 'you dont need this info';
$dbpass = 'you dont need this info';
$db = 'you dont need this info';
$dbserver = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db) or die("Unable to select database: " . mysql_error());
if (isset($_POST['id'])) {
$ID = $_POST['id'];
}
echo $ID;
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "' . $ID . '"');
$row = mysql_fetch_assoc($result);
$name = $row['name'];
$clubID = $row['clubID'];
$lID = $row['lID'];
$sName = $row['sName'];
$desc = $row['description'];
$json = json_encode(array(
'name' => $name,
'clubID' => $clubID,
'lID' => $lID,
'sName' => $sName,
'description' => $desc
));
echo $json;
?>
The javascript alerts in the form of [object Object], [object Object] ...
Which shouldn't be the case...
Don't echo $ID in your PHP. Use jQuery's ajax dataType property and set it to json. Use default javascript json parser.
try alerting json rather than data?
Javascript returns an object because you are in fact alerting an object. Try alert(data.name);
or alert(data.clubID);, it will work.
You should specify the data type that the ajax call is requesting, otherwise jQuery will "intelligently" detect based on the MIME type. If the ajax call receives json data, it will use it as a JavaScript object, which is why you are getting that alert.
That is right.
The JSON is an object. a.k.a Javascript Object Notation. That should be in case.
It should contain your data. Try data.*.
By the way, if you don't clear the data coming from your users before using it with any SQL Query, that will cause trouble.
See it in action with a basic example:
// $_POST['id'] = '" OR 1"'
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "'.$ID.'"');
Your query is now
SELECT * FROM clubmember WHERE clubID ="" OR 1 ""
Because 1 is always true, I am now able to take all of your clubmember table. Cheers.
Even if parseJSON returns an object, doing a console.log should show [Object, Object, ...] which is an array of object
The .ajax() call will, if the dataType parameter is not given, "intelligently guess" what the requested page returns. In the case of JSON, it will pass a JavaScript object to the success function.
After reviewing your question(s), I believe I get what you mean.
What you're expecting is a single object (looked up with SQL, as mentioned in a very insecure way) with 5 properties, name, clubID, lID, sName and description.
However, it seems that what you're getting back are multiple rows with only two properties?
What you're saying is that while the php script echo's the right values (one row) but JSON is receiving multiple values(/rows). Are you sure the PHP is receiving the right ID from the AJAX call?

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