Creating a link to pass a PHP venerable to jQuery - javascript

I can not seam to be able to figure out why the code below is not adding the id to the jQuery script, I do know that the $value['expid'] has the value of 13 in it and it is my understanding that echoing this PHP code will make jQuery see the number that is in the venerable.
The leak that creates the data-id value grabbed by the jQuery script
<a href='#' class='open-editexpenses' data-target='#editexpenses' data-id='<?= htmlspecialchars($value['expid'], ENT_QUOTES, 'UTF-8') ?>'>Edit</a>
The jQuery script
$(document).on('click', '.open-editexpenses', function() {
var id = $(this).data('data-id');
alert(id);
$.ajax({
type: "POST",
url: "expmodal.php",
data: {id: id},
success: function(html) {
$('body').append(html);
$('#editexpenses').modal('show');
}
});
});

Use
$(this).data('id')
Or
$(this).attr('data-id');
(The first is usually preferable)

Related

Turning jquery into an includable, callable function

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!
I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.
To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview

Ajax / Jquery refresh page after variables are passed

Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}

jQuery select every time first element

HTML:
<div class="vote" id="<?php echo $id; ?>">
jQuery:
$('.vote').on('click', function() {
var div = $(".vote").attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(".vote").attr('id')
},
success: function(data) {
alert(div);
}
});
});
this works, but div var it's always first element - and runs twice (two divs with vote class).
I use AJAX for displaying results (divs with vote class) also.
Why is this happening and how can I fix?
You need to use this, which refers to element which invoked the element.
var div = $(this).attr('id'); //this.id;
When you are using $(".vote").attr('id') it will always return you id of first element.
As you are using id to store custom data. I would recommend you to use data-* prefixed custom attribute which can be fetched by using .data()
<div class="vote" data-id="<?php echo $id; ?>">
Then you can use
var id = $(this).data('id');
You need to use current elements clicked context this:
var div = this.id;
Replace your $('.vote') to $(this) like this below:
$('.vote').on('click', function() {
var div = $(this).attr('id');
$.ajax({
type: "POST",
url: "vote.php",
data: {
id: $(this).attr('id')
},
success: function(data) {
alert(div);
}
});
});
Use this.id instead of $('.vote').attr('id'), because javascript will get the first id he founds if you use $('.vote').attr('id')

Using AJAX/Jquery to Replace div

I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

Categories

Resources