json_encode prints data in html - javascript

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?

Try to send out the json http header in first place on product.php
header('Content-Type: application/json');

Related

How can i receive more than one responses in ajax in the same function

here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.

Reload data from database without refreshing page

My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?
The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}

Data is obtained in the error function of the ajax

I'm trying to fetch the data from the datatable using ajax in cakephp. I'm sending a data named designation and wanna fetch all the records against that. This is how I've tried:
ajax:
$("#Designation").click(function(){
alert($("#Designation").val());
var data = {
"Designation": $("#Designation").val()
}
$.ajax({
type:"POST",
dataType: "JSON",
url: '<?php echo Router::url(array('controller'=>'DynamicForm','action'=>'getbulkoptions')); ?>',
data:data,
success:function(data){
alert("success");
console.log(data);
if(data.fieldid=="0"){
//MyNotif.Show(data.message,"warning");
alert("Field Exists");
}else{
$("#mymodal").modal('hide');
//MyNotif.Show(data.message,"success");
//window.location.reload();
alert("Bulk List");
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
});
});
This is how I try to communicate with the DB:
DynamicFormController:
<?php
namespace App\Controller;
session_start();
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
class DynamicFormController extends AppController {
public function getbulkoptions(){
$optionvalue = $this->request->data('Designation');
$designation = TableRegistry::get ('Field');
$result = $designation->getbulkoptions($optionvalue);
echo json_encode($result);
}
}
?>
FieldTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class FieldTable extends Table {
var $name = 'FieldTable';
public function getbulkoptions($designation){
$conn = ConnectionManager::get('default');
$stmt = $conn->prepare( "CALL proc_getbulkoptionslist (:tid)");
$stmt->bindValue( ':tid', $designation);
$stmt->execute ();
return $stmt->fetchAll ('obj');
}
}
The thing is, I get a proper response. I get the data I want, but that data is being printed in the error function of the ajax. I want it to be in the success function. I don't know what's wrong with the above code. When I tried to print the error, I got this:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 364 of the JSON data
Stack trace:
n.parseJSON#http://localhost/payrollengine/js/jquery.js:4:16508
Wb#http://localhost/payrollengine/js/jquery.js:4:18828
y#http://localhost/payrollengine/js/jquery.js:4:22274
.send/c#http://localhost/payrollengine/js/jquery.js:4:26750
I tried this in the error function and tried printing it out, I got this response:
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
response:
[{"fieldvalueid":"1","value":"Manager"},{"fieldvalueid":"2","value":"Project Manager"},{"fieldvalueid":"3","value":"Software Engineer"},{"fieldvalueid":"4","value":"Senior Software Engineer"},{"fieldvalueid":"5","value":"Associate Software Engineer"},{"fieldvalueid":"28","value":"sample"},{"fieldvalueid":"29","value":"azhagu"},{"fieldvalueid":"37","value":"t"}]null
I don't know what's wrong with the code. Can someone help me out with this?
Add the json header to your controller function:
header('Content-Type: application/json');
echo json_encode($result);
try to return a associative array from the db
->fetchAll('assoc');

Getting a value from Javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)

How to pass global variable via ajax

I have three files:
index.php
ajax.php
function.php
I want to pass a global variable from index.php to function.php via ajax.php.
So the alert message in index.php should be "2". But in fact, the result is "1" because function.php does not know the $global_variable.
Here is the code:
index.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
ajax.php
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
function.php
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
I do not want to pass the global variable to ajax call, because my real project has many variable like this, and they should not to display because of security.
How to do this?
$.ajax({
type: "POST",
url: 'ajax.php',
data:{
global_variable:<?php echo $global_variable?>
},
success: function(data) {
alert(data);
}
});
You can send it with data object to ajax.php page
and at ajax.php page you can fetch it by:
<?php
include 'function.php';
$global_var=$_POST['global_variable'];
$result = process_my_variable($global_var);
echo $result;
?>
index.php and ajax.php (with the included function.php) are different programs. They do not share variables.
You either need to store the data somewhere that both programs can get at it (such as in a SESSION) or pass the data from index.php to the browser, and then send it to ajax.php in the query string or POST body of the Ajax request.

Categories