I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/
Related
My HTML(simplified):
<input class="text" type="text" id="emailbox" value="None">
Note: content1 is the ID of a div that contains the email retrieved from a file using PHP and this part works (it returns the email)
My Javascript:
var email = $.trim(document.getElementById('content1').textContent);
if (!email == "") { document.getElementById("emailbox").value = email; }
The value of the input box is not changing at all
The error is with the line
document.getElementById("emailbox").value = email;
or with the html
ALL CODE: https://pastebin.com/5JSLzHdw
I grabbed your Pastebin code, and if I set the content of your content1 div to be this:
<div id="content1" style="display: none;">EXAMPLE#EXAMPLE.COM</div>
then the following code works as a replacement for the script starting at line 327. This is completely unstyled and I haven't changed any of the code except the essential to make it work.
<script>
$(document).ready(function(){
var email = document.getElementById('content1').textContent;
var register = document.getElementById("para7");
var login = document.getElementById("para8");
var logout = document.getElementById("para9");
if (email !== "") {
register.style.display = "none";
login.style.display = "none";
// It's an input so you need to set VALUE, not innerHTML
document.getElementById('mailbox').value = email;
console.log("We are here")
} else {
window.location.href = "../login/";
logout.style.display = "none";
}
document.getElementById("logo").addEventListener("click",function(){
document.getElementById("homebutton").click();
});
document.getElementById("account").addEventListener("click",function(){
if(!email == ""){
document.getElementById("accountbutton").click();
}
});
})
</script>
Others correctly commented that you shouldn't run your code until the document is ready, hence wrapping it inside that jQuery ready handler.
As you are using jQuery, I would suggest replacing all of your document.getElementById("whatever") instances with the jQuery method $("#whatever") as it will make the code more concise.
If I try your code like this, then document.getElementById('content1') returns null
Did you wrap your code in
window.onload = function() {
// run your script in here
}
or for jQuery
$(document).ready(function() {
...
}
Otherwise your code may try to access the DOM while it isn't ready yet.
See here https://stackoverflow.com/a/13921149/11472484 and here Running jQuery code before the DOM is ready?
I know this is a very concrete issue but I've struggled with this code for the last 2 hours and I can't find anything on the topic or figure out how to solve it.
I have an issue with a jQuery Ajax Post request. I am trying to make a section on my page where I display the users current level. When a user interacts and does something that increases the level on the site the level should also increase in the DOM/client's browser. Therefore I've added a setinterval that allows the request to run every 5th second. And if the $(response).text() is different from the current div's .text() where i am rendering the current level I want to append this new response from the ajax request.
Maybe the answer is more obvious than I think.... I have added the code below
Ajax page:
$(document).ready(function () {
function getLevel() {
var getLvlData = $.ajax({
url: "AjaxRequests.php",
type: "POST",
data: {type: "4", lvl_r_type: 1}
});
getLvlData.done(function (response, textStatus, jqXHR) {
var innerLevelHTML = $("#LevelContainer");
if (($(response).text()) != ($(innerLevelHTML).text())) {
innerLevelHTML.html("");
innerLevelHTML.append(response);
}
if ($(response).text() == $(innerLevelHTML).text()) {
alert("the same");
}
});
}
var levelChecker = setInterval(function () {
getLevel();
}, 1000);
getLevel();
});
AjaxRequests.php:
if ($_POST["type"] == "4" && isset($_POST["lvl_r_type"])) {
$returnVal = htmlentities($_POST["lvl_r_type"]);
if (!empty($returnVal)) {
if ($returnVal == 1) {
?>
<div id="chartWrapper">
<div>
<canvas id="doughnut-chart"></canvas>
</div>
<div id="chart-center">
<div>
<div><h1>0%</h1></div>
<div><p>GX 0 / 1</p></div>
</div>
<div><p>LVL 0</p></div>
</div>
</div>
<div id="progressList">
<div><p>View tasks</p></div>
</div>
<?php
}
}
}
?>
html page
<div id="LevelContainer"></div>
Try using trim since a white space could be treated as a part of the text.
if (($(response).text().trim()) != ($(innerLevelHTML).text().trim())) {
...
One alternative approach I can think of, off of my head is, to set a hash inside a data attribute say data-hash="" whenever you set the html of that div, and then whenever you have a new ajax response you can generate a hash on the fly and compare that to the existing one and if a change is found just update the html and the hash value for that attribute.
This process minimises the confusion that may be caused due to dom being updated by some script.
Also, Instead of
innerLevelHTML.html("");
innerLevelHTML.append(response);
Why not just just set the html directly as
innerLevelHTML.html(response);
So I have this unordered list of items that is made from querying a mysql database
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
I want there to be an onclick event that will pass 'apple' when I click apple and 'orange' when I click orange.
I also want to pass this information to another page through php. So this is my idea for the javascript function.
<script>
function passName(obj){
var pass = "<?php $x= " + obj.getName() + " ?>";
}
function getname(obj){
return 'string';
}
</script>
My Question: is there a method that exists within JavaScript that allows me to pull the raw string value of my unorderedlist without writing my own function? If I have to write my own JavaScript function, is there a way to set the 'name' strings automatically, while the list is populating?
Use JQUERY AJAX for send data into php page
/* Get value from clicked li */
$(function() {
let value = "";
$('ul li').on("click", function() {
value = $(this).text();
console.log(value);
});
/* AJAX for send value into result.php page */
$.post("result.php", {value: value}, function(res) {
console.log(res); // return from result.php page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
result.php
if(isset($_POST['value']) && !empty($_POST['value'])) {
echo $_POST['value'];
}
This is how you can do it. On click you can change the page or do whatever you want. In the new url you can append the fruit value as a parameter to pass it to php
<ul>
<li onclick="fruitsClick('apple')">apple</li>
<li onclick="fruitsClick('orange')">orange</li>
<li onclick="fruitsClick('pear')">pear</li>
</ul>
<script>
function fruitsClick(fruit){
// do whatever you want
window.location.href = "[yourpageurl]?fruit=" + fruit
}
</script>
I'm currently working on Ajax and jQuery live search which finds a results in a JSON file. Script is working fine, but the is only one problem - it's duplicating the result data.
EXAMPLE:
MARKUP:
<div class="row">
<h3>Live Search Results</h3>
<div id="update-results">
<p>event_name | club_name | memberid</p>
<ul id="update">
<!-- <li></li> -->
</ul>
</div>
</div>
SCRIPT:
$('#search').keyup(function() {
var searchField = $('#search').val();
var $update = $('#update');
$update.empty();
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
var vals = jQuery.parseJSON(data);
if($.isArray(vals['Event'])) {
$.each(vals['Event'], function(k,v){
$update.append("<li value='"+v['id']+"'><a href='#'>" + v['event_name'] + "</a></li>");
});
} else {
$update.append("<li value='"+vals['Event']['id']+"'><a href='#'>" + vals['Event']['event_name'] + "</a></li>");
}
});
});
I've tried to debug and stop the error, but it was unsuccessful. Can anyone help me please with that?
Put the empty() inside the response handler:
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
$update.empty();
basically you are clearing the list on every keystroke (rapid), then requesting the data, then (sometime later) appending the results that come back (which could be multiple results depending on the timing).
I didn't reproduce your error but I suspect that you have problem with multiple request to server and adding them all instead of last one. Probably adding below code will fix your problem
$update.empty();
Anyway I suggest you to use 2 more functions: throtlle and debounce from underscore to prevent too much request on every keyup.
Also you could try Rx.js witch give following example (https://github.com/Reactive-Extensions/RxJS):
var $input = $('#input'),
$results = $('#results');
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
.map(function (e) {
return e.target.value;
})
.filter(function (text) {
return text.length > 2;
});
/* Now debounce the input for 500ms */
var debounced = keyups
.debounce(500 /* ms */);
/* Now get only distinct values, so we eliminate the arrows and other control characters */
var distinct = debounced
.distinctUntilChanged();
Try changing this line $update.empty(); of your code to $update.find('li').remove(); and put it inside the response handler.
This removes all the previous data before you append the new values. Hopefully it might work.
I need to do a fetch using ajax. I need to use this: ajax/get_item_list/group_id/offset/limit/true (return true as JSON) where id comes from a link that user clicks. And when user clicks that link, it should call(?) that "ajax/get_item_list/group_id/offset/limit/tru" to get content to a div. And when user clicks another link (in navigation), it should do that again, but ofcourse it should get new content.
I am using drupal if that info is needed.
//Mario
Have you tried some jquery?
<div id="display"></div>
Click me
And then some javascript:
$(document).ready(function(){
$('a.ajaxToDisplay').click(function(){
$('#display').load(this.href);
return false;
});
});
I get this kind of error on firebug: $(this).href is undefined
[Break on this error] var group_id = $(this).href.replace(/.*#/, '');
this is when i use jcubic's proposal.
//mario
You can use JQuery.
$('a.link_class').click(function() {
var group_id = $(this).href.replace(/.*#/, '');
$.get("ajax/get_item_list/" + group_id + "/offset/" + limit "/true", null, function(data, status, xhr) {
$('#your_div_id').html(data);
});
});
and in html use links:
link
<div id="your_div_id"></div>