I m trying to send json data via ajax.but I m getting
ReferenceError: $ is not defined
Here is my code
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btnSubmit").click(function () {
var email = $("#email").val();
var password = $("#pwd").val();
authenticate(email, password);
});
});
function authenticate(email, password) {
$.ajax
({
type: "POST",
url: "authenticate.php",
dataType: 'json',
async: false,
data: '{"email": "' + email + '", "password" : "' + password + '"}',
success: function () {
}
})
}
You must include jQuery on the site. Try adding the following script to access jQuery from a CDN at the begining of the page's head section:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Add this inside your head tag
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
The error may cause because of jquery conflict,If you already included jquery
Try jQuery.noConflict()
$ in there is about jQuery which is a javascript library that simplifies javascript usage. In order to use jQuery, you must include it into your page e.g.:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
But the place is important, it must be before other <script> tags which contains jQuery functions(starting with $ or jQuery).
Related
I have a web site that periodically get a message. I put this message in a variable in javascript code (in php file). Then i want to take it in an another php page but doesn't work.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<!-- Script to import MQTT -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript">
</script>
<script>
....
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.destinationName);
console.log("message.payloadString:" + message.payloadString);
if (message.destinationName == "measure") {
var msg = message.payloadString;
if (msg.includes("temperature")) {
//Splitting up the message for the MAC address value
var MacVal = msg.substring(15,32);
var mac = String(MacVal);
$.ajax({
type: 'POST',
url: 'storeData.php', //url to php file
data: {mac: mac},
success: function(data)
});
}
}
</script>
In storeData.php page i have
$temp = $_POST['mac'];
But this varible is always empty.
Thanks
I'm trying to call an API using a submit button but i'm getting the following errors when i inspect the page on Chrome:
Uncaught ReferenceError: CallApi is not defined
My code is as follows:
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+ $('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)"
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
And my button has the following HTML:
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
Could anyone advise what i'm doing wrong? I have looked at related questions/answers but can't seem to get it working.
Thanks!
the function is not defined, so most likely the javascript file is not included correctly.to prevent mistakes like this:
include files using src instead of href
<script src="myscripts.js"></script>
include files in the correct order (first jquery, then your script)
understand what the term hoisting means in js
check developer tools in chrome (network) to check if files are loaded correctly or check window.CallApi, since it should be defined globally
if you define scripts direclty in html, still wrap them with script tags <script>function CallApi(event) {console.log(event);};</script>
You are both trying to import JQuery and write a custom JS code in the same script tag.
You must include JQuery in a tag.
Then in another tag declare your custom JS code.
Do it this way (i'm just doing an alert for demonstration purpose) :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function CallApi(event) {
alert('test')
}
</script>
</head>
<body>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" />
</body>
</html>
The following HTML file works for me, in so far as it can call your API url, and get a 404, then alert in the error callback:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
</script>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)"
class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
<input type="text" id="ctl00_ctl05_fvlc_Form1_txtEngagementID" value="foo" />
</html>
It doesn't work because on moment the DOM is created by the browser, the CallApi function doesn't exist yet. This occurs because of the order that element and the scripts is loaded. I believe if you insert the script in <head> section, the function should work.
I recommend change to something like this:
$ (document) .ready (function () {
$ ('#id-of-my-button-element').on('click', CallApi);
});
try setting my code for send variable from view to controller,but my code is not run and show error
Uncaught ReferenceError: $ is not defined
view
<script type="text/javascript">
$(document).ready(function() {
var st = $('#st').val();
var postdata = { st: st };
$.ajax({
type: 'POST',
url: '<?= base_url();?>task_tickets/tes',
data: postdata,
success: function(response) {
console.log(response);
}
});
});
</script>
controller
function cek(){
echo $st;
}
Looks like either you have not included jQuery plugin or added after your JavaScript code. $ is alias to jQuery.
In your view before script tag, include this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.
I have a script like this.
The jQuery ajax loads all my files with no issues.
The ajax_load_books.php file have lot of css and js(inline edit, sliders etc.) files in it.
The problem is:
How to load all the files before the success function so that the user can see the loader_div message untill all the files are loaded.
In other words - Load all the js/css files and proceed with the success function.
Even I have checked with .load() function. Could someone redefine the below code .
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
$("#loader_div").show();
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Thanks,
Kimz
For the css files, you can find them using jQuery.parseHTML() function, but the <script> will be stripped with this so instead we would have to use regex for the <script> tags.
Try:
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$("#loader_div").show();
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
//parsing <link>
var $str = $('<output>');
//loading html into fake tag
$str.load("ajax_load_books.php");
//now $str includes all your page code
temp = $.parseHTML(str);
$.each(temp, function (i, el) {
//finding the <link> tag
if (el.nodeName == 'LINK') {
//appending it to the <head> tag
$('head').append("<link rel='stylesheet' href='" + el.getAttribute('href') + "'>");
}
});
//for script we will use regex
var pattern = /<script[^>]+?>.*?<\/script>/gi;
var matches = str.match(pattern);
var scripts = "";
for (var i in matches) {
scripts += matches[i];
}
//appending script tag to <head>
$('head').append(scripts);
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Demo
There is a drawback with this, your stylesheets and script code will repeat. If the above code causes issue running because of the repetition, you should place the code of beforeSend() before the AJAX and have a parameter sent from your AJAX function indicating that when an AJAX is called with this parameter, to execute all the HTML except the stylesheets and js scripts.