Setting up QUnit tests for AJAX calls - ajax

I am attempting to use Q-Unit Testing for my code. I would like to run some tests against my AJAX queries to ensure they are running ok and returning what they should.
Is there anyway I could get guidance on the two ajax calls below.
The first AJAX savePgID() essentially takes in 2 numbers and then goes to the pagaAJAX.php page where a simple MySQL INSERT query runs to insert those 2 numbers into the DB.
The second AJAX getModuleData() call again goes to a PHP script where a SELECT query runs, which GETS data from the database and the AJAX just pushes the content to certain divs.
My 2 AJAX calls inside of
script.js:
function savePgID(moduleID, pageID){
$.ajax({
url: "pageAJAX.php",
method: "POST",
data: {moduleID:moduleID, pageID:pageID},
dataType: 'json', //ajax to expect JSON data type
});
}
function getModuleData(moduleID, pageID){
console.log
console.log(moduleID);
console.log(pageID);
$.ajax({
url: "moduleAJAX.php",
method: "POST",
data: { moduleID:moduleID, pageID:pageID },
dataType: 'json', //ajax to expect JSON data type
success: function(data){
//console.log(data);
$('#result').html(data.result);
$('#modContent').html(data.modContent);
$('#modTitle').html(data.modTitle);
$('#modID').html(data.modID);
$('#pgID').html(data.pgID);
$('#modProgress').html("Page " + data.pgID); // For footer of modal overlay
}
});
}
my test.html page:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Q-Unit Tests</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.0.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.10.0.js" integrity="sha256-X1fQXHSYGxa4V2bqkEAQW0DQGSxJrKveasahr959o28=" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>

Related

How do I return data from my backend script and avoid this Ngrok error page?

I am trying to access a javascript file which is part of my Shopify app and log the data returned from my backend php script but I get an Ngrok error page. I have added the proxy url to the app proxy settings on Shopify and I am accessing it like this:
$.ajax({
type: 'GET',
async: true,
datatype: JSON,
url: '/tools/app-script',
data: {
// search: search,
shop: window.location.href,
url: window.location.href
},
beforeSend: function() {
// function while sending...
},
success: function(result) {
console.log('SUCCESS');
// const data = JSON.parse(result);
console.log(result);
},
error: function(error) {
// Create function for errors in the page request.
console.log('ERROR');
console.log(error);
}
});
In the console I see result is being logged as the request is successful however, I'm not getting the data I expect. Instead I receive the Ngrok message below:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="author" content="ngrok">
<meta name="description" content="ngrok is the fastest way to put anything on the internet with a single command.">
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link id="style" rel="stylesheet" href="https://cdn.ngrok.com/static/css/error.css">
<noscript>You are about to visit a123-12-12-123-12.eu.ngrok.io, served by xxx.xxx.xxx.xxx. This website is served for free through ngrok.com. You should only visit this website if you trust whoever sent the link to you. (ERR_NGROK_6024)</noscript>
<script id="script" src="https://cdn.ngrok.com/static/js/error.js" type="text/javascript"></script>
</head>
<body id="ngrok">
<div id="root" data-payload=""></div>
</body>
</html>
Add the skip-browser-warning-header
$.ajax({
type: 'GET',
async: true,
datatype: JSON,
headers: {
'ngrok-skip-browser-warning': 'true'
}
url: '/tools/app-script',

Django 403 Forbidden Error

When I try the ajax in same page to html it works. Like this;
<html>
<head>
...
</head>
<body>
....
<script>
$.ajax({
url: /test/,
method: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: { name: a, surname: b},
dataType: 'json',
success: function (data) {
getList(data);
}
});
</script>
</body>
</html>
When I try the call same javascript as external. It doesn't work. Why?
<html>
<head>
...
</head>
<body>
....
<script src="{% static 'js/test.js' %}"></script>
</body>
</html>
Define the {{ csrf_token }} as a global variable in your HTML page in script tag as a global variable as such:-
var generated_csrf_token = "{{ csrf_token }}";
And then in your .js file call it,
headers: {'X-CSRFToken': generated_csrf_token},
But make sure you put AJAX call within the document ready func in $(document).ready(function () {***here***}
This way you can access it with name generated_csrf_token in any js file.
Hope this helps :-)

Why my ajax script doesn't work?

Take a look at:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Récupération d'un contenu HTML en Jquery Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function recupTexte() {
$.ajax({
url: "data.xml"
})
.done(function( texte ) {
$('body').append( " : " + texte );
});
}
setInterval(recupTexte, 1000);
</script>
</body>
</html>
data.xml
test
When I go to my web browser Safari, I have "test" displayed, but when I edit my data.xml file manually to "changed", Safari continues to display "test" and no "changed". Why ? I don't understand...
So, just to say it, this code only works in safari, and in local. When I put it in a server, nothing is displayed....
This might be an issue due to caching of get request. Try disabling the cache using :
$.ajaxSetup({ cache: false });
or inside your ajax call
$.ajax({
cache: false,
//other options...
});

CodeIgniter Check if image existing with Jquery Ajax

I would like check the image whether existing on server file system and the file list was store into database. I want to make a ajax call to doing validation then return the result to screen with append effect. Here is my code, but don't work :( Please help me.
UPDATE: Code is workable, but it's not my expectation, because three thousand record with caused timeout and No append effect. thanks
Controller
public function getImageList()
{
$this->load->model('image_model');
$data['list'] = $this->image_model->get_image();
foreach ($data['list'] as $key){
$result[] = $this->imageValidation($key->filename);
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($result));
}
private function imageValidation($imgfile)
{
if(!file_exists(LOCAL_IMG_TEMP.$imgfile))
{
return "<pre>". $imgfile." Not Find"."</pre>";
}
}
View
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title></title>
</head>
<body>
<script>
function makeAjaxCall(){
$.ajax({
type: "POST",
url: "http://127.0.0.1:8888/index.php/ajax/getImageList",
cache: false,
dataType : "json",
success: function(data){
$("p").append(data);
}
});
}
</script>
</script>
<input type='button' id='PostBtn' value='Check Image' onclick='javascript:makeAjaxCall();' />
<p></p>
</body>
</html>
try to use file_exists()
check it

Ajax button click that triggers a php file / link

I want a simple button that when I click, it shows the content from a file file.php ( this file when triggered it shows a random number) and if it's clicked several times refreshes the content from file.php.
You can try something like this:
PHP File: file.php
<?php
//your php code for random number...
?>
HTML File:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input type="button" id="clkMe" value="Load File" />
<div id="response"></div>
<script>
$(document).ready(function(){
$("#clkMe").click(function(){
var dataString={};
$.ajax({
url:"file.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000,
error: function() { },
success: function(response) {
$("#response").html(response);
alert(response);
}
});
});
});
</script>
</body>
</html>
I hope this is what you are asking.
Happy Coding!!!

Resources