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/
Related
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!
I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer.
This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one.
My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?
HTML/Jquery of the Ajax with the error:
function BekijkGegevens() {
$.ajax({
type: 'GET'
, data: {}
, dataType: 'json'
, url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
, success: function (rows) {
$('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
for (var i in rows) {
var row = rows[i];
var datum = row[1];
var stand = row[0];
$('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
}
$('#output').append("</table>");
}
, error: function (JQXHR, TextStatus, ErrorThrow) {
console.log(JQXHR);
console.log(TextStatus);
console.log(ErrorThrow);
}
})
}
PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo "{data:" .json_encode($data2). "}" ;
}
?>
Thanks for any help that you can provide.
EDIT: Forgot to put my browser network, here it is.
http://puu.sh/uzI4f/a9ed1e0be5.png
EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files:
This one is used to send the key from Jquery to PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}
?>
This one is used to get the needed information:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = $result-> fetch_row())
{
$data2[]=$row;
}
echo json_encode($data2);
}
?>
First, some warnings (in accordance with this link):
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You should test against the session variable in your second script, which should look like this:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$teller = $_SESSION['teller'];
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo json_encode(['data'=> $data2]);
}
?>
Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.
Dont try to glue data to string, like this:
echo "{data:" .json_encode($data2). "}" ;
Use simple
echo json_encode(['data'=> $data2]);
It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null
Declare your $data2 in the begginng, before if statement:
$data2 = [];
if (isset($_POST['teller'])) {
//do stuff and redefine $data2 or fill it;
}
//always echo valid json, event if no $POST["teller"] has arrived
echo json_encode(['data' => $data2]);
I have a table called Stats. Stats has 4 columns: id, ip, count, and date. count is the number of clicks the ip has clicked on the ads on my site. Each time the user clicks on an ad, their count number will increase by 1. How do I increase their count number by 1 and update that in the database? Here is my code and it's not working for some reason. When I click on the div, it doesn't refresh...so the whole block of code isn't executing. Note that I've already captured the user's ip when they entered my site, this is the part where if they clicked my ad, the count is incremented and updated in the database.
<script>
$(document).ready(function()
{
$("#ad").click(function()
{
<?php
$queryTot = "SELECT `count` AS total FROM Stats WHERE ip = '$ip'";
$resultTot = $db->query($queryTot);
$data = $resultTot->fetch_assoc();
$count = $data["total"] + 1;
$insert = $db->prepare("UPDATE Stats(count) WHERE ip = '$ip' VALUES(?)");
$insert->bind_param('i', $count);
$insert->execute();
$insert->close();
?>
location.reload();
})
})
</script>
There is a lot of points to consider in your answer.
But very possibly you should use an AJAX solution to do it, and avoid every SQL queries in your HTML pages, because keeping SQL queries there definitely is not a good pratice, according all basic security and code maintenance POVs.
It is not possible to re-write your code here rightly without knowing your project structure, or even your idea, and you must take this answer as an important start point.
Basically, you must define in your server-side application a method which returns pure data, in a JSON format for example, and then use AJAX to access this method according an event (a click, for example), receive its response and modify your client-side, probably with jQuery and JS.
I hope this answer can help you.
I've written a short example for you that you could continue to build on to accomplish what you need. Here's the basic idea.
HTML
<input type="hidden" id="ip" value="<?php echo $_SERVER['REMOTE_ADDR'];?>"/>
jQuery
var ip = $('#ip').val();
$(document).ready(function(){
$('#ad').on('click',function(){
$.ajax({
type: 'POST',
url: 'ajaxUpdateDatabase.php',
data: 'ip='+ ip,
success: function(response){
console.log(response)
//send the user to the ad's page here for example
//you could use location.href='url-to-add-here';
//or if you really want to reload the page for a reason I fail to understand, use location.reload();
}
});
});
});
PHP (ajaxUpdateDatabase.php)
//please note that using UPDATE requires that there is previously an entry with this IP address.
//example using PDO...
$sql = 'SELECT * FROM stats WHERE ip = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['ip']));
if($stmt -> rowCount() > 0){
$sql = 'UPDATE stats SET count = count + 1 WHERE ip = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['ip']));
}
else{
//ip-address was not found in the database
//insert query goes here
}
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
I have this problem that I have multiple fields that updates a database via an AJAX-call. The AJAX call looks like this:
$(".fresheditable").fresheditor("save", function (id, parsedHtml) {
$.ajax({
url: 'save.php',
type: 'POST',
data: {
id: id,
parsedHtml: parsedHtml
}
});
});
The ID value changes depending on what element is being edited. The problem is when the update gets sent to the save.php document. How do I only run the update with the specific ID?
See my save.php:
if($_POST['id']='link')
{
$link = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET linkname=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($link,$_SESSION['button'])))
{
echo 1;
}
}
//The next if-statement could look like this:
if($_POST['id']='contactperson')
{
$contactperson = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET contactperson=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($contactperson,$_SESSION['button'])))
{
echo 1;
}
}
If more than one ID is sent to the save.php say link and contactperson both if-statements are true and the update sets the same values because the parsedHtml variable.
Is there anything I can do in save.php that can prevent this? Somehow I need to associate the correct parsedHtml with the corresponding id.
The comparison operator in PHP (as well as in Javascript) is == and not =
if($_POST["id"]=="link")
Is it because you're using single equals in your IF tests, which assigns and returns true as a value exists? Not double-equals for comparison?
E.g.
if($_POST['id']=='link')
not
if($_POST['id']='link')
One thing you can use is data attribute i mean
<span item-data="some_id">data</span> now you can select in jquery, the specific item-data from your html to update.
Use else-if structure.
if($_POST['id']='link') {
}
else if($_POST['id']='contactperson') {
}