I am trying to use jQuery to post a variable to the same page using the following code
file.js
$('#sidebar-nav').on('click', 'li', function() {
var theID = $(this).attr('id');
$.post(location.href, {theID: theID});
});
file.php
<?php
if (isset($_POST['theID'])) {
// do something
}
?>
<html>
<!-- the rest of the page -->
</html>
UPDATED
But theID is not posted to the php file for some reason. My code inside the if statement won't execute. In addition, I used this exactly same method for other removeID in the same js and same php files, it's working well for removeID, but not theID.
And to clarify what location.href is in this situation; it is file.php.
Anyone can help me on this?
You have a syntax error on this line:
var theID = $(this).attr('id'));
// -----------------^
You need to remove the extra closing ). Or even better don't call two functions when the property can be accessed directly:
var theID = this.id;
Or better still, since theID is used in only one place get rid of that variable altogether:
$.post(location.href, {theID: this.id});
To send ajax request to the same page you can keep url parameter empty/removed
TRY
<script type="text/javascript">
$.post({
theID: theID,
success: function (data) {
alert("Data Loaded:");
}
});
</script>
Related
I am having a bit of trouble, and i think my syntax and structure is correct but for some reason the function is failing.
products.php page
i have this function at the bottom of the page which takes the value of $child and adds it to the page, where it gets passed to the Javascript function get_child_options:
jQuery(document).ready(function(){
get_child_options(<?=$child;?>);
});
The function get_child_options is added by my footer.php page
footer.php
function get_child_options(selected){
if(typeof selected === 'undefined'){
var selected = '';
}
var parentID = jQuery('#parent').val();
$.ajax({
url: '/admin/parsers/child_categories.php',
type: 'POST',
data: {parentID: parentID, selected: selected},
success: function (data){
jQuery('#child').html(data);
},
error: function(){alert("Something went wrong with the child options.")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
The error when i load products.php is get_child_options is not declared
I have had a look online and via this forumn and i think the makeup of my function within my products.php page is correct, i just don't understand why its not recognising the function is declared within my footer.php and processing the function.
To add, i have tried this within the function on my products.php page but i got rid of the undefined error but the function didnt pass any data to my get_child_options function.
jQuery(document).ready(function(){
function getchild(child){
var child = <?=$child;?>
get_child_options(child);
}
});
If anyone can help, that would be great and i can't think of what i am doing wrong. TIA
I have reviewed How can I call PHP functions by JavaScript? and feel my situation is different to theres.
I found the issue and it was that my parsers file couldn't see my authentication file to get the function. Once i had add the correct path to the file it all worked.
I've been trying to get my website to do live comments (so the comments appear without refreshing the page) using AJAX with jQuery (the rest of the code being in PHP and HTML). This is the code I have been using, however it doesen't seem to want to work - comments.php is the file which displays the comments, the $comments being variable for the comments.
<script type="text/javascript">
var int=self.setInterval("showComments()",5000);
function showComments(){
$.post( "ajax_comments.php", function( data ) {
$("#comments).html( data );
});
}
</script>
<script type="text/javascript">
var int=self.setInterval(showComments,5000);
function showComments() {
$.post( "ajax_comments.php", function( data ) {
$("#comments").html( data );
});
}
</script>
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
In the setInterval function the first parameter should be a reference to the function, not a string with the name of the function. The string gets executed using the eval() function, which is not recommended and even though it might not be a problem here it is simply best to avoid.
I have a problem with jQuery and PHP.
I have a .php file that contains a variable, for example var surname = "";
The problem that I am facing is, I want remotely access it from a .html file and give it a value from another variable in the .html file.
Is there any way to do it?
Thanks.
Ok, so you said you wanted to get a variable from HTML and send it to the PHP file to change data, that is what the variable 'varfromhtml' is.
You just need to give it a value you want to send, you can get the value of a div using jQuery eg
<div id="div">data</div>
var varfromhtml = $.("#div").val();
The variable 'varfromhtml' is now equal to 'h08sahdas', you can mess around with that to get it right for you.
Here is the final script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var varfromhtml = $.("#div").val();
$(document).ready(function(){
$.ajax({
method: "POST",
action: "myfile.php",
data: {
varfromhtml:varfromhtml
},
success: function(data){
$('#mydiv').val(data);
}
});
</script>
I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}
I'm struggling to get this get request to cooperate. I would like to begin by saying that the PHP side flawlessly. I am now trying to use ajax and jQuery to make it look smooth.
Here is the js:
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
$(this).html(data).fadeIn(200);
});
});
});
$(this).attr("href") refers to a URL that is passed in order to get information from a MySQL database (e.g. hours.php?week=2014-08-11). The value passed in week is updated via PHP every time a link is clicked.
Here is what I get from console.log(data) http://pastebin.com/bGpfjq6r
I've tried converting data (raw HTML) into a jQuery object by doing the following:
var $data = $.parseHTML(data);
However, this just coverts the HTML into an array. I can perform a find for the element:
console.log($($data).find(".schedule"));
but when I view the output of this the context is undefined.
I also tried the accepted answer in this question Extract part of HTML document in jQuery with no avail:
var foo = $(".schedule", $data);
console.log(foo);
This still has an undefined context.
Ideally, I want to grab just the information in .section and replacing the current in .section with the information captured from the GET request. .section is part of the document as well as what is returned from the request.
There are no errors in the console. jQuery version is 1.11.1.
My apologies if the question is poorly written. I tried to write it in a general way so it may apply to other people too. Let me know if you need additional information.
Try using jQuery filter() function.
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
// apply filter function here to find new schedule div
var newSchedule = $(data).filter(".schedule").eq(0).html();
$(this).html(newSchedule).fadeIn(200);
});
});
});
Try wrapping the response so you can parse it...
$(document).ready(function() {
// Create named function to Initialize the on click event capture
function initAJAX() {
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
var response = $('<div>' + data + '</div>');
var contents = response.find('.schedule').html()
$(".schedule").fadeOut(200, function() {
$(this).html(contents).fadeIn(200);
// After we get the content updated, we have to reinitialize those new anchors
initAJAX();
});
});
});
}
// We have to call this once to start or nothing will happen
initAJAX();
});