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();}
});
});
});
Related
Having problem to change the state if its active or inactive everytime I clicked one of them nothings happened.
This is my code on ajax.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? '0' : '1';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
my php code ajax.php
<?php $db= new mysqli('localhost','root','password','dbname');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>
this is my code for displaying it, on this part everything works fine, when the value are 0 it will display inactive and 1 for active, however when clicking the status theres nothing happen only the notification and reload the page.
<td><i data="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
</i></td>
Try to configure your code to:
$(document).on('click','.status_checks',function(){
var status = '1';
var msg = 'Activate';
if($(this).hasClass("btn-success")){
status = '0';
msg = 'Deactivate';
}
if(confirm("Are you sure to "+ msg)){
var id= $(this).data('id');
url = "/ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:id,status:status},
dataType: "json",
success: function(data)
{
console.log(data);
location.reload();
}
});
}
});
<?php $db= new mysqli('localhost','root','password','dbname');
$user_id=$_POST['id'];
$newStatus=$_POST['$status'];
$sql = "UPDATE user SET status=".$newStatus." WHERE id=".$user_id."
";
if($db->query($sql) === TRUE){
echo json_encode(1);
}else{
echo json_encode(0);
}
?>
<td><i data-id="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' :
'Inactive'?>
</i></td>
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('');
}
}
hi guys i need to append data to a div where i cant dynamic the div look at this code
<li class="media_comment'+$post_id+'"></li>
now the post_id is a dynamic value that i am joining to my class
now i need to append some data to this
$(.media_comment).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
i have the same variable post_id avialable in the append function too. but the value is in a loop and i need to only append this in the li where the same post_id is passing which is posting the same data to every li so what can i do to design a dynamic selector ?
is it possible to do this or should i try another approach?
$(window).load(function(e){
// grab the scroll amount and the window height
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore(){
var lastID = $('.load-more').attr('lastID');
alert(lastID);
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data: {id: lastID },
dataType: 'json',
beforeSend:function(data){
$('.load-more').show();
},
success:function(data){
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json=="") {
$("#bottom").append('<div class="btn btn-default col-md-6" >'+'No More Results'+'</div>');
$("#Load_more_data").hide();
}else{
$postID=json[json.length-1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function (key, data) {
var post_id=data.id;
// alert(data_id);
var post_status=data.status;
var status_image=data.status_image;
var multimage=data.multimage;
if(!post_status=="" && !status_image==""){
alert(post_id);
$("#status_data").append('<div class="panel-footer " onload="select_comment('+post_id+');"><div class="row"><div class="col-md-12">13 people like this</div></div><ul class="media-list"><li class="media_comment" id="comment_div'+post_id+'"></li><li class="media"><div class="media-left media-top"><?php echo img($user_file_image); ?></div><div class="media-body"><div class="input-group"><form action="" id="form_content_image"><textarea name="textdata" id="content_comment_image" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_image" onclick="comment_here_image('+post_id+');">Comment</button></form></div></div></li></ul></div></div>');
}
});
}
}
});
}
function select_comment(post_id)
{
// alert(post_id);
var Post_id=post_id;
var User_id = $('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/select_comment"); ?>',
data: {Post_id:Post_id,User_id:User_id},
dataType: 'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function (key, data) {
var comment=data.comment;
var post_id=data.post_id;
$post_id=post_id;
$("#comment_post_id").attr('value',$post_id);
$(#comment_div).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
});
}
});
}
here is the loop.
UPDATE: (try to update the loop something along this lines..)
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function (key, data) {
var comment=data.comment;
var post_id=data.post_id;
var mediaID = '.media_comment' + post_id;
$( mediaID ).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
});
when you loop over json object try to insert something like this there,, if that code is on the php side ofcorse..
$sel = ".media_comment$post_id";
$img = img($user_file_image);
$com = $comment;
echo "$($sel).append('<li class='media-top'>$img <p>$com</p> <br><a href='#'>Like</a><a href='#'>Reply</a> </li>');";
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.
I made a form using radio button (for poll).
And I use $.ajax to submit the form.
but when I use $("#polling").serialize() for the data, there is nothing sent/requested...
Are there any problem with the radio button?
$(function(){ $("input[name=vote]").click(function(){
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: BASE_URL + "/processes/polling.php",
data: $("#polling").serialize(),
success: function(msg){
document.getElementById("poll-content").innerHTML = msg;
}
});
});
and this is the HTML code :
<div class="poll-content" id="poll-content">
<form action="#" id="polling">
<?php
$poll = Polling::_find_by_id($id);
$view = "<h4 class=\"polling\">" . $poll->nama . "</h4>";
$options = explode(",", $poll->opsi);
foreach ($options as $i => $option) {
$view .= "<input type=\"radio\" class=\"option\" name=\"option\" value=\"" . $option . "\" />";
$view .= $option;
$view .= "<br />";
}
$view .= "<input type=\"hidden\" name=\"id_polling\" value=\"" . $poll->id_polling . "\">";
echo $view;
?>
<input type="button" name="vote" value="Vote" />
</form>
</div>
At first look it appears you are missing a closing });
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: $("#polling").serialize(),
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
}); //<-Missing this to close out dom ready
Edit, after looking at your markup, doing $("div[class=poll-content]").text("Loading"); will destroy the form so your call to $("#polling").serialize() will fail.
Try to capture the form before you call .text()
$(function() {
$("input[name=vote]").click(function() {
var id_polling = $("input[name=id_polling]");
var formData = $("#polling").serialize();
$("div[class=poll-content]").text("Loading");
$.ajax({
type: "POST",
url: "/echo/html/",
data: formData,
success: function(msg) {
document.getElementById("poll-content").innerHTML = msg;
}
});
});
});
Example on jsfiddle
Side note, you can use the class selector instead of the attribute selector $("div.poll-content").text("Loading");