how to empty the function parameter once it passes to the function? - javascript

I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
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;
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="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png

Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}

Related

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Append a button with a specific ID returned from PHP is not working

I am appending a button to a row when adding via Ajax and PHP:
var addHistory = function()
{
var patient_medication = $("#patient_medicationn").val();
var disease = $("#disease option:selected").text();
var patient_side_effect = $("#patient_side_effect").val();
var pid = $("#pid").val();
var elem = '<button type="button" class="btn btn-danger btn-sm"
id="delete_disease" name="delete_disease"><i class="fa fa-remove"></i>
</button>';
$.ajax({
url: '../php/history.php',
data: {pid: pid, patient_medication: patient_medication, disease:
disease, patient_side_effect: patient_side_effect},
type: 'POST',
dataType: 'TEXT',
success:function(resp)
{
console.log(resp)
$("#after_th").after("<tr id='resp'><td>"+disease+"</td><td>"+patient_medication+"</td><td>"
+patient_side_effect+"</td><td>"+elem+"</td></tr>")
},
error:function(resp)
{
console.log(resp)
}
})
}
And on click:
$(document).ready(function()
{
$("#add_history").on('click', addHistory);
});
In my php file:
$addHistory = "INSERT INTO history(patient_medication, patient_side_effect, disease, patient_id, clinic_id)
VALUES(:patient_medication, :patient_side_effect, :disease, :patient_id, :clinic_id)";
$ExecAddHistory = $conn->prepare($addHistory);
$ExecAddHistory->bindValue(':patient_medication', $patient_medication);
$ExecAddHistory->bindValue(':patient_side_effect', $patient_side_effect);
$ExecAddHistory->bindValue(':disease', $disease);
$ExecAddHistory->bindValue(':patient_id', $pid);
$ExecAddHistory->bindValue(':clinic_id', $clinic_id);
$ExecAddHistory->execute();
$lastId = $ExecAddHistory->lastInsertId();
echo $lastId;
I am echoeing the last insert ID so I can append it to the newly added <tr> and then if directly the user clicked on the remove button, to delete directly if a mistake happened while adding the history.
Now everything working properly and the new row is appending, but it's remove button does not work at all.
The remove button of already existing rows works fine:
$("#delete_disease ").on('click', function()
{
var elem = $(this).closest('tr');
console.log(elem)
var patient_medication_id = $(this).closest('tr').attr('id');
var pid = $("#pid").val();
if(confirm("Are you sure that you want to remove the selected history?"))
{
$.ajax({
url: "../php/deleteDiseaseFromHistory.php",
type: 'POST',
data: { pmid: patient_medication_id, pid: pid},
dataType: 'TEXT',
success:function(resp)
{
if(resp="deleted")
{
elem.fadeOut(800, function() {
//after finishing animation
});
}
},
error:function(resp)
{
alert("Please try again");
}
});
}
});
You need
$(document).on('click', '#delete_disease ', function(event)
in place of
$("#delete_disease ").on('click', function()
Since the content has been loaded through AJAX.

Need to get some value of variable from linked lists

I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);

Delete data from database without reloading the page

I want to delete data from database without refreshing the page. My code is working but after deleteing a product needs to refresh the page. I want something like this
Here is my js code:
<script>
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
$.ajax({
type: "POST",
async: false,
url: "delete_product.php",
data: {
object_id: id
},
dataType: 'json',
success: function(data) {
location.reload();
}
});
}
});
return false;
});
</script>
and the delete_product php code:
<?php
// check if value was posted
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// set product id to be deleted
$product->id = $_POST['object_id'];
// delete the product
if($product->delete()){
echo "Object was deleted.";
}
// if unable to delete the product
else{
echo "Unable to delete object.";
}
}
?>
Please show me a way to make it!
I see no place where the you're targeting something in the page, but this is what I would use:
<script>
function swapContent(href, url_data, target) {
$.ajax({
type: 'GET',
cache: false,
url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data
success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request
//load more data to "target" value div
target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below
}
})
}
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
swapContent(base_url, url_data, target) //set variables
}
});
return false;
});
</script>
note: because of how much ajax I use, I keep an ajax function by itself

How do I exit the click function?

So with this example I have form with a hidden field and a button called ban user. When the ban user button is clicked, it submits the value in the hidden field and sends the ajax request to a java servlet. If it is successful, the user is banned and the button is changed to "unban user". The problem is when I click the button once and ban a user and I try to click it again to unban, I'm still inside the click event for the ban user and I get the alert "Are you sure you want to ban the user with the id of ...?". How do I exit the click event to make sure when the button is clicked a second time, it starts at the beginning of the function and not inside the click function? I have tried using 'return;' as you can see below but that doesn't work.
$(document).delegate('form', 'click', function() {
var $form = $(this);
var id = $form.attr('id');
var formIdTrim = id.substring(0,7);
if(formIdTrim === "banUser") {
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(7);
var dataString = $form.serialize();
var userID = null;
userID = $("input#ban"+ trimmed).val();
$("#banButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to ban the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserBan",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#banUser'+trimmed).attr('id','unbanUser'+trimmed);
$('#ban'+trimmed).attr('id','unban'+trimmed);
$('#banButton'+trimmed).attr('value',' UnBan User ');
$('#banButton'+trimmed).attr('name','unbanButton'+trimmed);
$('#banButton'+trimmed).attr('id','unbanButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
else if(formIdTrim === "unbanUs") {
//Stops the submit request
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(9);
var dataString = $form.serialize();
var userID = null;
userID = $("input#unban"+ trimmed).val();
$("#unbanButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to UNBAN the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserUnban",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#unbanUser'+trimmed).attr('id','banUser'+trimmed);
$('#unban'+trimmed).attr('id','ban'+trimmed);
$('#unbanButton'+trimmed).attr('value',' Ban User ');
$('#unbanButton'+trimmed).attr('name','banButton'+trimmed);
$('#unbanButton'+trimmed).attr('id','banButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
});
Try with:
$("#banButton"+ trimmed).off('click').on('click', (function(e){......
I had similar problem and this was solution

Categories