I get a random row from a mysql-server using php. I then display some information and would like to let the users give feedback on that specific row. However, I can't seem to transfer the ID correctly to the update.php. (No updating is happening on the server). Can somebody spot out my error?
Mysql-php getting a (ugly) random row:
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT id, username, message, ttime, field1, field2 FROM field WHERE done = 0 ORDER BY RAND() LIMIT 1");
$array = mysql_fetch_row($result);
echo json_encode($array);
Then index.php:
<div id="output">
<div id="username">content</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{ $.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(timestamp +message );
$('#username').html( vname );
}
});
});
</script>
<script>
$(document).jkey('a',function() {
$.post("update.php", { id: "id"} )
});
</script>
Then in the update.php:
<?php require_once('Connections/connection.php'); ?>
<?php
$id = $_POST['id'];
$sql = "UPDATE field SET field1 = field1 +1 WHERE id = '$id'";
$result = mysql_query($sql);
?>
Put a global _id in a script tag, then :
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
//...
and
<script>
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} ) // <--- Look here
});
</script>
$.post("update.php", { id: "id"} )
is sending the Stringid to the server as the id. You'll want to replace it with the actual variable that holds the id number based on which row the user selected, for example
$.post("update.php", { id: rowIDNum} )
If you provide some information on how the user is selecting a row, I can provide more details on how to determine the value to put in rowIDNum.
Related
PHP code :
<?php include_once 'includes/dbconnect.php';
$name = $_POST['name'];
$year = $_POST['year'];
$term= $_POST['term'];
$semester= $_POST['semester'];
$class= $_POST['class'];
$query = "SELECT * FROM hostelfee WHERE RegNo = '$name' AND PayYear='$year' AND PayTerm='$term' AND PaySemester='$semester' AND PayClass='$class' ";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
?>
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
name = $('#name option:selected').val();
year = $('#year').val();
term = $('#term').val();
semester = $('#semester').val();
class = $('#class').val();
$.ajax({
type : 'POST',
dataType: 'json',
data: {name : name,year : year,term:term,semester:semester,class:class},
url:'getBalance.php',
success:function (result) {
$('#Year').val(result['PayYear']);
$('#student-balance').val(result['Balance']);
}
});
});
}
</script>
I have a payment page where I first have to select student No, Year and term, then the balance of that period will be selected.
The challenge is that I can only send one parameter from PHP to ajax. How to use more than one parameter?
you can use serialize.
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
//use serialize to get multiple value of form. Add your form id - #form. you can also use form name, class
form_data = $('#form').serialize();
$.ajax({
type : 'POST',
dataType: 'json',
data: {action : 'hostelfee',formdata : form_data},
url:'getBalance.php',
success:function (result) {
$('#category').val(result['PayYear']);
$('#student-contact').val(result['Balance']);
}
});
});
}
</script>
In getBalance.php file use parse_str to get the serialize data in array.
if($_POST['action'] == 'hostelfee'){
parse_str($_POST['formdata'], $form_data);
//here will get all the parameter like name, year,term,semester and class etc in array.
print_r($form_data);
//add your code here
}
I have written code for button to send a value to php file using ajax as show below :
<script>
$(document).ready(function(){
$(".open-AddBookDialog").click(function(){
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax({
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result1){
var packagetype = package_type;
alert(packagetype);
}
});
});
});
</script>
This is the ajax code for the button which i have written. My button code is :
<a data-toggle="modal" id="custId" data-name="<?php echo $arr["package_name"]; ?>" data-id="<?php echo $arr["id"]; ?>" href="#myModal" class="open-AddBookDialog btn btn-submit" OnClick='change(this);'>Book / Enquiry / Pay</a>
When clicking this button in href, I want to send a id value to a php file using ajax.
data1.php
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
$arr = mysqli_fetch_array($query1);
echo $arr['package_type'];
echo $arr['package_price'];
mysqli_close($con);
?>
using the id value, I want to pick multiple rows of package type and package price from the database having the same id value.After picking the multiple rows of these values i want to send it to the main php file and display all the values of all the rows picked from the database.
Can anyone suggest how to do this ?
<script>
$(document).ready(function()
{
$(".open-AddBookDialog").click(function()
{
var packageid = $(this).attr("data-id");
var dataString = 'packageid='+ packageid;
$.ajax(
{
type: "POST",
url: "data1.php",
data: dataString,
cache: false,
success: function(result)
{
resultJson=jQuery.parseJSON(result);
$.each(resultJson.packageDetails, function(i, item) {
var packagetype = item.package_type;
var package_price = item.package_price;
alert("packagetype :- "+packagetype+" ----- package_price :-"+package_price);
});
}
});
});
});
</script>
<?php
include('database.php');
$id=$_POST['packageid'];
$query1 = mysqli_query($con,"select * from ayurveda_packagetypes where package_id = '$id'");
//$arr = mysqli_fetch_array($query1);
while( $strPackageResult=mysqli_fetch_array($query1,MYSQLI_ASSOC) )
{ $ArrPackage[]=$strPackageResult; }
if( isset($strPackageResult) ){ unset($strPackageResult); }
mysqli_free_result($query1);
if( isset($query1) ){ unset($query1); }
$myResultPackageArray=array();
if( isset($ArrPackage) && is_array($ArrPackage) && count($ArrPackage)>0 ) {
$tempArray=array();
foreach( $ArrPackage as $tempPackage )
{
$tempArray['package_type']=$tempPackage['$tempPackage'];
$tempArray['package_price']=$tempPackage['package_price'];
$myResultPackageArray['packageDetails'][] =$tempArray;
}
}
mysqli_close($con);
echo json_encode($myResultPackageArray);
?>
There are some basic things you should know first then you can easily rectify your errors.
Debuging javascript
Prepared Statements
PHP Error Handling
This is not you have asked but as a programmer i will suggest you to go through it.
As going through your code
var packagetype = package_type;
package_type is undefined. If you are using chrome inspect element and check the console you will see the error.
Hope this will work.
I'm sending JSON to my server via jQuery's ajax method.
Here's my jquery, and im pretty sure this is fine:
function stuffs() {
this.fname = document.getElementById("fname").value;
this.lname = document.getElementById("lname").value;
this.email = document.getElementById("email").value;
}
$(function() {
function ajaxhelper(data){
//console.log(JSON.stringify(data));
//this returns "{"fname":"mike","lname":"smith","email":"a#a.a"}" which is what i expect
$.ajax({
url: 'postdb.php',
type: 'POST',
data: {data : JSON.stringify(data)},
success: function(data) {
console.log(JSON.stringify(data));
console.log("Success");
},
error: function(e) {
console.log(e);
}
});
}
$("form").on('submit', function(e){
e.preventDefault();
var data = new stuffs();
ajaxhelper(data);
//window.location = "postdb.php";
});
});
</script>
I get back an 500 server error. Here's my php code. (yes i'm only sending it an fname that i've preloading into my database, $con is valid i just didnt share the code to connect to my database)
$obj = json_decode($_POST['data']);
$sql = "SELECT * FROM testtable WHERE fname = \"$obj->{'fname'}\"";
$query = $con->query($sql);
I think my sql is incorrect due to the quotes? This is where im stuck.
Try using $obj->fname instead of $obj->{'fname'}.
Here is the correct syntax for your SQL Statement
$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";
I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>
I have this javascript function which serves an AJAX request to an external PHP Script, I want this to auto update a HTML <div> if the new check is different from the old check.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
This currently sucessfully returns and updates the div with the content from the array, the problem is, since adding the window.setInterval(function() line, it will server the connection every 5 seconds and update the <div> with duplicate data.. when all I want, it for it to echo the new data (if there is a ny)
Here is my other PHP script:
$STD = new mysqli ("localhost", "root", "hidden", "ajaxrequests");
$array = array();
$Query = $STD->prepare ("SELECT * FROM ajaxdata");
$Query->execute();
$Query->bind_result($ID, $Name, $Password);
while ($Query->fetch())
{
$array[] = array ( $ID, $Name, $Password);
}
echo json_encode($array);
Just add a call to empty() before your loop.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
Of course if your data size is large, this would not be very optimal. I would actually suggest having the PHP server send a timestamp value with it's response. You could then pass this back in subsequent AJAX requests and have the server determine if there are actually updates to deliver since that last timestamp. You could then have the server only send those updated records, which you could append/update similar to how you are already doing it.