Trouble with jQuery Script for On click event - javascript

My code seems to not run the jQuery at all for some reason, I have spent lots of time attempting to figure out what's wrong and have tested my delete PHP file separately
jQuery script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$('#button').on('click', '#btn',function()) {
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});
</script>
Php:
$query = "SELECT * FROM accounts";
$resultset= mysqli_query($connection,$query);
while($row = mysqli_fetch_array($resultset,MYSQLI_NUM)){
echo $row[0]." ".$row[1]." ".$row[2]." ".'<input type="submit" class="btn" name="".$row[0]."" value="delete" />';
echo "</br>";
}

use this :
$(document).ready(function(){
$('.btn').click(function(e){
e.preventDefault();
alert('Button is pressed');
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});

Related

JQuery & PHP: How to pass appended button value to jquery? Is it possible?

I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?
<!DOCTYPE html>
<html>
<head>
<title>Infinite Software Blog</title>
<meta name="viewport" content="width=device-width, scale=1.0">
<script type="text/javascript" src="/blog/jquery/jquery-3.2.0.min.js"></script>
<script>
$(document).ready(function () {
$('.del_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/helpers/delete_post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
alert("Post was successfully deleted");
});
});
$('.edit_btn').click(function () {
var clickBtnValue = $(this).val();
console.log(clickBtnValue);
var ajaxurl = '/blog/edit_post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
window.location.assign("/blog/helpers/updatePost.php");
});
});
$('.post_content_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/view/post.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function () {
window.location.assign("/blog/post.php");
});
});
$('.more_posts_btn').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = '/blog/helpers/show_more_posts.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (output) {
$(".content").append(output);
});
});
});
</script>
<link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>
</head>
show_more_post.php
<?php
if (isset($_POST['action'])) {
include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
$post = new posts();
$postsToDisplay = $post->getPostsQty($_POST['action']);
$newRecordsIndex = $_POST['action'];
for ($i = 1; $i <= $postsToDisplay; $i++) {
$record = $post->getPost($newRecordsIndex);
$newRecordsIndex++;
$elementToAdd = '<article class="topContent"><header><h2><a href="#" title="' . $record[1] . '">' .
$record[1] . '</a></h2></header><footer><p class="post-author">Author: ' . $record[2] . '</p>' .
'</footer><content>' . $record[6] . '</content><footer><p class="post-date">Publish date: ' .
$record[3] . '</p>' . '<p class="post-time">Publish time: ' . $record[4] . '</p><form><button type="submit"
title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
</form></footer></article>';
echo($elementToAdd);
}
}
I will suggest you to go in a simple way, You can use live table update strategy where you can simply update the data directly from the UI and delete or add as well. Find the below code
$(document).ready(function(){
function load(){
$.ajax({
url:'db.php',
method: 'POST',
success:function(data){
$("#load").html(data);
}
});
};
load();
$(document).on('click', '.bton', function(){
var name= $(this).data("id");
if(confirm("Do you want to delete this row"))
{
$.ajax({
url: 'delete.php',
method: 'POST',
data:{id:name},
success: function(data){
alert(data);
load();
}
});
}
});
$(document).on('click','#add', function(){
var addName= $("#name").text();
var addComp= $("#company").text();
$.ajax({
url:'insert.php',
method:'POST',
data: {name:addName, company:addComp},
success:function(data){
alert(data);
load();
}
});
});
$(document).on('blur','.type', function(){
var editID=$(this).data('id1');
var editName= $(this).text();
alert(editName);
})
});
for reference click here, download file and use to understand better.
Use $(document).on('<event>', '<selector>', function() {}); to make available events on dom elements, that creates after script init.

Binding a dynamically populated <select> to produce a third

I am trying to create a chain of drop downs in a form. The first select is populating the second form, but I can't call a third from the results. I have figured out (I think) that it is a binding issue, but how would I go about correcting this.
The JavaScript on the page:
<script>
var selected_form_div = null;
var frm_submit_event = function(e){
var $this = $(this); // the button
//var frm = $this.closest(form);
var frm = $('#'+selected_form_div + " form");
console.log(frm);
console.log(frm.serialize());
e.preventDefault();
$.ajax({
type: "POST",
url: "classes/forms/ajaxPost.php",
data: frm.serialize(),
dataType: "text",
success: function($result) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$('#'+selected_form_div).html($result);
},
error: function() {
alert('error handing here');
}
});
}
function loadSubSelects(value,form,select)
{
$.post("classes/forms/update_form.php",{catid : value,form : form,select : select},function(data)
{
jQuery('#sub_categories').html(data);
});
}
$(document).ready(function(){
$('._form_selector').click(function(e){
e.preventDefault();
var $this = $(this);
$.get('classes/forms/forms.php', {
form: $(this).attr('form_data')
},
function($result){
$('#'+$this.attr('form_div')).html($result);
//selected_form_div = $this.closest("form");
selected_form_div = $this.attr('form_div');
//console.log($result);
});
console.log($(this).attr('form_data'));
});
$(document).on("click", '.frm_submit_btn', frm_submit_event);
$('._pay').click(function(){
var $this = $(this);
console.log($this.attr('form_id'));
$('._form_pay').css('display', 'none');
$('#form_'+$this.attr('form_id')+'_pay').css('display','block');
});
});
function showForms(form,click_listen) {
jQuery.noConflict();
jQuery('form').hide();//hide initially
jQuery("#click_listen").click(function(e){
jQuery(form).toggle('fast');//or just show instead of toggle
});
}
function reportError(request) { alert("Something Went Wrong, Please Submit A Support Ticket.");}
</script>
and LoadSubSelects is the function in question, and the PHP results:
What I am trying to bind in the results (I think)
the PHP code:
$query="SELECT letter_id,letter_title FROM letter_template where letter_category_id = $catid";
$result = mysql_query ($query) or die(mysql_error());
echo'<select name="sselect1" class="e1" style="width:100% !important; height: 1.85em !important; color: #a8a8a8 !important; border-color:#d7d7d7 ! onChange="loadSubSelects(this.value,\'write_letter\',this.name)"><option value="0">Please Select A Letter</option>';
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){
//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['letter_id'])."\">".$catinfo['letter_title']."</option>";
}
echo"</select>";
echo htmlspecialchars($catinfo['letter_id']);
Any help would be most appreciated, thanks so much guys :)

javascript work on windows but don't work on linux

This javascript dropdown list auto complete work on windows local server in PHP aplication, but when i try this funcionality when aplication is on linux server nothing happen. Maybe i should change live method into on? But how?
This is javascript
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
$("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.country_name').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
});
$(document).o("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
$("#result").fadeOut();
}
});
$('#search_keyword_id').click(function(){
$("#result").fadeIn();
});
});
</script>
And this is search.php
include('db.php');
if(isset($_POST['search_keyword']))
{
$search_keyword = $polaczenie->real_escape_string($_POST['search_keyword']);
$sqlCountries="SELECT name FROM shop WHERE name LIKE '%$search_keyword%'";
$resCountries=$polaczenie->query($sqlCountries);
if($resCountries === false) {
trigger_error('Error: ' . $polaczenie->error, E_USER_ERROR);
}else{
$rows_returned = $resCountries->num_rows;
}
$bold_search_keyword = '<strong>'.$search_keyword.'</strong>';
if($rows_returned > 0){
while($rowCountries = $resCountries->fetch_assoc())
{
echo '<div class="show" align="left"><span class="country_name">'.str_ireplace($search_keyword,$bold_search_keyword,$rowCountries['nazwa']).'</span></div>';
}
}else{
echo '<div class="show" align="left">Brak</div>';
}
}

$_POST won't receive ajax

AJAX works fine, but $_POST does not have a value.
What I have tried:
$data = json_decode(file_get_contents('php://input'), true); &
$post = json_decode($data); into storecart.php
Changing the data into 'jCart=' + jData'
removing datatype (Jaromanda X)
answer (Umakant Mane)
cart is an array of objects
Javascript:
$(document).ready(function(){
$("#showcart").click(function(event){
event.preventDefault();
showcart();
url = 'cart.php';
$(location).attr("href",url);
});
});
function showcart(){
var jData = JSON.stringify(cart);
$.ajax({
url:"storecart.php",
type:"post",
data: {jCart : jData},
datatype: "json",
success: function(data){
console.log("SUCCESS")
console.log(jData);
},
error: function(data){
console.log("REDO")
}
});
}
storecart.php:
<?php
if(isset($_POST['jCart'])){
echo "Right";
}else{
echo "Wrong";
}
?>
How do get the $_POST to accept the json.stringify?
SOLUTION:
SOLVED:
All i did was add a form that has a hidden value
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(cart)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone that has answered but hope this helps.
$(document).ready(function(){
var data = {one:"one", two:"two", three:"three"};
var jsonData = JSON.stringify(data);
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"POST",
data:{cart:jsonData},
success:function(response){
console.log(response);
}, error:function(err) {
console.log(err);
}
})
});
});
PHP
<?php
if(isset($_POST['cart'])){
echo "Right";
}else{
echo "Wrong";
}
?>

JQuery receive value in php

I've tried to get some values with button through jquery into php. Which i've done like this.
HTML
<button class="button" name="reject" value="<?php echo $row['mail']; ?>" type="submit">reject</button>
Jquery
$(document).ready(function(){
$('.button').click(function(){
var url = window.location.href;
var whichBtn = $(this).attr("name");
var mail = $(this).attr("value");
var ajaxurl = url,
data = {'mail': mail, 'whichBtn' : whichBtn};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert(whichBtn);
alert("action performed successfully");
});
});
});
PHP
if(isset($_POST['mail']))
echo $_POST['mail'];
Well, the thing is that POST[mail] is not set and I don't have clue why.. Could you help?
You need to add event.preventDefault() to your click handler. Since it is a submit button it is navigating away from the page before your Javascript gets executed. Try this:
$(document).ready(function(){
$('.button').click(function(event){
event.preventDefault();
var url = window.location.href;
var whichBtn = $(this).attr("name");
var mail = $(this).attr("value");
var ajaxurl = url,
data = {'mail': mail, 'whichBtn' : whichBtn};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert(whichBtn);
alert("action performed successfully");
});
});
});

Categories