Ajax function not called when included - html

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';

Related

Setting value of variable in HTML element with JQUERY not working

I have a div in my HTML like this in which I'd like to set the ID of capital using JQuery
` <div class="modal-body">
<p id="capital"></p>
</div> `
This is how I'm setting it in my JQuery function
`function getWeather() {
$.ajax({
url: "assets/geojson/countryBorders.geo.json",
type: "GET",
dataType: "json",
data: {
},
success: function(result) {
let features = result["features"];
let countryFeature = findFeatureFromName(countryName);
let countryCode = JSON.stringify(countryFeature.properties.iso_a2).replace(/"/g,"")
$.ajax({
url: "assets/php/countryInformation.php",
type: 'POST',
dataType: 'json',
data: {
country: countryCode
},
success: function(result) {
console.log(result);
console.log(JSON.stringify(result));
let capitalCity = (result['data'][0]['capital']);
console.log(capitalCity)
$('#capital').html(capitalCity);`
etc
But capital isn't getting set?
The console.log is returning the expected value, so I know that has set okay.
I've even tried
$('#capital').text(capitalCity);
and plain JavaScript out of curiousity
document.getElementById("capital").innerHTML = capitalCity;
Nothing seems to be working and no errors in the console - what would be wrong?
Your HTML and JSON code is correct Code it correct, may be you are missing something in your jSON file
Here is what I tried and got the Output, if possible please post
ountryBorders.geo.json, so that we get more clarity
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body onload="getWeather()">
<div class="modal-body">
<p id="capital"></p>
</div>
<script>
function getWeather() {
debugger;
let capitalCity = 'hello';
console.log(capitalCity)
$('#capital').html(capitalCity);
}
</script>
</body>
</html>

How to call my ajax function/fetch with a btn

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.

Custom Google place search returns error with $.ajax()

I am working on Google Places from https://developers.google.com/places/documentation/search
After adding api key this url
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=
gives me pretty fine json response in browser.But whenever i want to parse these response with JQuery.Ajax() it gives me error.
I cant find the reason behind this error.How can i solve these problem?Thanks.
JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(event){
var url="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=<myKey>";
$.ajax({
url: url,
type:'POST',
dataType: 'json',
success: function(data)
{
alert("success");
},
error:function(){
alert("error");
}
});
});
});
</script>
Html:
<button id="submit">press</button>
The linked ressource is not accessible via AJAX, because the access is restricted by same-origin-policy and JSONP is not supported.
Use the nearbySearch of the javascript-places-library to get the result on clientside.
dataType: 'jsonp',
This workd for me!!

Using HTTP GET with JQuery

I'm trying to use a GET HTTP cal, I got the request to work with the Advanced REST client (Chrome plugin) but cannot get it to work in JQuery.
Following the advice from this thread, I've set up the following:
$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
This is the output I'm trying to get (successfully with REST client)
{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}
I just want to be able to access the name variable from that JSON and pass it through my function. I wanted to at least get the above code to work before I try to figure out how to create an object so I can successfully call the name, something like .append(object.name)
I just started learning JQuery and this is my first post so sorry if I didn't include enough details.
You can't apply ajax calls to other domains. You can make workaround using server-to-server calls via curl() or file_get_content(url), and then make a js call to your script.
First make php file, which will call the server note that if you want to use file_get_contents you should allow_url_fopen in your php.ini:
myProxy.php
<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>
your js should make call to your PHP, so you have workaround Same Domain Policy:
$.ajax({
url: 'myProxy.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
I am not sure if your api info is correct, but I think the main thing you need to do is change to jsonp instead of json due to the same origin policy that musa mentions.
The following JS fiddle "works" but the request is not authorized at the server: http://jsfiddle.net/cf8S9/.
$(document).ready(function() {
$('#button').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'jsonp',
success: function() { alert('hello!'); },
error: function() { console.log(arguments);alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });

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>