Changing content of multiple elements with same name - php

I have some <td name="puja"> elements I want to update every 5 seconds deppending on their id so they contain the greatest bid(puja) for it's auction(subasta). For that, I'm trying to use AJAX and PHP.
Html looks like this (relevant code):
<?php
foreach ($subastas as $subasta) { ?>
<td name="puja" id="<?php echo $subasta["oid_s"] ?>"> </td>
As I have multiple elements to update, I tried getting all the elements and then running my AJAX function for every one of them.
AJAX:
$(document).ready(function()
{
var ids = document.getElementsByName("puja");
for (var i=0; i<ids.length;i++){
var id = ids[i].id;
$.ajax({
url : 'includes/getPuja.php',
data:{"oid_s":id},
success: function(data){
$(`#${id}`).html(data);
}
});
};
});
Finally, in my php file I just make a database connection, get the desired value , and echo it.
getPuja.php (relevant code):
$puja = 0;
if(isset($_POST["oid_s"])) {
$oid_s = $_POST["oid_s"];
$consultaPuja='SELECT pujado from (SELECT * from pujas WHERE OID_S = :oid_s ORDER BY pujado DESC) where rownum = 1';
try {
$stmtPuja = $conexion->prepare($consultaPuja);
$stmtPuja -> bindParam(':oid_s', $oid_s);
$stmtPuja -> execute();
foreach ($stmtPuja as $fila) {
$puja = $fila["PUJADO"] ;
}
echo $puja;
} catch(PDOException $e) {
$_SESSION["excepcion"] = $e -> GetMessage();
header("Location: excepcion.php");
}
}
When I run it, the HTML is not modified.

I fixed my problem with the following code, now the values get updated every second:
$(document).ready(function(){
setInterval(getPuja, 1000);
function getPuja() {
$( '[name=puja]' ).each(function() {
var id = $( this ).attr('id');
$.ajax({
url : 'includes/getPuja.php',
method:"POST",
data:{oid_s:id},
success: function(data){
$(`#${id}`).html(data);
}
});
});
}
});

Related

How to add a member and task allocated if not found in dynamically populated dropdownlst

I have reviewed suggested solutions but did not find any matching my issue.
We have a SELECT list that is dynamically populated from the database.
Each time a staff wishes to create a task and allocate time to complete the task, s/he selects the member who would handle that task and then allocates time to complete the task. This works fine.
//JS
function populateMember() {
$.ajax({
type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/getMember.php?mode=edited&rowId=' + $.urlParam('id'), // the url where we want to POST
dataType: 'html', // what type of data do we expect back from the server
encode: true
})
.done(function (data) {
var returnedData = JSON.parse(data);
var newRows = (returnedData.length - 3);
if (returnedData.length > 3){
var x = 0;
for (x=0; x < newRows; x++){
$( "#newMember" ).trigger( "click" );
}
}
var i=0;
for (i in returnedData){
$('#member' + i).val(returnedData[i][0]);
$('#task_time_alocatted' + i).val(returnedData[i][1]);
}
})
.error(function () {});
}
//PHP
<?php
//Connect to server
///Connection info goes here
}
//These are parameters from the POST request
$mode = $_GET[ 'mode' ];
$rowId = (int) $_GET[ 'rowId' ];
$sql = "SELECT member, task_time_allocated FROM TaskAllocations WHERE parent_task_id = $rowId;";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
$theErrors = sqlsrv_errors();
array_push($messages, 0, $sql, $theErrors);
echo json_encode($messages);
die();
} else {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
array_push($messages, [$row['member'], $row['task_time_allocated']]);
}
echo json_encode($messages);
}
?>
However, if the member that a staff is trying to select from the SELECT list is not on that list, we would like two text boxes, one for the member and one for task to be allocated to that member.
How do we handle this?
We have created this on the HTML form:
//JS
<script type="text/javascript">
$(function () {
$("#btnstaff").click(function () {
if ($(this).val().toLowerCase() == "amend") {
$.each($('.dvstaff'), function(i, item){
$(this).show();
});
$(this).val("Cancel");
} else {
$.each($('.dvstaff'), function(i, item){
$(this).hide();
});
$(this).val("Amend");
}
});
});
</script>
//HTML
<input id="btnstaff" type="button" value="Amend" name="btnstaff" />
<tr>
<td></td>
<td><div class="dvstaff" style="display: none"><input id="amendmember" class="shortText" style="width:242px;" name="amendmember"></div></td>
<td>
<div class="dvstaff" style="display: none"><input id="amendtime" class="shortText" placeholder="0" name="amendtime"> %</div></td>
</tr>
You click Amend and it creates two blank textboxes, one for new member and the other for task_time_allocated.
We would prefer to handle this Amend bit on the JS that invokes the getMember method since the HTML is generated from the JS.
Is this possible?

Select and Delete multiple rows by selecting checkboxes using PHP

Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
<input class='file' type="checkbox" class="form-control" name="hid" id="<?php $rs["carimgid"]; ?>" placeholder="Please choose your image">
this my ajax script where using this to delete multiple row without refresh
<script type="text/javascript">
$(document).ready(function(){
jQuery('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
jQuery('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
//alert(allVals.length); return false;
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
//$("#loading").show();
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
//for server side
var join_selected_values = allVals.join(",");
$.ajax({
type: "POST",
url: "delete.php",
cache:false,
data: 'ids='+join_selected_values,
success: function(response)
{
$("#loading").hide();
$("#msgdiv").html(response);
//referesh table
}
});
//for client side
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
jQuery('.remove-row').on('click', function(e) {
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
$('table tr').filter("[data-row-id='" + $(this).attr('data-id') + "']").remove();
}
});
});
</script>
and my php code is
<?php
include("config.php");
if(isset($_POST['ids'])){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid ='$id'");
}
?>
Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
You haven't got the ids from POST.
Look at the following
$ids = mysqli_real_escape_string($con, $_POST['ids']);
if(!empty($ids)){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid IN ({$ids})");
}

Display the JSON data returned from PHP in the Datatable format

I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

Jquery: If form is blank load this query

I've got some JQuery which monitors a form. Basically, for every keyup it will call a php file to search the database.
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2) {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
});
This works fine, however it filters the results in #searchresultdata depending on the query. The only thing is, if nothing is in the form, I want it to load everything - the user should not have to click the form to do this, therefore a .blur would not work.
The PHP file is simply:
if(isset($_GET['keyword'])){}
you should handle a [*] search on your server
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
if (faq_search_input =='') faq_search_input ='*';
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2 || faq_search_input=='*') {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
$("#faq_search_input").trigger('keyup');
});
If you're loading all results initially, then could you not just store this in a JavaScript array and filter the results with JavaScript? This would save you a HTTP request on every key press, which can only be good for speed and resource usage of your site.
EDIT: Sample.
<?php
$sql = "SELECT `title` FROM `your_table`";
$res = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row['title'];
}
echo '<script>var data = ' . json_encode($rows) . ';</script>';
?>
<form method="post" action="">
<fieldset>
<input type="text" name="search" id="faq_search_input" />
</fieldset>
</form>
<script>
// I presume you're using jQuery
var searchInput = $('#faq_search_input');
var searchResults = $('#searchresultdata');
var tmpArray = data;
// add all results to results div
$.each(data, function(key, val) {
searchResults.append('<li>' + val + '</li>');
});
searchInput.attr('placeholder', 'Begin typing to search');
searchInput.keyup(function() {
// hide any <li> in your #searchresultdata that don't match input
});
</script>
I don't know what is in your serverresponse variable, so I can only guess what gets put into the searchresultdata <div>. You'll also need to modify the SQL query to match your table and column names.
Contents of searchdata.php
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%'";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$result=mysql_query($query, $database_connection) or die(mysql_error());
if($result){
if(mysql_affected_rows($database_connection)!=0){
while($row = mysql_fetch_object($result)){
?>
<div class="hold-cont">
<div class="holder">
<div class="image-hold" >
<img class="image-icon" src="<? echo $deviceimg.($row->Image); ?>"/>
</div>
</div>
<div class="device-name devicename-txt"><? echo($row->Manufacturer. ' ' .$row->Model); ?></div>
</div>
<?
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}

Categories