Why my ajax script doesn't work? - ajax

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...
});

Related

Setting up QUnit tests for AJAX calls

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>

d3.xhr example or AJAX d3's way

I've been looking for an example of updating data with d3.xhr but have not seen anything obvious, or at least of my level of understanding. The following 2 links are close but no cigar:
from stackoverflow
from mbostock’s block
I look around more and found this example in jquery and php. I tried it and understand the code. I would appreciate if you give me an equivalent code in d3.xhr or d3.json. BTW, what is different between d3.xhr and d3.json, and when to use what? Thanks in advance.
<?php
// AJAX & PHP example
// http://iviewsource.com/codingtutorials/learning-how-to-use-jquery-ajax-with-php-video-tutorial/
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
$(document).ready(function() {
$('#searchip').change(function(){
$.ajax({
type: "GET",
url: "ajax.php",
data: 'ip=' + $('#searchip').val(),
success: function(msg){
$('#resultip').html(msg);
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
</body>
</html>
I found the solution. In fact it has less coding, :) I sincerely hope that the answer would be useful to someone.
<?php
// AJAX & PHP example
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
d3.select('#searchip').on("change", function() {
d3.xhr('xhr.php?ip='+this.value, function(data) {
d3.select('#resultip').html(data.response);
})
});
</script>
</body>
</html>

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

cross domain ajax request fails in android device

i have a very basic jqm/phonegap app
here is my html
<html>
<head>
<title>jQuery Mobile Web App</title>
<link href="jquery-mobile/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id="home" >
<div data-role="header">
<h1>p</h1>
</div>
<div data-role="content" style="text-align:right" id="c1">
</div>
</div>
</div>
</div>
here is my js code which is placed in the body of html code
<script>
function get_news_list(id , link_ , refresh_ ){
jQuery.support.cors = true;
$.ajax({
url : link_ ,
success:function(data){
$('#c1').html(data);
} ,
error : function(data) {
alert(data.toSource);
}
});
}
get_news_list('latest' , 'http://pnup.ir/?feed=json' , refresh_);
</script>
when i run it as a webpage i get
this alert
if firefox
function toSource() {
[native code]
}
in chrome
undefined
which i assume is ok cuz it's a cross domain ajax request and it fails in a web browser (altho in firebug it's status is ok 200 it just doesn't return anything as response )
but when i test it on my android device i get the same undefined . i thought cross domain ajax request isn't problem once i rune it as app in android device ?
am i missing something ? should i use jsonp ? its a wordpress website and with json feed plugin its feeds are available in json but getting jsonp feed would be a nightmare ... at least i dont know how !
i implemented jsonp recently in one of my phonegap + jquerymobile project, i had the same issue but i used asp.net for my services
calling the service like below worked for me all you have to do is add ?fnCallBack=? at the end of the url
$.ajax({
url : link_+'?fnCallBack=?',
contentType : "application/json; charset=utf-8",
dataType : "json",
jsonp : 'json',
cache : false,
success : function(result) {
if (result != 'Error') {
var valX = JSON.stringify(result);
valX = JSON.parse(valX);
} else {
navigator.notification.alert("An error occured, Please try later");
}
}
});
and on the server side when you send json response just add fnCallBack like this
string jsoncallback = context.Request["fnCallBack"];
context.Response.Write(string.Format("{0}({1})", jsoncallback,jsonData));
this way i solved my cross domain issue so hoping you ll get a clue from this

How do I make SignalR work inside _Layout.cshtml?

I'm working on an MVC3 project right now and just started using SignalR.
I have followed several demos but I can't seem to get it working when my codes are inside \Views\Shared_Layout.cshtml. I always get the "Connection must be started before data can be sent." error.
Please see my codes below:
My Class:
[HubName("notificationsHub")]
public class NotificationsHub : Hub
{
public void updateServer()
{
Clients.updateClient("boom");
}
}
My script inside _Layout.cshtml:
$(function(){
var signalR = $.connection.notificationsHub;
signalR.updateClient = function (message) {
alert(message);
};
$("#open").click(function () {
signalR.updateServer();
});
$.connection.hub.start(function () {
alert("Connected");
});
});
Script references:
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.6.4.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.signalR.js")"></script>
<script type="text/javascript" src="#Url.Content("~/signalr/hubs")"></script>
My NotificationsHub Class is inside a folder named NotificationsHub which is of the same directory level as my Views.
I tried this on a .html file and it works perfectly (I get the alert callback for $.connection.hub.start).
What am I missing here?
Thanks
That's weird, I cannot reproduce the problem. Here's my Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.6.4.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.signalR.js")"></script>
<script type="text/javascript" src="#Url.Content("~/signalr/hubs")"></script>
<script type="text/javascript">
$(function () {
var signalR = $.connection.notificationsHub;
signalR.updateClient = function (message) {
alert(message);
};
$("#open").click(function () {
signalR.updateServer();
});
$.connection.hub.start(function () {
alert("Connected");
});
});
</script>
</head>
<body>
#RenderBody()
Open
</body>
</html>
Works perfectly fine. Make sure you don't have script reference errors.

Resources