I have a HTML page which i am running on localhost. I want to access some data from a Python script and use it in my HTML page, The Ajax call in the function doesn't work, If i remove it the program runs perfectly. Any help?
Javascript Function :
<script src="/js/jquery.min.js" type = "text/javascript" ></script>
<link rel="stylesheet" href="LoginStyle.css" type="text/css" />
<script type = "text/javascript" >
function getData()
{
//Code doesn't even enter this function but when i remove the $.ajax part it enters the function
alert("I AM HERE");
$.ajax(
{
type: "GET",
url: "/cgi-bin/check.py" // Path of the script/code i want to run
success: function(response)
{
$("#username").text(data); //this is where i should get the response, Not sure about the syntax i.e. whether i should
//output in a <div> tag or a text box
}
});
}
Calling the Function in HTML like this:
<form name="login-form" class="login-form" action="" method="post" onsubmit="getData();return false;"">
<input id="Uname" name="username" type="text" class="input username" placeholder="Username" />
Python Script:
#!/usr/bin/python
from StringIO import StringIO
import json
def htmlData():
content=json.loads('{"access": {"token": {"issued_at": "2013-04-18T14:40:23.299903", "expires": "2013-04-19T14:40:23Z", "id": "4c5ef01f52c7404fb5324c520d25d1fe"}}}')
data=json.dumps(content, indent=4, separators = (', ', ': '))
print data
return
htmlData()
You have a missing , in the url property
function getData() {
//Code does not even enter this function but when i remove the $.ajax part it enters the function
alert("I AM HERE");
$.ajax({
type: "GET",
//--> here missing , in url
url: "/cgi-bin/check.py", // Path of the script/code i want to run
success: function (response) {
$("#username").text(data); //this is where i should get the response, Not sure about the syntax i.e. whether i should
//output in a <div> tag or a text box
}
});
}
Try using, you have missed to add , end of url string
url: "/cgi-bin/check.py",
instead of
url: "/cgi-bin/check.py"
Related
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);
});
I am trying to call a function that isn't being recognised. I have a PHP block of code that adds the form to the HTML when the user is logged in:
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user'];
echo("<form onsubmit=\"nbpost('#nbpost','$usr'); return false;\">\n");
echo("<textarea id='nbpost' placeholder='Create a post...'></textarea>\n");
echo("<button type='submit'>SUBMIT</button>\n");
echo("</form>\n");
}
?>
I put my JavaScript below that HTML. According to W3Schools, the script has nothing to do with how it's executed. Additionally, I've tried countless times to execute the script when the script was on top, with no result either.
Also, I previously had the code in a separate script, but I've taken it out to see if that's the issue.
Here's the script with an example of the generated HTML:
<form onsubmit="nbpost('#nbpost','$usr'); return false;">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<button type='submit'>SUBMIT</button>
</form>
<script type="text/javascript">
const nbpost = function(element, name) {
alert("WORKING");
name[0] = name[0].toUpperCase();
const msg = $(element).val;
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
};
</script>
Whenever I execute the code, it simply says in the console:
Uncaught TypeError: nbpost is not a function at HTMLFormElement.onsubmit (index.php:54)
What's going wrong?
Change the name of the function nbpost so it does not match the textarea id='nbpost'
CodePen
I would try and separate your content a little better, it can make it less confusing. Give this a try with jQuery enabled.
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user']; ?>
<form id="form" method="post">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<input type="hidden" name="user" value="<?=$usr;?>">
<button type='submit'>SUBMIT</button>
</form>
<?php
}
?>
This needs to go at the bottom of your document. You can also put the JavaScript in a separate file and call it by filename of course.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#form").on("submit", function (e) {
e.preventDefault();
var name = $("input[name=user]").val().toUpperCase();
var msg = $("#nbpost").val();
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
});
</script>
see if this works for you.
You should declare your submit event as an entire function
onsubmit=\"function(){nbpost('#nbpost','$usr'); return false;}\"
So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
In the code below I make a POST request to a servlet that replies in this way:
response.setContentType("application/json");
json = "{success:true,sessionUid:\""+sessionUid+"\"}";
response.getWriter().write(json);
So Firefox opens it like a file and I can see it's ok. Here you have the JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
The problem is that I can't inspect the JSON object. It seems not to exist inside my callback function (also using Firebug). Take a look to the code and alerts.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#loginForm").submit(function(response){
alert("response="+response); //output: "response=[object Object]"
var obj = jQuery.parseJSON(response);
alert("obj.sessionUid="+obj.sessionUid); //doesn't work, Firebug says "obj is null"
if (response.success == true){ //never true
document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp';
}else{
alert("Something went wrong in the login process.");
}
return false;
});
});
</script>
</head>
<body>
<form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post">
<fieldset><legend>Login to Quotero:</legend>
<label>Action:</label><input type="text" name="action" value="login"/><br />
<label>Username:</label><input type="text" name="login-quotero" value="admin"/><br />
<label>Password:</label><input type="text" name="password-quotero" value="admin" /><br />
<label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
EDIT: I also tried to do the same with an AJAX request, wothout success:
$("#ajaxSubmit").click(function () {
$.ajax({
type: "GET", //GET or POST is the same for this servlet
url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero",
dataType: "json",
success: function (response) {
alert("response=" + response);
var obj = jQuery.parseJSON("" + response);
alert("obj.sessionUid=" + obj.sessionUid);
if (response.success == true) {
document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp';
} else {
alert("Something went wrong in the login process.");
}
}
});
return false;
});
This is not valid JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
This is valid JSON:
{"success":true,"sessionUid":"D07WC15R7LFRFRGPF4P5"}
In JSON the keys must always be quoted. See DEMO.
I think you have mixed up ajax with submit. submit is just simply an event, when form is submitted do the following. then you can
$("#loginForm").submit(function(){
var post_data = $(this).serialize();
$.ajax({
url: '',//url of the php file that handles the forms
type: 'GET',
dataType:'json',
data:post_data,//this are the query strings, e.g. ?q=blabla&s=blabla
success:function (data){//if page was 200 or successfully loaded
alert(data.sessionUid);
// do what ever you wish with the data here
},
error: function (){
alert('Page failed to load');
}
})
return false;
});