I have the following code configured to reference an offsite XML file and autocomplete and return the value. It is not working no matter if I hardcode the data element like you see below or if I comment the data: element out. I've tried to change the Type: from Post to Get in both scenarios as well. I've also confirmed that the .xml is in the URL path specified as well as try to simply place it in the same directory as the .php file you see below. No errors are generated on the webserver either.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.3.js'></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/start/jquery-ui.css">
<style type='text/css'>
.red {color: red}
</style>
<script type='text/javascript'>
$(window).load(function(){
$.ajax({
url: "domain/file.xml",
type: "POST",
dataType: "xml",
data: {
xml: "<geonames><geoname><name>London</name><geonameId>2643743</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname><geoname><name>London</name><geonameId>6058560</geonameId><countryCode>CA</countryCode><countryName>Canada</countryName></geoname><geoname><name>The Tower of London</name><geonameId>6286786</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname></geonames>"
}, //should not need to define 'data' on your own xml call
success: function(xmlResponse) {
var data = $("geoname", xmlResponse).map(function() {
return {
value: $("name", this).text() + ", " + ($.trim($("countryName", this).text()) || "(unknown country)"),
id: $("geonameId", this).text()
};
}).get();
$("#test").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function(item) {
return matcher.test(item.value);
}));
},
minLength: 2,
select: function(event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.value + ", geonameId: " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
}
});
});//]]>
</script>
</head>
<body>
<p class="ui-widget">Try typing 'Lo' it will match on 'London'.</p>
<div class="ui-widget">
<label for="test">London matches: </label>
<input id="test" />
</div>
<p id="result" class="ui-widget red"></p>
</body>
</html>
If you can open the remote URL directly in the browser or a browser addon, but not using Ajax, the same-origin policy and missing CORS headers are the most likely reason.
The remote resource has to provide CORS headers. Otherwise the browser will not open it in the XHR object (jQuery.ajax() uses XHR internally).
Open the network tab of the developer tools in your browser an check the request/response headers.
Related
I have this in my <head>
<link rel="stylesheet" href="css/jquery-ui.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/date.js"></script>
all of it is vital to run the date time picker which is this.
<span><input id="datepicker" style="width:64px;outline:none;border:transparent;" type="text" > </span>
Yeah sure thing, it works. but whenever i am calling the whole .php of it and it display to the page. it doesnt work. here is my ajax code.
<script type="text/javascript">
function get_bookextt(user_id) {
var request = $.ajax({
url: "getbookext.php",
type: "POST",
data: {'user_id': user_id},
dataType: "html"
});
request.done(function(msg) {
$("#get_bookext").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
So i will recap my question in case i didnt explain it very well. that getbookext.php is working just fine, but whenever i am calling it from another page, the date time picker doesnt work anymore.
EDITED:
The page i am calling it from also have the seam <head> could it be the problem?
I am struggling with getting this code to work. My intention is to be able to save the contents of a div to an html file, so that I can recall it later...
It works partially, in that if I change $data=$_POST['id'] to $data=$_POST['memory'] in readInput.php it will indeed save any text I enter into the input named 'memory' to an html file, and will correctly save the file with whatever name I give it. Where it fails is if I try to grab the data of DIV 'readDiv' and its contents $data=$_POST['id']; it will save a blank html page, with whatever name I gave it... Here is the code:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>readInput</title>
<meta name="description" content="HTML5 web page">
<meta name="keywords" content="HTML5">
<meta name="author" content="You">
<meta charset="UTF-8">
<link href="jquery-ui.htm" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-latest.htm"></script>
<script name="saveMemory" type="text/javascript">
$(document).ready(function() {
$('#saveMemory').click(function() {
//e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content}
//dataType: "html" // test
});
});
});
</script>
</head>
<body onload="document.readWrite.writeInput.focus();"><!--form name.input name.focus!-->
<div id="formContainer" style="display:block">
<form name="readWrite" action="readInput.php" method="POST">
<input name="memory" placeholder="...enter text here..." type="text">
<input name="readMemory" id="readMemory" class="readMemory" placeholder="...read..." type="text">
<input id="writeInput" name="writeInput" class="writeInput" placeholder="...write..." type="text">
<input class="saveMemory" id="saveMemory" name="saveMemory" value="...saveMemory..." type="submit">
</form></div>
<div name="readDiv" id="readDiv" class="readDiv">
<div id="writeDiv" class="writeDiv" title="writeDiv">test text
<div id="topDropbox" class="topDropbox" title="topDropbox">
<img src="car.jpg">
</div></div></div>
</body></html>
readInput.php:
<?php
$writeInput = $_POST['writeInput'];
$data = $_POST['id'];
$fileName = ("memories/$writeInput.html");
$fileHandle = fopen($fileName, 'w+') or die("Cannot open file");
fwrite($fileHandle, $data);
fclose($fileHandle);
echo($fileName);
echo($data);
?>
It probably looks like a horrible hack job to you pros because I have tried so many bits of code, and I am sure I am just missing something silly, but I am at a loss...thank you anyone for any help!
This update should do the trick:
$(document).ready(function() {
$('#saveMemory').click(function(e) {
e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content, writeInput : $('#writeInput').val()}
//dataType: "html" // test
}).done(
function( data ){
$('#result).html( data);
}
);
});
});
Changes:
Added e to the click function. It provides the function with a reference to the event object.
Uncommented e.preventDefault() so the form won't execute breaking the ajax call.
Added writeInput to the post data.
Added a callback (.done). When the request is finished this function will execute writing the responseData into writeDiv
Add the following div directly in the body tag.
<div id="result" style="background-color: #f4f4f4;width:100%;height:300px;overflow: auto"></div>
I am having a problem is retrieving data sent to a php file through .ajax() via jquery
Following is my html:
<!-- Jquery tute no 94 onwards -->
<html lang="en">
<head>
<meta charse="utf-8">
<title> jquery4 </title>
<link rel="stylesheet" type="text/css" href="jquery4.css"/>
</head>
<body>
<input id="lo" type="text"> </input>
<input id="ton" type="button" value="Load"> </input>
<div id="content"> </div>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="jquery4.js"> </script>
</body>
</html>
My jquery4.js is:
$(document).ready(function()
{
$('#ton').click(function()
{
var nm= $('#lo').val();
$.ajax({url: 'page.php', data1: 'name='+nm, success: function(data2)
{
$('#content').html(data2);
}
});
});
});
My page.php is:
<?php
if(isset($_GET['data1']))
{
echo $namer= $_GET['data1'];
}
?>
All the above files are in the same folder, and I have xampp installed.
I guess the error is somewhere in the jquery file where I call the
ajax() function
jQuery ajax doesn't take a data1 parameter. It takes a data parameter, which should be an object of name-value pairs.
$.ajax({
url: 'page.php',
data: {
data1: 'name=' + nm,
},
success: function(data2) {
$('#content').html(data2);
}
});
$.ajax({
type: "GET",
url: "page.php",
data: {
data1: 'name=' + nm,
}
,
success: function(data2) {
$('#content').html(data2);
}
});
Try this:
$(document).ready(function() {
$('#ton').click(function() {
var nm= $('#lo').val();
$.ajax({
url: 'page.php?name=' +nm,
success: function(data2) {
$('#content').html(data2);
}
});
});
});
You don't have to tell jQuery to use GET, as it defaults to that, if nothing else is specified.
So the ajax function does not take an argument called data1, but 'data', this is mostly used for other methods as POST, PUT and DELETE.
I prefer also sending GET requests with a normal query string, like the above example.
You can then check for get GET parameter with PHP, using $_GET['name']
POST PHP to itself using AJAX does not return the expected value?
Parameters has been successfully send to POST, based on Firebugs Console
but it does not dispaly the result to the same page.
How to fix this?
labor.php
<?php
if(isset($_POST['from']) && isset($_POST['from']))
{
echo 'from: '.$_POST['from'].
' to: '.$_POST['to'];
//do something here
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Labor Reports</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker_from" ).datepicker();
$( "#datepicker_to" ).datepicker();
$( "button" )
.button()
.click(function() {
$.ajax({
url: 'labor.php',
type: 'POST',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
success: function(){
}
});
});
});
You aren't doing anything with the returned data.
success: function(data){
alert(data);
}
data represents the response sent back from the server. In your case, it will be the echoed output of your from and to $_POST values. Coincidentally, you will also get the rest of the page sent back to you as well, you'll probably want to return false; after the echoes, so that it stops the printing of the page.
Just to give some context I'm a self taught programmer with no formal education or experience so apologise for my code in advance...
Code below attempts to turn a site designed for an iphone into a single page site (i.e. using ajax). I'm having an issue with multiple form submissions... looks like this is occurring when clicking the submit button on form #id2.
I've done some research and was thinking of implementing the below jquery solution for preventing multiple form submissions:
How to prevent form from submitting multiple times from client side?
and this php solution for preventing multiple form submissionson the server side:
http://www.ideologics.co.uk/programming/how-to-prevent-multiple-form-submissions-in-php
Also some sites suggest that the ajax post code should set async to false and cache to false but I'm not entirely sure of the reason and whether this is applicable in my case.
The reason I had to use the delegate function is because clicking submit on form #id1 loads a form with id#2... I tried using the on function which jquery site says supersedes the delegate function but this didn't seem to work. I'm loading version 1.8.2 using google CDN.
var startUrl = 'menu.php';
$(document).ready(function(){
loadPage(startUrl);
});
function loadPage(url) {
$('body').append('<div id="progress">Loading...</div>');
scrollTo(0,0);
if (url == startUrl) {
var element = ' #header ul';
} else {
var element = ' #content';
}
$('#container').load(url + element, function(){
var title = $('h2').html() || 'Menu';
$('h1').html(title);
$('h2').remove();
$('.leftButton').remove();
if (url != startUrl) {
$('#header').append('<div class="leftButton">Menu</div>');
$('#header .leftButton').click(function(e){
$(e.target).addClass('clicked');
loadPage(startUrl);
});
}
$("#container").delegate("a", "click", function(e){
var url = e.target.href;
if (url.match(/example.com/)) {
e.preventDefault();
loadPage(url);
}
});
$("#container").delegate("form", "submit", function(event){
event.preventDefault();
});
$('#id1').submit(function(){
var formData = $(this).serialize();
$.post('processform1.php',formData,processResults);
function processResults(data) {
$('#id1').remove();
$('#container').html(data);
}
});
$("#container").delegate("#id2", "submit", function(event){
var formData = $(this).serialize();
$.post('processform3.php',formData,processResults);
function processResults(data) {
$('#id2').remove();
$('#container').html(data);
}
event.preventDefault();
});
$('#progress').remove();
});
}
Below is the index page:
<html>
<head>
<title>Title</title>
<meta name="viewport" content="user-scalable=no, width=device-width" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon-precomposed" href="myCustomIcon.png" />
<link rel="apple-touch-startup-image" href="myCustomStartupGraphic.png" />
<link rel="stylesheet" href="iphone.css" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="iphone.js"></script>
</head>
<body>
<div id="header">
<h1>Menu</h1>
</div>
<div id="container"></div>
</body>
</html>
Just place this in your JS for the page the submit button is on
<script type="text/javascript">
$(document).ready(function(){
$("input[type='submit']").attr("disabled", false);
$("form").submit(function(){
$("input[type='submit']").attr("disabled", true).val("Please wait...");
return true;
})
})
</script>
You may need to use an on() event handler or do other tinkering depending on if the form is generated on page load.