$.ajax passing multiple parameters - javascript

For some reason passing parameters using ajax is a real problem for me. I checked all of the questions regarding parameters and found the following as the correct way to pass parameters:
var username = $("#email_0000").val(),
password = $("#password_0000").val(),
func = 'emailexists',
bValid = true;
$.ajax({
type: "GET",
url: "php/ajax.php",
data: {
func:func,
email:username
},
success: function(data) {
alert(data);
}
});
The following is my php code:
<?php
$func = $_REQUEST['func'];
echo var_dump($_GET);
switch($func) {
case 'emailexists':
$email = $_REQUEST['email'];
echo 'Email address is='.$email;
break;
default:
return false;
break;
}
The alert is showing the following:
array(1){
["func"]=>
string(11)"emailexists"
}
Email address is=
I know I'm doing something wrong, but if someone has a clue I would appreciate it. Am I missing something in the "head" tag:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="expires" content="1">
<!--Stylesheets-->
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/dhaStyle.css">
<!--JavaScripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script src="js/vendor/jquery.simplemodal.1.4.4.min.js"></script>
<script src="js/DHA_forms.js"></script>
Thanks in advance for your help, regards, Rich

Related

UTF-8 Arabic in JavaScript

I read this, but it did not solve my issue, and as it is old, I'm posting a new question.
I've the below code, that is recieving a SSE from GoLang server, but the Arabic script is not encoded probely:
<!DOCTYPE html>
<html lang="ar-AR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
</head>
<body>
<div id="msg"></div>
</body>
<script src="socket.js" charset="utf-8" type="text/javascript"></script>
</html>
And
var source = new EventSource("http://localhost:1234/sse/signal");
source.onmessage = function (event) {
var message = event.data
document.querySelector('#msg').innerHTML = message;
}
And sample output I get is:
data: {
"IsFromMe": false,
"IsGroup": false,
"ID": "26DE3A6A0AEA98406D286E9C58C40114",
"PushName": "إدارة قطو٠و حلا",
"Timestamp": "2022-07-05T09:45:46+03:00",
}
The PushName above should be Arabic script!
As mentioned by #slebetman in his comments, the correct answer is to send the data from the server as utf-8 which is done in my case as I'm sending data as streaming, by sending the Content-Type as text/event-stream; charset=utf-8
My code in the GoLang server became:
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")

How to display rest api using AJAX in Django?

I want to be able to use the REST API below and display data on a single HTML page.
This is the API (response) from a database connection function in my Django project.
URL: http://127.0.0.1:8000/api/v1/test/
API output:
{
"message": "Success !",
"server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)"
}
I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>API Calls Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<h3>Test Output</h3>
<br></br>
<table class="table table-sm">
<tr>
<th>Output</th>
</tr>
<tbody id="divBody"></tbody>
</table>
</div>
</body>
<script>
$(document).ready(function () {
BindConnection();
});
function BindConnection(){
$.ajax({
type:"GET",
dataType: "JSON",
url: "http://127.0.0.1:8000/api/v1/test",
success: function(data){
console.log(data);
var str = "";
var totalLength = data.length;
for (let i=0; i < totalLength; i++){
str += "<tr>" +
"<td>" + data[i].server + "</td>"
"</tr>"
}
$("#divBody").append(str)
}
});
}
</script>
Note: The result can be displayed on the console and there is no error.
Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts but I cannot make it.
Could you please help me to answer this problem? Thank you!
i think the following line who causing the problem
var totalLength = data.length;
it seems the dictionary has no attribute length as the api response with dictionary so you need to deal with it as a dictionary not array
if you tried to add line
console.log(totalLength)
it will be undifiend value so no looping happening

Can't call function from body onload (uncaught reference error: resetLoginForm is not defined) javascript

I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log:
uncaught reference error: resetLoginForm is not defined
My code is as follows:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Login Page</title>
<script src="/client/js/popper.min.js"></script>
<script src="/client/js/js.cookie.min.js"></script>
<script src="/client/js/querystring.js"></script>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script type="module" src="js/login.js"></script>
</head>
<body class="blue-grey darken-2" onload="resetLoginForm()">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
This is the JavaScript code that I am trying to use:
import * as Cookies from "/client/js/js.cookie.min.js";
function resetLoginForm() {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
const loginForm = $('#loginForm');
loginForm.submit(event => {
event.preventDefault();
$.ajax({
url: '/admin/login',
type: 'POST',
data: loginForm.serialize(),
success: response => {
if (response.startsWith('Error:')) {
alert(response);
} else {
Cookies.set("sessionToken", response);
window.location.href = Cookies.get("destination");
}
}
});
});
You're using new ECMAScript modules (<script type="module" ...>), which are isolated to their own scope. Your function resetLoginForm() isn't being defined in the global scope (Where you can essentially call it from your onload body function). You need to define it explicitly in your module:
import * as Cookies from "/client/js/js.cookie.min.js";
window.resetLoginForm = {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
...
Ideally though, you should not be using onload at all. Just add an event listener in:
import * as Cookies from "/client/js/js.cookie.min.js";
function resetLoginForm() {
if (Cookies.get("destination") === undefined) {
window.location.href = "/client/index.html";
}
...
}
// Attach an event, and call resetLoginForm when the document is done loading.
document.addEventListener("DOMContentLoaded", resetLoginForm);
Change is <script type="text/javascript" src="js/login.js"></script>
Cnages is please check once resetLoginForm function in onload.

What is wrong with this HTML, JavaScript and JSON code?

I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.
<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
var hr = new XMLHttpRequest();
hr.open("GET", "game.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data)
{
results.innerHTML += data[obj].title;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>
It pulls data from a file called game.json which is stored in the same directory.
{
"level_001":
{
"id":001,
"title":"Level 1",
"difficulty":0,
"comments":"this is how you complete level 1"
},
"level_002":
{
"id":002,
"title":"Level 2",
"difficulty":0,
"comments":"this is how you complete level 2"
}
}
The problem is that the results.innerHTML = ""; line is never reached. Why?
There are no errors in the browser, I've checked this on Firefox and on Safari.
According to jsonlint.com your JSON is invalid because of these properties:
"id":001
...
"id":002
You need to either remove the leading zeros:
"id":1
or make the numbers strings:
"id":"001"
For further details see the format rules spelled out at json.org
Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources