jquery sorting table after ajax response - javascript

I have this small project to get multiple Alexa rank of each website.
I am trying to sort a table using jquery.tablesorter.js however it is not working, because I am sending ajax request for every URL then displaying it.
this is my jquery and ajax request :
<script>
$(document).ready(function(){
$('#btnurls').click(function(){
$('#loadingmessage').show();
var arrayOfLines = $('#websiteurls').val().split('\n');
$.each(arrayOfLines, function(index, item) {
$.ajax({
type: "POST",
url: "ajax_pages/ajax_alexa.php",
data: "textposted=" + item,
cache: false,
success: function(html){
$('#loadingmessage').hide();
for (var i = 1; i <= 1; i++) {
$("#content table").delay(1000)
.queue(function (nxt) {
$(this).append(html);
nxt();
});
}
$("#websiteurls").val("");
}
});
});
});
$("#textarea_reset").click(function(){
$("#websiteurls").val("");
});
});
</script>
alexa_rank.php
<?php $line = $_POST['textposted'];?>
<tr>
<td><?php if (!filter_var($line, FILTER_VALIDATE_URL) === false) {echo $line;} else {echo "$line";}?></td>
<td>
<?php
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$line);
$rank = isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
$country_rank=isset($xml->SD[1]->COUNTRY)?$xml->SD[1]->COUNTRY->attributes()->RANK:0;
$country_name=isset($xml->SD[1]->COUNTRY)?$xml->SD[1]->COUNTRY->attributes()->NAME:0;
echo $rank;
?>
</td>
<td><?php echo $country_rank; ?></td>
<td><?php echo $country_name; ?></td>
</tr>
live test https://www.bulkalexarankchecker.com/

Based on the example AJAX provided with jQuery tablesorter you need to trigger the update event on the table when the data is updated. It would probably be something like:
$.each(arrayOfLines, function (index, item) {
$.ajax({
type: "POST",
url: "ajax_pages/ajax_alexa.php",
data: "textposted=" + item,
cache: false,
success: function (html) {
$('#loadingmessage').hide();
for (var i = 1; i <= 1; i++) {
$("#content table").delay(1000)
.queue(function (nxt) {
$(this).append(html);
$(this).trigger("update");
nxt();
});
}
$("#websiteurls").val("");
}
});
});
Ideally you'd wait until all the data is fetched but you've made no provision for such an event with the current code so this would probably work equally well.

Related

How can i call a php function on a dynamically created html element in .js file

This is my product.php file which include the following php function
<?php
function getOfferName($conn,$companyID){
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
<?php
}
}
}
?>
This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');
}
});
Here i call php function getOfferName but it is showing me output like this
enter image description here
<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>
You can do by below code
getdata.php
if($_POST['action'] == 1){
$companyID = $_POST['id'];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
$html = '';
while ($row=mysqli_fetch_assoc($result)) {
$html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
}
}
echo json_encode($html);
exit(0);
}
?>
Ajax Call to Get Data
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
}else{
$.ajax({
url: "getdata.php",
type: 'POST',
data: {id:id,action:1},
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response) {
$(this).parent().parent().append('<select name="" id="">'+response+'</select>');
} else {
//Error
}
return true;
}
});
}
});
the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.
if you want to combine JavaScript with a server call you should use ajax.
JavaScript:
$('.offerCheckBox').on('change', function() {
var id=$(this).data('id');
if (!this.checked) {
var sure = confirm("Are you sure want to remove offer ?");
this.checked = !sure;
} else {
let fd = new FormData();
let companyID = $(this).val();
fd.append('companyID', companyID);
$.ajax
({
url: "getOffer.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
let response = JSON.parse(results.responseText);
my_function.call(this, response);
}
});
}
});
// in this function you will put the append of the select box that php has created
function my_function(response) {
console.log("response", response);
}
PHP code (the file name is : getOffer.php)
<?php
$companyID = $_REQUEST['companyID'];
$options = array[];
$sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers`
WHERE `company_id`='$companyID'";
if ($result=mysqli_query($conn,$sql)) {
while ($row=mysqli_fetch_assoc($result)) {
$options[$row['id']] = $row['offer_name'];
}
}
$resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
?>
Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP.
iterate on this array in JavaScript build your option select items and append them to the select box.

change function ajax call from php file

The following code consists of drop-down "(id=name" which populates from "listplace.php" through ajax call which works correctly.
Now I am trying to make another ajax call using the change function. when I select the particular item already populated on dropdown box it has to pass the selected item name1 in 'where' query to dataprod.php and has to display the products by clearing the existing products list available.
I am doubtful over the $name1 response from dataprod.php. Please help!!
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}else {
alert('No data found!');
}
}
});
</script>
ajax 2
$(document).ready(function(){
$("#name").change(function(){
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
Since you are calling ajax event on element which is loaded via ajax action so the change event is not bind and nothing is happend.
For ajax 2 action use below code.
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}

append before a specific row id generated by PHP

I have multiple rows generated into my page using PHP and MySQL, and I have a simple form that helps me to add more rows to database. What I want exactly is, that I have to add a row before a specific row with a specific id:
foreach($resInst as $installment){
$sum = $sum + $installment['payment'];
?>
<tr id="<?php echo $installment['infoid'] ?>"><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $counter--; ?></td>
<td><?php echo $installment['date_now'] ?></td>
<td><?php echo $installment['payment'] ?> $</td></tr>
</tr>
<?php } ?>
Here is the AJAX script:
$(document).on('click', '#add_payment', function()
{
var date_of_pay = $("#date_pay_now").val();
var pay_now = $("#pay_now").val();
//var id_pay = $(this).closest('tr').attr('id');
var id_pay = $("#select_to_pay").val();
var pid2 = '<?php echo $patient_id ?>';
console.log(pid2);
if(date_of_pay == "" || pay_now == "" || id_pay)
{
$("#date_pay_now").css('border-color', 'red');
$("#pay_now").css('border-color', 'red');
$("#select_to_pay").css('border-color', 'red');
}
if(date_of_pay != "" && pay_now != "" && id_pay != 0)
{
$.ajax
({
url: 'add_payment.php',
type: 'post',
data: {pid: pid2, date_o_pay: date_of_pay, pay_n: pay_now, id_of_proj: id_pay},
dataType: 'text',
success:function(result)
{
alert("Payment added!");
//Append here
},
error:function(result)
{
alert("Payment didn't added! Please Try again");
}
});
}
});
I mean that when I add information into database that have the same infoid I need to append this new line before the <tr> that have had the same $installment['infoid'].
The problem for me is how to put a condition inside jQuery that said:
if row of the id == id_pay ==> append before this line exactly
Like this:
success:function(result)
{
alert("Payment added!");
if($("tr").prop('id') == id_pay)
{
$(this).before("<tr><td>"+id_pay+"</td></tr>");
}
},
Something like this?
$('#'+id_pay).prev().after( put_your_inner_html_here )
Although, that might be interesting if your row was the first row ... but should still be ok since prev() would be the tbody

ajax test not working

I tried to get a simple ajax-test working but without success. I am trying to pass a variable($add1) from PHP to JS, then let the JS calculate the sum and return it back to a PHP variable via $_POST and ECHO it out in the html.
index.php:
<?php
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum($add1)</script>";
$sum = $_POST['variable'];
echo $sum;
?>
script.js:
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
});
}
For some reason this code doesn't work. Any help is appreciated.
I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST.
$sum from $_POST is actually echoed, but not shown in HTML page, but handled as a response back to Ajax.
You have to add a success function in Ajax closure
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function (data){
document.write(data);
}
});
You will see the answer show in page.
php:
if (isset($_POST['variable'])) {
$sum = some_futher_function($_POST['variable']);
echo $sum;
} else {
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum({$add1})</script>";
}
function some_futher_function($param){
//do some thing
return $return;
}
Include this on your page before your script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
PHP code
<?php
if ($_POST['variable']) { // If ajax request only
$sum = $_POST['variable'] + $add1;
echo $sum;
} else { // Loading in the browser
$add1 = 3;
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="script.js"></script>';
echo "<script>sum(".$add1.")</script>";
}
?>
Javascript
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function(result) {
alert(result)
},
error: function(e) {
console.log(e);
}
});
}

ajaxed data can't be picked up by jquery?

On document load I run the following ajax script.
function LoadData() {
$.ajax({
type: "GET",
url: "display.php",
dataType: "html",
success: function(text){
$("#responsecontainer").html(text);
}
});
}
Here is the PHP script it pulls the data from.
Yes I know it's depreciated and most likely vunerable to attack.
<?php
include 'db.php';
$counter = 0;
echo '<table class="table" id="tableShow">
<tr>
<td align=center><b>ID</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Quantity</b></td>
<td align=center><b>Price</b></td></td>
<td align=center><b>Description</b></td>
<td align=center><b>Edit Item</b></td>
';
$result = mysql_query("SELECT * from user ORDER BY `id` ASC");
while($data = mysql_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "<td align=center>$data[2]</td>";
echo '<td align=center><a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a></td>';
echo "</tr>";
}
echo "</table>";
?>
As you can see, within the table it has a button for each row.
<a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a></td>
I then have this script.
$(".Edititem").click(function ()
{
$('#Edit').modal('show');
$("#updateResults").click(function (){
$.ajax({
url: 'api.php',
data: "id="+ $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{ var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function(){$("#failure").alert();}
});
});
});
It seems that the html thats pulled from the PHP script, is invisible to jQuery. For example, when you click on one of the buttons, it should launch the modal I have within my page, however, it don't happen and I get no console errors either. But if I just insert the button into the #responsecontainer like so:
<div id="responsecontainer">
<a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a>
</div>
jQuery can find it, and the modal launches?
What is wrong here?
I recommend you to use .on() jQuery function.
.on() | jQuery API Documentation
Consider following script update:
$("#responsecontainer").on("click", ".Edititem", function() {
$('#Edit').modal('show');
$("#updateResults").click(function() {
$.ajax({
url: 'api.php',
data: "id=" + $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function() {
$("#failure").alert();
}
});
});
});
This is because when the document is loaded the elements are not loaded yet.
You can try the following. This does late binding on Jquery. Read More here https://api.jquery.com/on/
$(document).on('click', '.Edititem', function (e)
{
e.preventDefault();
$('#Edit').modal('show');
$("#updateResults").click(function (){
$.ajax({
url: 'api.php',
data: "id="+ $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{ var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function(){$("#failure").alert();}
});
});
});

Categories

Resources