How to call my ajax function/fetch with a btn - html

Im learning how to use API's with ajax in jquery.
I fetched "bored api" in my html page, and I want to update it or run the function again, by pressing a button and without refreshing the page.
I know I would write the function name in my onclick method, but I can't see where the function name should be placed or is.
<p id="activity"></p>
<script>
$(function () {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
})
})
</script>
</form>
<button onclick="()">Click me</button>

Have a look on this example from W3 Schools:
Example
It should look something like this:
<p id="activity"></p>
<script>
function doApiRequest() {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
});
}
</script>
</form>
<button onclick="doApiRequest()">Click me</button>
You do not need to encapsulate the method inside jquery. and this way, we give it a name, that we can call.

Related

ASP.NET jQuery reload element on submit (Ajax POST/GET)

Using ASP.NET I'm trying to reload only a part of my webpage using jQuery instead of using "location.reload();". It's a single page application. As the user submits a form the user credits change and the new value should be updated without a full page reload. The value for credits is retrieved through an Ajax Get Call and should be updated after an Ajax Post Call. I tried using "$("#userCredits").load(?);" within the Ajax Post but can't get it right. Do I need to make a partial view to achieve this? Thanks for helping.
HTML _Layout.cshtml
<ul class="nav masthead-nav">
<li id="userCredits">
//Paragraph retrived from Ajax Get Call: "#reloadUserCredits".
</li>
<li>
<p class="user">#User.Identity.GetUserName()</p>
</li>
</ul>
JS
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
location.reload();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.append('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
As I understand... You already are getting the user credits via Ajax on page load. So you only need to do it again after he bought some more.
Have the Ajax request to /api/user in a named function. Below, I called it get_credits(). Run it on page load AND on success of the Ajax request to /api/buypack.
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
//location.reload();
// Refresh the credits displayed on the page
get_credits();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
function get_credits(){
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.html('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
}
// Run on page load
get_credits();

Ajax is not working in codeigniter 4 when call the controller

I just want to make sure this ajax is working to call my controller. But when i click the button nothing happened. Thank you
My view :
<input type="text" id="phonenumber" name="phonenumber" class="form-control" placeholder="Phone number">
<button type="button" id="sendotp" name="sendotp" class="btn btn-primary btn-block">Sign Up</button>
My AJAX :
$(document).ready(function() {
$('#sendotp').click(function(e) {
e.preventDefault();
var phonenumber = $("input[name='phonenumber']").val();
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
});
});
My Controller :
public function register()
{
if($this->request->getMethod() == 'post'){
$phonenumber = $this->request->getPost('phonenumber');
echo $phonenumber;
}
return view('register/register');
}
My Routes :
$routes->match(['get', 'post'],'/register', 'Home::register');
In your javascript you have you success event empty. So nothing happening is the expected behavior. If you're returning a view in your controller, you must do something with it in your javascript.
marco answer sufficient.
You need also to add
headers: {'X-Requested-With': 'XMLHttpRequest'}
in your ajax call in JQuery
$.ajax({
url: '<?php echo base_url();?>/register',
type:'post',
dataType:'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
phonenumber:phonenumber
},
success: function(data) {
}
});
and in your controller check if its ajax call first before processing anything.
if ($this->request->isAJAX())
{
}
Please refer to isAjax and refer to Ajax JQuery
this is the proper way to handle ajax calls in Codeigniter4 .
I had the same issue I fixed it Like this:
in app/Config/Filter.php make this change:
public $globals = [
'before' => [
'csrf' => ['except' => ['your route or api']]
]
];

How to refresh an html page using ajax in Django?

I know this question has been asked several times, but I cannot find a solution.
I cannot connect the method output in views with html page.
views
def save_form(request):
if request.method == 'POST' and 'save' in request.POST:
lsection = [5]
print("calculate method runs...")
return JsonResponse({'lsection':lsection})
"calculate method runs..." is printed only when I do not use ajax.
html
<form method="post" name="nameForm" id="idForm"
action = "/project/save/" enctype="multipart/form-data">
{% csrf_token %}
...
<input type="submit" name="save" value="Save">
</form>
ajax
var frm = $('#idForm');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('save_form'),
url: frm.attr('/project/save/'),
//data: frm.serialize(), // I tried this as well
data: {},
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
},
});
});
Question:
I do not get lsection list on html, I try alert(data) I get an empty html.
How can I get lsection on html?
You need attribute's values:
type: frm.attr('method'),
url: frm.attr('action'),
Correct code:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
}
});
.attr
While receiving JSON response in ajax success you used data.
to show the lsection.
alert(data.lsection)
update alert like above

jquery function runs only once

I have this function below. Works great and is from http://caroufredsel.dev7studios.com/ (by far the best and easiet I have found if anyone else is after a carousel)
<script type="text/javascript" language="javascript">
$(function() {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
});
</script>
anyway I the carousel loops through a selection of images. Now I have a separate function that reloads the div through an ajax call below. It populates the div with a new set of images based on the users selection of folder.
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg').html(data);
}
});
}
</script>
This too works fine. The problem is when you have clicked a new folder and it reloads refreshes the div the carousel stops completely. Is there anyway based on the success of the ajax call to re fire the jquery function to get the carousel going again?
on the callback function of the AJAX you call, you have to re-apply:
success: function(data) {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
...
}
If you are using a .html() function or similar to re-write the foo element, you are erasing any event associated to it too, so you have to call it again.
Add something like this into your callback:
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
It should work. Respect!
Supposing in your example foo1 == scrolimg, do this:
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg')
.carouFredSel('destroy')
.html(data)
.carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
}
});
}
</script>

Ajax function not called when included

I have an ajax function that is not run when the ajax script is included in my HTML page like so:
<script type='text/javascript' src='ajax.js'></script>
However, if I place the exact same script in the head portion of the HTML page, then it does run.
Why does this occur, and how can I fix it?
<script type="text/javascript">
$(function() {
$(".a").click(function()
{
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
</script>
This might seem trivial but did you remove the <script> tags when using it in an external .js file?
The contents of your ajax.js file should just be:
$(function() {
$(".a").click(function() {
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
I have the impression that when you mentioned "exactly", you left the script tags intact in the ajax.js file.
Also if this still doesn't work. try added an alert("hello"); line at the top of ajax.js before everything to see whether it runs at all.
I made a example which worked fine for me. cant see any problems so im guessing its a mistype or something silly.
here is the sample code i used:
HTML:
//double check these paths
<body>
<a class="a" href="#">clicky</a>
</body>
Javascript:
$(function() {
// i noticed you put .a here instead of a, i am assuming you are referring the class
$(".a").click(function()
{
alert("1");
$.ajax({
type: "POST",
url: "1.php",
data: "html",
cache: false,
success: function(data)
{
//stuff
$("body").html(data);
}
});
return false;
});
});
PHP:
echo 'bar';