echo select options according to AJAX call - javascript

ive been trying this for the whole day and cant get my head around it. Im retrieving a count from an ajax call called quote.pdfnum which tells me the number of pdfs generated per user. I want to echo quote.pdfnum (number) of options. Im trying to echo in the select at the last table column.
setInterval(function(){
$.ajax({
url: 'poll_requests.php',
type: 'POST',
data: {data:currRequests},
dataType: 'json',
// dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
})
.done(function(response, textStatus, jqXHR) {
// console.log("new Requests "+response.new_quotes);
// console.log("all requests "+response.all_quotes);
var oldRequests = currRequests;
currRequests = response.all_quotes;
var newRequests= response.new_quotes;
if(oldRequests!=currRequests){
if(activeTab!='requests_tab' && newRequests.length>0 && pollRequests>1){
var spanText=Number($('#rbadge').text())+newRequests.length;
$('#rbadge').text(spanText);
}
if(newRequests.length==0 && oldRequests.length==1){
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
$("#rtable tr:first").after("<tr><td colspan='8'>No pending requests at the moment...</td></tr>");
}
if(newRequests.length>0 && oldRequests.length==1){
//and old requests are 0 (-1) remove the first row "no requests at the moment"
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
}
for (var i = 0; i < newRequests.length; i++) {
quote = newRequests[i];
if (activeTab!='requests_tab' && pollRequests>1) {
noty({text: quote.company+' requested a new quote'});
};
// $("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a><a class='approve' href='approve.php?id="+quote.id+"'>Approve</a></td> </tr>");
$("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a></td><td><select name='pdfs' id='pdfs'></select></td> </tr>");
};
}
// console.log('requests length '+newRequests.length);
pollRequests++;
})
.fail(function(error) {
console.log("error"+ error.responseText);
})
.always(function() {
// alert("complete");
});
// },1000000);
},2000);
And this is my poll_requests.php page.
<?php
header('Content-Type: application/json');
$data = $_POST['data'] ;
$new_quotes = array();
$files = array();
$all_quotes = array();
require_once('db_connect.php');
$sql = $db->prepare("SELECT * FROM users, quotes WHERE users.id = quotes.user_id and quotes.status = 'req' ORDER BY quotes.rdate ASC");
if($sql->execute()){
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$files[] = $row;
}
}
foreach ($files as $file):
$quote_id = $file['quote_id'];
$all_quotes[] = $quote_id;
if(!in_array($quote_id, $data)):
$date_time=explode(' ',$file['qdate']);
$insured=$file['insured'];
$status = $file['status'];
$user_id = $file['id'];
$username= $file['username'];
$country = $file['country'];
$company = $file['company'];
$pdfcount = $file['pdfnum'];
$pdf_path="all/$quote_id/$quote_id.pdf";
$new_quotes[] = array('id' => $quote_id,
'user' => $username ,
'country' => $country,
'insured' => $insured,
'status' => $status,
'date' => $date_time[0],
'time' => substr($date_time[1],0,8),
'company' => $company,
'pdfcount' => $pdfcount,
'pdf' => $pdf_path);
endif;
endforeach;
$all_quotes[]=-1;
$data_to_send = array();
$data_to_send['new_quotes'] = $new_quotes;
$data_to_send['all_quotes'] = $all_quotes;
$json_to_send = json_encode($data_to_send);
echo $json_to_send;
?>

Related

How can I pass id of multiple row selection to print page at the time of inserting data

I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();

json not displaying with dataType :'json'

i'm tying to do an ajax get call
i can successfully console.log the result without putting the datatype json in the ajax
dataType: 'json',
when i console.log without it i get
{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}
however i cant display the json data
if i put
dataType: 'json',
my
console.log
is empty
i dont understand where the problem is
$(document).ready(function(){
var username = $("#usernameinfo").text();
$.ajax({
type:"GET",
url: "<?= base_url()?>"+"account/listings/more_user_ads",
data: {"username":username,"pid":"<?=$this->input->get('pid')?>"},
success: function(res){
console.log(res);
}
});
});
php
function more_user_ads(){
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
if($query->num_rows()>0){
foreach($query->result() as $row){
if($post_id != $row->post_id){
$result = array(
'id'=> $row->id,
'post_id'=> $row->post_id,
'post_title'=> $row->post_title,
'image1'=> $row->image1,
'price'=> $row->price,
'price'=> $row->price,
);
$res = json_encode($result);
echo $res;
Add each row to the $result array then echo the json_encode once.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
if($post_id != $row->post_id)
{
$result[] = array(
'id' => $row->id,
'post_id' => $row->post_id,
'post_title' => $row->post_title,
'image1' => $row->image1,
'price' => $row->price,
'price' => $row->price,
);
}
}
}
echo json_encode($result);
}
Actually, you can shorten this a bit by using $query->result_array(); because you won't have to convert an object to an array.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
$rows = $query->result_array();
foreach($rows as $row)
{
if($post_id != $row['post_id'])
{
$result[] = $row;
}
}
}
echo json_encode($result);
}

Ajax jQuery on success if statement double json_encode return underfined value

I trying to get $comments_id,$comments_timestamp, $user_firstname, $user_lastname values and pass back to ajax, but in the if statement was execute only one object array which is ['successful-submit-comment'] = true;.
Ajax
$.ajax({
type:'post',
url:'getcomment_detail.php',
data:{comment_id: comment_id,user_desc:user_desc},
cache:false,
dataType:'json',
success: function (data){
console.log(data);
var ttes1 = data.comments_timestamp;
alert(ttes1);
}
});
getcomment_detail.php :
$u_id = $_SESSION['u_id'];
$submit_comment_status = array();
if($sql = "INSERT INTO comments (post_id, user_id, user_desc) VALUES ('$comment_id','$u_id','$user_desc')"){
mysqli_query($conn,$sql);
mysqli_close($conn);
$get_comment_user_detail = "SELECT comments.id, comments.timestamp, user.firstname, user.lastname FROM comments INNER JOIN user ON user.id = comments.user_id WHERE user.id = $u_id ORDER BY comments.id DESC LIMIT 1";
if($stmt = $conn->prepare($get_comment_user_detail)) {
$stmt->execute();
$stmt->bind_result($comments_id, $comments_timestamp, $user_firstname, $user_lastname);
while ($stmt->fetch()) {
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
}
$stmt->close();
}
$submit_comment_status['successful-submit-comment'] = true;
header('Content-Type: application/json');
echo json_encode($submit_comment_status);
}
Console return value:
Alert return value:
Undefined
Why don't you just put it into the array and return it all as a json file?
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname,
'successful-submit-comment' => true
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
and in your ajax you just get the value like
console.log(data['successful-submit-comment']);

How to parse large data via POST query

I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Categories