PHP jQuery HTML - Getting custom HTML attribute - javascript

I have a PHP file which puts out all orders in the system and adds the custom attribute oid (order-id) to all the links. My links look like:
<a href='#' class='completeOrder' oid='$order_id'>$status</a>
Which gives correct html, when I do inspect element I get this
<a href='#' class='completeOrder' oid='8'>Un-completed</a>
What I would like to do is when this link is clicked, spawn a form with checkboxes and a submit button with the correct order ID in it's html to send. So I can send the form and the order id to another PHP file for processing ( in this case updating the order status ).
What I am doing to spawn the form with the checkboxes is using a jQuery AJAX call, but when I try to alert the order ID to check if jQuery got the oid correctly it tells me its undefined... :
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
getCompleteOrderTools();
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools() {
var o_id = $(this).attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}

Your main issue was that you are referencing this in wrong context as the this available in your function getCompleteOrderTools is different that this that you wanted to refer for the click event of your desired link.
You have 2 options :
either use jQuery(this).attr('oid');
Or
use jquery data attributes
<a href='#' class='completeOrder' data-oid='$order_id'>$status</a>
jQuery(this).data('oid');
So your code with .attr will look like :
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
var myThis = $(this);//This is the 'this' corresponding to the link clicked
getCompleteOrderTools(myThis);
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools(myThis) {
var o_id = myThis.attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}

The jQuery object ain't passed to your function. You should do the following:
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
getCompleteOrderTools(jQuery(this));
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools(_this) {
var o_id = _this.attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}
By passing jQuery(this) to your function, you now have full access to the jQuery object from your click event.

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

Passing parameters between html pages using jquery

I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

Properly attach event change on select in an ajax success response

I am new to JavaScript.
I have this jQuery/AJAX code to refresh data (select, table) in a page:
$(document).ready(function () {
$sport.change(function(){
var $form = $(this).closest('form');
var data = {};
data['sport_id'] = $sport.val();
$.ajax({
type: $form.attr('method'),
data: data,
url: Routing.generate('pphb_championnat_liste'),
success: function(html){
$('#pphb_sportscoringbundle_findligue_ligue').replaceWith(
$(html).find('#pphb_sportscoringbundle_findligue_ligue')
);
$('#champTable').replaceWith(
$(html).find('#champTable')
);
$('#pphb_sportscoringbundle_findligue_ligue').change(function(){
var $form = $(this).closest('form');
var data = {};
data['ligue_id'] = $(this).val();
$.ajax({
type: $form.attr('method'),
data: data,
url: Routing.generate('pphb_championnat_liste'),
success: function(html){
$('#champTable').replaceWith(
$(html).find('#champTable')
);
}
});
});
}
});
});
});
It work fine: populating "ligue select" when I'm changing "sport select" and refresh the table data, refresh the table data when I'm changing "ligue select".
But I have to put
$('#pphb_sportscoringbundle_findligue_ligue').change{ ...}
in the ajax success response. I would like to know how to write it properly.
you should use event delegation for dynamically created objects,
$(document).on("change", "#pphb_sportscoringbundle_findligue_ligue", function () {
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

Targeting specific element jquery

I have searched this on the net however couldn't find a solution, simply I would like to replace the content inside button element with ajax response. The only problem I am facing is that, the whole divs are being changed not the one I click on. If I change the class to id only the first one changes not the specific button I want. So how do I replace the content of specific button?
PHP Code:
while($row = $result->fetch_assoc()){// there are four rows so I have 4 buttons.
echo "<button class=btn btn-primary test' value='."$row['id']".'>."$row['voteup']".</button>";
}
javascript code:
$(function() {
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$(".test").fadeIn('slow').html(response);//this is replacing all 4 buttons not just one, if I change the class to id, only the first one is being replaced with the response. I also tried $( .test", this) but no luck.
}
});
});
});
$(function () {
$('.test').on('click', function () {
var test_val = $(this).val();
$.ajax({
// -------v Set the context of the callback
context: this,
type: "GET",
url: "test.php",
data: {
tar: 'vrate',
test: test_val
},
cache: false,
success: function (response) {
// v--and use `this` here
$(this).fadeIn('slow').html(response);
}
});
});
});
Try to use the $(this) reference here to achieve what you want,
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
var $this = $(this);
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$this.fadeIn('slow').html(response);
}
});
});

Categories