I made a JavaScript code that I’m building to make a shopping cart, but this code is run even if I don’t click it:
function addProduct(prodId) {
var sessionDivId = document.getElementById(prodId);
if (prodId) {
sessionDivId.innerHTML = '<?= $_SESSION['product_id_1']+=1 ?>';
}
}
<div onclick="addProduct('testSession1');">ADD</div>
<div id="testSession1"></div>
Everytime I refresh the website it adds 1 to session testSession1 even if I don’t click the button “ADD”.
Your PHP logic will be run on the server before the user loads the page. To add a product, you will need to store it somehwere else (since the PHP has no longer any control to put +=1 to the cart).
I would make an AJAX request to post a product id to the user shopping cart:
function addProduct(prodId) {
// using jQuery for simplicity of writing
$.ajax({
type: "POST",
url: "/cart/item/" + prodId, // or other backend API endpoint
success: displayNiceUserMessage()
});
}
And of course some error handling in case something goes wrong.
Update
I saw that you did not want to use Ajax. Just so you know, it doesn't need to be any more complex than the code I wrote above. Then in the backend you just add +1 to the session if any user makes a POST request to that url.
But if you do not want ajax, you will need to reload the page when clicking the add button. Like was said in the comments, put a form of type post around the add button (and with a good url to make your server know that it was an added item event that took place), and make the add button a submit type. Then no javascript is needed at all.
Related
I'm helping with an open source project. It's a small Go webserver running on a device containing a Raspberry Pi. I want to be able to have a user click a button on an html screen, which calls a routine in Go, which returns 2 values, a boolean and a string.
What we are wanting to do is see which network interfaces are up on the raspberry pi e.g. is the lan connection up?
To do this I really need to ping a site from each interface. This takes a few seconds for each of 3 interfaces: Lan, WiFi, and 3G.
I can do this when the page is requested and fill in an html template as the page loads, but it means waiting maybe 10 to 15 secs for the page to load, so it seems like something is broken.
So I want to be able to list each of the 3 interfaces on the page and have the user click 'test' which then calls a routine in the underlying Go webserver.
I then need to be able to display the results from the call in a couple of text areas for each interface.
What I have tried:
I have tried registering a Go function (in this case IsLANConnectionUp) using funcmap from the net/html package and calling it from the html template from a JavaScript function, like this:
<button onclick = "getLANStatus()" class="btn btn-primary">Test</button>
<script>
function getLANStatus() {
var status = document.getElementById('status');
{{ if IsLANConnectionUp }}
status.innerHTML = "Lan is up!"
{{ else }}
status.innerHTML = "Lan is down!"
{{ end }}
}
</script>
But having the template code inside the javascript code doesn't seem to work. Also, I'd like the text output from the ping command (which my Go function getLANStatus and I don't know how to extract that data from the function call. The documentation says only one value can be returned.
Searching on StackOverflow I see this: calling Golang functions from within javascript code
$.ajax({
url: "http://www.example.com/signup",
data: {username: "whatever"} //If the request needs any data
}).done(function (data) {
// Do whatever with returned data
});
But it says things like "// Do whatever with the returned data" I'm new to web programming and so don't know how to use that code. If this is the way to go, could someone please expand on this a little?
Any help would be much appreciated.
So couple different concepts here.
Render: On the initial request to your html that generates the Test button. Your go server will render that html 1 time and return it to your browser. It does not re-request dynamically unless you wire some stuff up to make the web page change.
Client: So when someone clicks your button, the function getLANStatus will be ran. You will want that function to do a few things
Through ajax, communicate with your go server through an api that will return the status of your connections as a json object. Something like
{
"3g": "up",
"lan": "down",
"wifi": "up"
}
Second, in the done part of your ajax, you will manipulate something in the DOM in order to convey that the status of the interfaces is what it is. You could do that by finding the element, then changing the text to what is returned by the object.
As a simple first step, you can alert the payload in the function that would look like this
$.ajax({
url: "http://YOUR_GO_SERVER_IP_OR_DNS:PORT/interfaces_status.json"
}).done(function (data) {
alert(data);
console.log(data);
debugger;
});
Then if you request that with the console open in chrome, you will be able to directly play with the returned data so that you know what all it reponds to.
I have a simple table with records and each of them has a btn with data-id attribute to run the confirmation dialog:
#foreach (var dog in Model)
{
<tr>
<td>#dog.Name</td>
<td>#dog.Age</td>
<td>Delete</td>
</tr>
}
After clicking the delete btn, this code is running :
$('.deleteBtn').on('click', function () {
$.ajax({
url: '#Url.Action("DeleteConfirm", "Home")',
data: {
id : $(this).attr('data-id')
},
success: function(data)
{
$('#myModal').empty().html(data).modal('show');
}
});
});
As you can see, its Ajax request to my Action in HomeController. It returns PartialView that is loaded to my Bootstrap dialog:
<div class="modal fade" id="myModal">
</div>
After showing the dialog, the user can click confirm to delete the row via button with class saveBtn. Thats what happens after I click it :
$('#myModal').on('click', '.saveBtn', function () {
var numer = $(this).attr('data-id');
$.ajax({
url: '#Url.Action("DeleteDog", "Home")',
type: 'POST',
dataType: 'JSON',
data: {
id: numer
},
success: function (data)
{
if (data = 'true')
$('a[data-id=' + numer + ']').closest('tr').remove();
}
});
});
So as you can see there is another Ajax (POST this time) request to delete the row.
So here is my question. Is this approach good practice? I'm not sure because in order to delete a row i have to send 2 ajax request (to load confirm dialog, and delete after confirm). Can anyone experience developer comment this code and say whether im doing it good or bad? I would be grateful.
It's always a good idea to challenge whether or not you could do things more effectively (as you have here.) So, let's think about it...
The Question:
Is it a good approach to send to two ajax requests - one to load a partial view and the second to post a delete request from the partial - for a single "user action"?
The Answer:
Maybe.
Why?
Based your example, if your goal is to simply confirm with the user whether or not they want to "Delete Dog ID: foo?" You can absolutely do that without making a trip to the server for a partial view. Presumably, in your first ajax call - $(this).attr('data-id'); - is the dog's Id. You already have it!
In most circumstances, when you make a get request with an identifier, like /dogs/id?='foo' you're using foo to access some additional information about the object from a persistent data store. Like, for example, the dog's owners, similar dog breeds, last visit to the vet, etc.
If additional information about the dog (owners, other dogs, vet) is an important part of deciding whether or not to delete the dog AND there's a good reason not to load it when the page loads intially then it totally makes sense to issue two ajax calls.
It could also make sense to issue two ajax calls just to get the partial view html, even if you don't need additional "dog" data, if you simply don't want the "parent" page to be to big (hence, slowing it's loading time.)
Ultimately, though if you're not retrieving additional data, and there's no specific reason to load additional html, it's probably best in this case to just update the modal dialog using javascript/jquery:
Example fiddle
i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.
It was suggested that I try to explain my problem with no code so here it goes. I have a webpage that lists a bunch of links with project names as seen in this jsfiddle. What I want to do next is display a second webpage after a project link is clicked by a user. The second webpage would need to make a second ajax request like in this Second page jsfiddle to get new information to display a project summary, citations and names for that particular project. The part that's killing me is the ajax request for the second page currently has a number 504216b6e4b04b508bfd333b in the url which means it will only use that project for the second page to display summary, citations and names. I need that ajax request to take a variable for any id number. However to compound the problem the id number comes from a user clicking a link on the first page. So my problem is getting the value of the id once a link is clicked and putting it into the ajax request for the next page. I have all the work done for what the pages will display but I can't get the value from the one file to the next. Any help is appreciated, Thanks.
wouldn't let me save without putting some code so this is just the bare bones,
// The ajax request is in another file but it works good
promise.done(function (json) {
// Make some links
// Which link was clicked? I need to see some id please
$('#sbItems a').on('click', function (e) {
e.preventDefault();
// Do stuff to find the id for the link the user clicked
// Assign the id to a variable that I can use in the next ajax request
// that is called in a seperate file
testId = json.items[itemId].id;
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
second file has,
// Need to somehow, someway get the testId variable that holds the id
// into this file
var url = 'https://www.sciencebase.gov/catalog/item/ + THE TESTID + ?format=
jsonp&fields=relationships,title,body,contacts';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
complete: onComplete,
success: function(json) {
// Display some stuff based off this url
}
});
If you're trying to get a number from the first page and into the second page when you click a link that takes you to the second page so you can use it in the second page ajax call, then there are several options:
Attach the value onto the URL when requesting the second page as a search parameter like this: http://www.sample.com/mypage?id=504216b6e4b04b508bfd333b. The in the second page, parse that id value out of the URL and use it for your ajax call. This is the safest of these three options because it works properly even if the user has multiple windows open clicking on different pages in your site.
When clicking on the link in the first page, store the id value as a cookie. In the second page, retrieve the id from the cookie.
Same as option 2, but store the value in local storage.
Thanks to a javascript function and an ajax request, I have a count indicating the number of points a user makes when he uses my app. He can see that count on the page where he 'plays'.
Now, what I would like to do, is to pass this number into my views.py so that it modifies the object "Score" of my user.
I explain. Thanks to this function, I get the count:
var count = parseInt(0);
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: Escore
});
}, 60000);
function Escore(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
count += parseInt($(this).attr("count"));
$(".PlayerScore").html(count)
}
});
}
displayed in my html:
<div class="PlayerScore"> </div>
Now, I would like to modify the object "score" of my user thanks to that. Every minute, I have a request that gives me the number of points the player makes in my div. How can I take this count in order to modify my "request.user.userprofile.score" in my views.py?
I hope my question is not too confusing. Any help would be really welcome. thanks!
Hm If I understand the question, you need to do the following:
Create your view function, and create a URL pattern in URL.conf that attaches to this view function. Something like /points/save/
This function will likely require the points of the user and the user ID (so you can make changes to the specific user in the database)
You need to make an ajax request that sends the point data and the user ID To the URL that points to your view function. Sent through GET/POST
Your view function will lookup the user from the user id sent from jquery ajax call, then edit the user points with the points sent from the ajax call
Here are a few guides to help
Ajax with Jquery and Django
Django and Jquery