I have a table sets in a popup window to show orders placed by a specific userID
<div id="shpcart">
<div id="shpop">
<table>
<thead>
<tr><th></th><th>Item name</th><th colspan="2">Price</th><th>shipping</th></tr><th>Quantity</th>
</thead>
<tbody id= "cartbody">
</tbody>
</table>
</div>
</div>
Here is the ajax to send the userID to the server
$(function(){
$(".prod_buy").click(function(){
var htmlId = $(this).attr('id');
var idarray = htmlId.split('-');
var itemId = idarray[1];
$.ajax({
type: "POST",
url: "tempselector.php",
data: {'proId': itemId }
}).done(function( msg ) {
jQuery.parseJSON(msg);
var output = jQuery.parseJSON(msg);
var htmlstring;
alert ("im running");
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
});
});
and here is the PHP to fetch the order of the passed user id
<?php
session_start();
include('includes/config.php');
$uId = $_SESSION["uId"];
$prID = mysqli_real_escape_string($link,$_POST["proId"]);
//$pQty = mysqli_real_escape_string($link,$_POST["prQTY"]);
$pQty = 2;
//$prID = 4;
$sqlget= "SELECT * FROM vasplus_programming_blog_pagination WHERE id='".$prID."'"; // to find the selected item
$resultget = mysqli_query($link, $sqlget);
$itemget = mysqli_fetch_array($resultget);
$itemId = $itemget[0]; // store the selected id in var
$itemNm = $itemget[1];
$ITimage = $itemget[2];
$ITprice = $itemget[3];
//$ITdiscount =$itemget[4];
$ITdescription =$itemget[5];
$ITshipping =$itemget[6];
// $ITavailable = $itemget[7];
$ITcontrycod =$itemget[8];
$itemCol = $itemget[9]; // store the selected color in var
$itemSiz = $itemget[10]; // store the selected size in var
$ITqty = $itemget[11];
// we need to search the temp table to see if the selected item is there
$sqlsrch= "SELECT * FROM XXXXX WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // if the item is in the temp table or not
$resultsrch = mysqli_query($link, $sqlsrch);
$itemsrch = mysqli_fetch_array($resultsrch);
echo $itemsrch;
if (isset($itemsrch)){
$adqty = $itemsrch[8];
$adqty ++;
$sqlupdate=" UPDATE XXXXXX SET qty='".$adqty."' WHERE product_id ='".$prID."' AND size = '".$itemSiz."' AND color = '".$itemCol."' AND user_id = '".$uId."' "; // update the qty of theexisting items in temp table
$resultupdate = mysqli_query($link, $sqlupdate);
}else {
echo " user id searching ";
$sqlisUsr= "SELECT * FROM XXXXXX WHERE user_id = '".$uId."' "; // check if the user has any item in the temp table
$resultisUsr = mysqli_query($link, $sqlisUsr);
$isUsr = mysqli_fetch_array($resultisUsr);
if (isset($isUsr)){ // if user has items in the cart
$getOrdId = $isUsr[2]; // get the order ID
$sqladdN=" INSERT INTO XXXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$getOrdId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) "; // insert the item with the existing order ID
$resultaddN = mysqli_query($link, $sqladdN); }else{ // user has no record in temp order
echo " else is running " ;
$ReNth = 0;
$oId = 1;
while ($ReNth != 1){
$sqlNewOiD= "SELECT * FROM XXXXXX WHERE order_id = '".$oId."'"; // generate a new order ID
$resultOsrch = mysqli_query($link, $sqlNewOiD);
$oIdsrch = mysqli_fetch_array($resultOsrch);
if (isset($oIdsrch)){
echo $oId++;
echo " order Id generated " .$oId;
}else{ // insert the new item with the new order id in the temp table
echo $oId."oId<br />" ;
echo $uId."uId<br />" ;
echo $ITimage."<br />" ;
echo $ITshipping."<br />" ;
echo $pQty."<br />" ;
echo $ITprice."<br />" ;
echo $ITcontrycod."<br />" ;
echo $itemCol."<br />" ;
echo $itemSiz."<br />" ;
echo $prID."<br />" ;
$sqladdNOID = " INSERT INTO XXXXXx (order_id, user_id, photo, express, qty, unit_price, country, color, size, product_id) VALUES ('$oId', '$uId' , '$ITimage' , '$ITshipping' , '$pQty', '$ITprice' , '$ITcontrycod' , '$itemCol' , '$itemSiz' , '$prID' ) ";
$resultaddNOID = mysqli_query($link, $sqladdNOID);
$ReNth = 1; // quit the searching for unique order id loop
}//end if
}//end while
}// end if
}// end if
// pars json code for the cart
$sql= "SELECT * FROM XXXXX WHERE user_id = '".$uId."'" ;
$result = mysqli_query($link, $sql);
while($item = mysqli_fetch_array($result)){
$array[] = $item;
}
echo json_encode($array);
?>
The problem is that the ajax is not able to retrieve the parsed array by the PHP. I see that the $uId being passed to the PHP and the PHP code works fine and $array has been fetched, but in return the ajax isn't able to read the $array .
please help me here
about the ajax method, you can try this code:
$.ajax({
url:'tempselector.php',
dataType:"json",
type:"GET",
data: {'proId': itemId },
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('body').append(XMLHttpRequest.responseText);
},
success:function(output){
var htmlstring;
for(var index=0;index<output.length; index++){
var itmnam = output[index][1];
var itmpic = output[index][2];
var itmpr = output[index][3];
var itmdisc = output[index][4];
var itmdesc = output[index][5];
var itmshp = output[index][6];
var itmav = output[index][7];
htmlstring +="<tr><th><img src = '../cartimg/'"+itmpic+"></th><td>"+itmnam+"</td><td>"+itmdisc+"</td><td>"+itmshp+"</td><td>QTY</td></tr>";
}
$('#cartbody').html(htmlstring);
$("#shpcart").fadeIn();
}
});
if unnecesary output is present then json can not be parsed, that's the issue. problem has been solved
Related
I am trying to calculate the total earnings after a certain timestamp.
What I want to do:
I have a button which on click adds the total earnings till that time to the table with a timestamp.
As soon as it gets added to the database, from there on i want to display the total earnings earned after that timestamp.
So, that means if there are no earnings after the click of the button, it should show me 0.
Problems:
The thing works only the first time if the database is empty. Otherwise Values are correctly inserted in the database but the jquery doesnt update the span tags each time I hit the button.
HTML:
<span id="wb_uid8">Earned: </span><span id="wb_uid9">Fetching data..</span>
<input type="submit" id="Button1" name="Button1" value="I received my incentive today!">
<span id="wb_uid10"><strong>Last payment receive date:</strong></span><span id="wb_uid11"> </span><span id="wb_uid12"></span><span id="wb_uid13"><br>
</span><span id="wb_uid14"><strong>Received amount:</strong></span><span id="wb_uid15"> </span><span id="wb_uid16"></span>
jQuery:
<script>
$(document).ready(function()
{
$('#Button1').click(function(){
var fullDate = new Date();
var twoDigitMonth = fullDate.getMonth()+"";
if(twoDigitMonth.length==1){
twoDigitMonth="0" +twoDigitMonth;
}
var twoDigitDate = fullDate.getDate()+"";
if(twoDigitDate.length==1){
twoDigitDate="0" +twoDigitDate;
}
var currentdate = twoDigitDate+"/"+twoDigitMonth+"/"+fullDate.getFullYear();
var dataString = 'date='+currentdate;
$.ajax({
type:"POST",
data: dataString,
url: "receipts.php",
cache:false
});
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
url: 'checkearnings.php',
success: function(data){
var data=JSON.parse(data);
$('#wb_uid9').html('₹ '+ data['earned']);
$('#wb_uid12').text(data['lastdate']);
$('#wb_uid16').html('₹ '+ data['lastamt']);
}
});
}, 1000);
});
</script>
checkearnings.php
<?php
include 'connect.php';
$earned = 0;
$lastdate = "";
$lastamt = "";
$timestamp = "";
$sql = "SELECT * FROM receipts ORDER BY date DESC LIMIT 1";
$result1 = mysqli_query($db, $sql);
if($details = mysqli_fetch_array($result1)){
$lastdate = $details['date'];
$lastamt = $details['amt'];
$timestamp = $details['timestamp'];
}
else{
$lastdate = "Never";
$lastamt = "Nothing";
}
$sql = "SELECT amt FROM sales WHERE timestamp>'$timestamp'";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
$earned = $earned + $fetch_options['amt'];
}
$responses=array('earned'=>$earned, 'lastdate'=>$lastdate, 'lastamt'=>$lastamt);
$return=$responses;
//echo $earned;
echo json_encode($return);
?>
receipts.php
<?php
include 'connect.php';
include 'checkearnings.php';
if (isset($_POST['date']))
{
$newdate = $_POST['date'];
$time = round(microtime(true)*1000);
$sql = "INSERT `receipts` (`date`, `amt`, `timestamp`) VALUES ('$newdate', '$earned', '$time')";
$results = mysqli_query($db, $sql);
mysqli_close($db);
}
?>
I tried using ajax to send data from onclick event on image
This is the ajax code
function get_img(name) {
$.ajax({
type: "POST",
url: "img_main.php",
data: "img_name="+name,
success: function(response)
{
alert("main image selected");
}
});
}
This is the img tag where I put the onclick event
while($row = mysql_fetch_array($query))
{
$test = $row['img_name'];
$result .= "<td><img src='".$uploaddir.$row['img_name']."' class='imgList' onclick='get_img(\"".$test."\")' /></td>";
This is the img_main.php
<?php
include("connect.inc.php");
echo "<script type='text/javascript'> alert('test'); </script>";
$img_name = $_POST['img_name'];
$query = "UPDATE upload set status = 1 where img_name = $img_name";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != $img_name";
$result2 = mysql_query($query2);
?>
What I want is when I clicked on the image, it update the field status on the database.
The success function in the ajax code give me the alert function but the status field is not updated.
My console returns no error.
Can somebody please help?
try change
data: "img_name="+name,
to
data: {img_name:name},
or
$.ajax({
type: "POST",
url: "img_main.php", or use full url like "http://domain/img_main.php"
data: {img_name:name},
success: function(response)
{
alert("main image selected");
}
});
and img_main.php (add quotes to your query variable)
$query = "UPDATE upload set status = 1 where img_name = '$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != '$img_name'";
$result2 = mysql_query($query2);
Add quotes to $img_name in the update queries like:
$query = "UPDATE upload set status = 1 where img_name='$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name!='$img_name'";
As you are getting alert as response, I don't think that there is error in ajax call.
I am gtting data from database, but it's printed again and again. There is get coding of index page.
var lastmsgid = 0;
function getChat() {
$.ajax({
type: "POST",
url: "view_msg.php",
data: "sid=<?php echo $id; ?>&lastmsgid="+lastmsgid,
async: false,
datatype: "json",
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var uname=row['uname'];
var msg=row['msg'];
$('#chatbox').append("<b>"+uname+"</b> : </b>"+msg).append("<hr />");
lastmsgid=row['id'];
}
}
});
}
Here is my view_msg.php page:
<?php
header('Content-type: application/json');
require_once('include/util.php');
$sid = $_POST['sid'];
$lastmsgid = $_POST['lastmsgid'];
$sql = "SELECT m.`id`, m.`msg`, u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid AND `senderid` = $sid OR `senderid` =".$_SESSION['id']." AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (!empty($data)) {
echo json_encode($data);
}
exit;
?>
You should check your SQL query.. You need to use brackets in where condition because you are using OR.. I don't know the conditions for your desired result but it may be like below:
$sql="SELECT m.`id`,m.`msg`,u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE ((m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid) AND (`senderid` = $sid OR `senderid` =".$_SESSION['id']." ) ) AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;
im having a little problem, i have a form, with three fields, my problem is this one:
on the 2 and 3 input i get via javascript values for countries and cities, what i want to do is to make the city input throw the values from the country i have selected in the country input, heres the javascript
<script>
var availableTags = [
<?php
$sql = "select * from citys ";
$rsd = mysql_query($sql);
while($row = mysql_fetch_array($rsd))
{
$pid=$row['cid'];
$city=$row['city'];
$state=$row['state'];
?>
"<?php echo $city; ?>,<?php echo $state; ?>",
<?php } ?>
];
$( "#inputsearch21" ).autocomplete({
source: function( request, response ) {
var matches = $.map( availableTags, function(tag) {
if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
return tag;
}
});
response(matches);
}
});
</script>
and the country script is the same, changing the php for country database.
i know i have to get the country id from the first form and in the second query i should be "select * from citys where countryid="$countryid"
any idea how to do this?
Probably the best thing to do is to work with an cobmination ajax and json. Then It should be something like this.
getCities.php
<?php
/* your connection ofc. */
$con = database_connection();
/* example unsecure please use PDO */
$sql = "SELECT ID, Name FROM City WHERE Country = '" . $_GET['country'] . "'";
$rsd = mysql_query($sql);
$res = mysql_fetch_array($rsd);
/* Return output in json format */
echo json_encode($res);
?>
Javascript
$.ajax({
type: "GET",
url: "getCities.php",
data: { country: "Germany" }
}).done(function( output ) {
/* Example for select inputs */
var cities = eval('(' + output + ')');
var length = cities.length;
for(var i = 0; i < length; i++)
{
var newOption = $('<option/>');
newOption.attr('text', cities[i].Text);
newOption.attr('value', cities[i].Value);
$('#ID-OF-SELECTBOX').append(newOption);
}
});
I want to pass the result of a query through a $.post.
function GetAllTasks()
{
$sql = "select t.id as task_id,
description,
createdat,
createdby,
max_requests,
max_duration,
j.name as job_name
from darkfuture.tasks t, darkfuture.jobs j
where t.job_id = j.id";
$sqlresult = mysql_query($sql)
or die("The list of works failed: ".mysql_error($this->con));
$result = array();
while($row = mysql_fetch_assoc($sqlresult))
{
$task = new TasksResult();
$task->id = $row["task_id"];
$task->description = $row["description"];
$task->createdat = $row["createdat"];
$task->createdby = $row["createdby"];
$task->max_requests = $row["max_requests"];
$task->max_duration = $row["max_duration"];
$task->job_id = $row["job_name"];
array_push($result, $task);
}
mysql_free_result($sqlresult);
return $result;
}
Here is how i call it:
$tasksDB = new TasksDB();
$tasks = $tasksDB->GetAllTasks();
Now i want to pass $tasks through here:
$.post("views/insert_tasks.php",{'tasks[]': $tasks}, function(data)
{
});
I know this {'tasks[]': $tasks} it's wrong but i don't know how to do it right.
<script type="text/javascript">
$.post("views/insert_tasks.php", {tasks:<?php echo json_encode($tasks); ?>}, function(data) {
});
</script>
On a side note you might want to look at mysql_fetch_object($result, 'TasksResult');
{tasks:
[id: 42, title: 'a'],
[id: 43, title: 'b'],
...
}
It's working, i will paste here all the code that way other users can use it as well.
This is the javascript function that gets the clicked checkboxes and the query result object and passes them to the .php file:
<script type="text/javascript">
// Attach a click handler
$(document).ready(function()
{
var clickedRows=new Array();
var table = document.getElementById('tablesorter');
var rowCount = table.rows.length;
var index = 0;
$('#request_tast').click(function()
{
for(var i = 0; i < rowCount; i++)
{
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(chkbox != null && chkbox.checked == true)
{
clickedRows[index] = i;
index++;
}
}
var clickrows = JSON.stringify(clickedRows);
$.post("views/insert_tasks.php",{ clickedRows : clickrows , <?php echo "tasks:'" . json_encode($tasks) . "'"; ?> }, function(data)
{
});
});
});
</script>
This is the php file that receives the clicked checkboxes and the query results object:
<?php
session_start();
require_once("../database/db_connect.php");
if(isset($_POST['clickedRows']))
{
$clickedRows = json_decode($_POST['clickedRows']);
$tasks = json_decode($_POST['tasks']);
foreach($clickedRows as $i)
{
$task_id = $tasks[$i]->task_id;
$myFile = "debug.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $_POST['tasks']);
fclose($fh);
$user_id = $_SESSION['id'];
$requestedat = date('l jS \of F Y h:i:s A');
$requestedby = $_SESSION['first'] . " " . $_SESSION['last'];
$sql ="INSERT INTO
darkfuture.users_tasks
(
`task_id`,
`user_id`,
`requestedat`,
`requestedby`
)
VALUE (
$task_id,
$user_id,
'$requestedat',
'$requestedby'
)";
$res = mysql_query($sql) or die(mysql_error());
}
}
?>
This is a feature I'm doing for my game website for task management, the team members can choose several tasks in a table by checking the check boxes and that tasks will be added to their profile and no one else can work on them.