Get a new Sql id after submition by Ajax - javascript

After submission a comment of a post with ajax, comment.php display new comment with its own SQL auto increment id. like:
// Here $id comes from SQL after submit data
<div class="comment'.$id.'"><ul>
// new comment
</ul></div>
Now, how to get this new id in Ajax complete: function(data) from comment.php to show it post.php page into .
I tried this code which not working:
complete: function(data){
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
}
complete code:
$(".repfrm").click(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST", url: "comment.php", data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
});
}
});
}
else //alert("Please fill all fields!");
error_message();
});

It helps to describe exactly how your code isn't working, but I think I found it:
var ID = $(this).attr('id').replace('comment','');
should be
var ID = $(this).attr('class').replace('comment','');

I suppose you need this:
This is used to get the last insert id, ID of last record inserted
Send this into your ajax call back and append as the ID.
Let us know if you want to know how to send this from comment.php

your attribute is not id it is class so use something like this:
var ID = $(this).attr('class').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
see this for sample:
<script>
$( document ).ready(function() {
var ID = $('div').attr('class').replace('comment','');
alert(ID);
});
</script>
</head>
<body>
<div class="comment1"></div>
</body>

Related

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

how to make a variable to echo this data on ajax

I have ajax code:
<script type="text/javascript">
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
$("#title-modal").html(nama_puskesmas);
$("#exampleModalCenter").modal('show');
$("#button-submit").html(`Lihat data`)
$("#button-submit2").html(`Kirim Pesan`)
}
})
})
</script>
If I run this program, it will view like this:
Data yang belum diupload
1.Form Lap PTM
2.Form Lap Posbindu
3.Form Lap IVA
4.Form Lap Jiwa
5.Form Lap Indera dan Gimul
6.Form Lap Diare
7.Form Lap LROA
8.Form Lap Thypoid
9.Form Lap Laporan Hiv Aids dan IMS
10.Form Laporan Hepatitis
I will then echo this data to my another function.
How can I make a variable from this code?
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
To echo on this :
$("#button-submit2").html(`Kirim Pesan`)
Or can I make an echo to this #button-submit2?
<script type="text/javascript">
// this var contains a new element, which is not yet appended to the DOM
var $receivedItems = $('<div></div>');
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
// instead of echoing it directly by appending it to the DOM, store your list items in the hidden or not-appended element in your variable
$receivedItems.append("<li>"+obj.format+"</li>");
$("#list-format").append("<li>"+obj.format+"</li>");
});
// ..... your other stuff
var buttonHtml = `Kirim Pesan`;
var $button2 = $(buttonHtml);
$button2.on('click', function(e) {
// be aware to use href only as a fallback if js does not work. otherwise your url will change and js won’t be executed
e.preventDefault();
// on click, you can append the list items stored in $receivedItems
$("#list-format").append($receivedItems.children());
});
// be aware of nesting a and button tags, you shouldn’t
$("#button-submit2").append($button2);
}
})
})
</script>
I put some comments in the code. In this approach you can store all received items in a jQuery object which is not yet appended to a DOM node. It will be by triggering the on-click event which is added to the submit2 button.

Jquery ajax issue in php and ajax code

Here in the following code in jquery i get the alert test1 but when i try to get alert test2 i dint got that... there is some issue in code please help me to resolve.
$(document).ready(function() {
$(".delete-item-details").click(function() {
alert('test1');
var id = $(this).attr('ids');
alert('test2');
var order_id = $("#order_id").val();
goto_url = "/order/DeleteOrderDetailItems/" + id;
dataString = 'id=' + id + '&order_id=' + order_id;
$.ajax({
type: "POST",
url: goto_url,
data: dataString,
cache: false,
success: function(html) {
$("#row-id-" + id).fadeOut();
$("#total_span").html(html);
}
});
});
});
Please change this three lines in code and you will definitely get alert !!
alert('test1');
var id=$(this).attr('id'); // here you have written ids
alert('test2');
The default attribute is 'id' not 'ids'
If still now clear let me know i will help you out.
TRY
var id = $(this).prop('ids');

passing array value to url in jquery ajax

i'm passing the array value to url like this
view code
from_multiselect('functio[]',$function,'','id=function')
baseurl/test/roles?id=1,2,3
this is my jquery
$("#role > option").remove();
var id = $('#function').val();
alert(id);
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+id,
success: function(roles)
{
alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
Page give error when i pass the array value in url like Disallowed Key Characters.
Thank in advance
and then post this array like this:
$("#role > option").remove();
var id = $('#function').val();
var valArray = id.split(',');
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+valArray,
success: function(roles)
{ alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
in the method add parameter to accept array.
This is CodeIgniter error.
So, to solve this, please go to
/application/config/config.php
AND
search for
$config['permitted_uri_chars']
change to:
$config['permitted_uri_chars'] = 'a-z 0-9~%\.\:_\+-,?&=';

Pass string through Jquery and ajax to PHP

I've been struggeling with this problem for a while now and I still can't understand why it's not working. I've tried multiple possibilites but none of them worked, so can someone please help me with how to pass var superstr = $( "#savelyric" ).text(); through Ajax and into my database? This is what I've been experimenting with:
function saveinPHP() {
//alert("Came here");
var lyr = $( "#savelyric" ).text();
var superstr = { lyricsave:lyr }
//var superstr = 'lol';
//var hashString = "lol";
//var data = { yoururl:'hmm'}
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: superstr,
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~" + hashString);
//window.location.reload(true);
}
});
}
And as you can see, I've tried with multiple ways of doing it, but it just never works. I don't understand how on earth you do this. And the PHP file goes like this:
<?php
include ('db_connect.php');
$data = $_POST['data'];
$query = "UPDATE song SET time='".$data."' WHERE id='1'";
mysqli_query($query);
?>
And yes, I'm fully aware that my database is vulnerable for SQL injections, and I will fix that as soon as I get this working.
This is what I've tried, but I can do things completely different if you think that is necessary.
Right now I got the JS:
function saveinPHP() {
var superstr = $( "#savelyric" ).text();
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: {superstr: superstr},
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~");
//window.location.reload(true);
}
});
And PHP
<?php
include ('db_connect.php');
$data = $_POST['superstr'];
$query = "UPDATE song SET lyrtime='".$data."' WHERE id='1'";
mysqli_query($query);
?>
Only change this line:
var superstr = { lyricsave:lyr }
with
var superstr = { data:lyr }
You are trying to pass var superstr = $( "#savelyric" ).text(); as your question states, but in your code you are actually assigning:
var superstr = { lyricsave:lyr }
Change it to:
var superstr = $( "#savelyric" ).text();
UPDATE (per Kevin B's comment)
You also need to change the following:
data: {superstr: superstr},
and in your PHP:
$data = $_POST['superstr'];
Also, why are you tring to set it to the time column? I have not seen your tables, but a wild guess will tell me that time is a different datatype (TIMESTAMP/DATETIME maybe?) and is rejecting your data. Don't you want to set it to a column named data or lyrics or anything which contains text?

Categories

Resources