I currently have a webpage where an iframe contains data that is stored into an invisible form, and I want to replace that iFrame, with a div, where the content is being changed/updated via AJAX.
If you dont feel like reading all this, you can skip to the end and read my main question.
Now, the complicated part is that the form contains all the important and used data in an invisible form, which needs to be send via POST. But, the page also includes a form that can send data via GET. And: I've setup the forms like this, that the php file recieves the form data as an array.
At the moment it works like this:
The iFrame shows the data, and stores it in an invisible form. When you want the page to refresh automatically, every 30 seconds, you click a button, and you get redirected to another page, which recieves the data from the previous page, using POST.
When you're on the auto-refreshing page, I use Javascript to automatically submit the form containing all the important data, to refresh the page.
Resubmitting the page is nessecary because I use PHP to do some important calculations with the data I'm using. Moving all this functionality to Javascript is not an option.
Just to be clear, here is a very brief description of my case:
Main page: 2 forms, 1 POST setup so variables are in 1 array, 1 GET with 6 variables.
The GET form could be modified to an AJAX function, as it only includes 6 variables
Auto update page: 2 forms, same as before. Though this POST form is auto-submitted via Javascript every 30 seconds (to update the PHP
functions output).
So, my main question is:
Can I, and if so how, recieve an array from a POST form in AJAX, and then send it as an array to a php page?
EDIT:
Here is some of the code for submitting the form:
<script type="text/javascript">
function paginarefresh() {
document.forms["updateform"].submit();
}
var paginatimer = setInterval(paginarefresh, 60000);
</script>
and the form is build up like this:
echo '<form action="data-reis-refresh.php" id="updateform" name="update" method="POST" style="width: 100px;">';
echo '<input type="submit" class="submit replaced" value="Volg deze trein" name="submit-search"/>';
if (round($afgelegdpercentage*100,1)==100) {
echo ' <span style="text-align: center;">Deze trein is al aangekomen</span>';
} else {
echo ' <span style="text-align: center;">Ververs gegevens (automatisch elke minuut)</span>';
}
echo '<input type="hidden" name="provincie" value="'.$provincie.'">
<input type="hidden" name="reisdata[Overstap]" value="'.$reisdata["Overstap"].'">
<input type="hidden" name="reisdata[Van]" value="'.$reisdata["Van"].'">
but then longer (a lot longer, and with changing length);
I'm using this for all my AJAX requests: [though I change it for different uses]
// Algemene functie om een xmlHttp object te maken. Via dit object kunnen we later Ajax calls plaatsen
function GetXmlHttpObjectReisData() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function CallAjaxReisDataFunction(serverScript,arguments)
{
var xmlHttp = new GetXmlHttpObjectReisData(); // Functie welke wordt uitgevoerd als de call naar de server klaar is State 4)
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
handleReisDataResult(xmlHttp.responseText);
}
}
// Ajax call (Request naar de server met eventuele parameters (arguments))
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", arguments.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(arguments);
}
function callReisDataServer(serverScript,van,naar)
{
CallAjaxReisDataFunction(serverScript,"?&reisdata=" + reisdata);
}
function handleReisDataResult(responseText)
{
document.getElementById('reis').innerHTML = responseText;
}
JS code:
var postdata = {"provincie":"123","reisdata":{"Overstap":"234","Van":"345"}};
var post = "";
var url = "data-reis-refresh.php";
var key, subkey;
for (key in postdata) {
if (typeof(postdata[key]) == object) {
for (subkey in postdata[key]) {
if (post != "") post += "&";
post += key + "%5B" + subkey + "%5D=" + postdata[key][subkey];
}
}
else post += key + "=" + postdata[key];
}
req.open("POST", url, true);
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", post.length);
req.setRequestHeader("Connection", "close");
req.send(post);
And to transfer associative array back from PHP to JS:
In PHP script, called from AJAX request:
echo "(".json_encode($hash).")";
In JS code, parsing the result:
var hash = eval(response);
In the end, I ended up using jQuery .post() and .get().
Those are extremely easy to use and a lot faster and more flexible.
Related
I'm trying to create a form that is capable of generating multiple urls, depending on the input by the user. The created url has a json extension. A php file is used to get the contents of that url. This php file has to have the same contents as the inputted url has. This php file is used as input for a javascript/jquery file.
In this file I'm trying to convert the json code to an html table. This is done by an http_request. The table has to be outputted in a div on the html page. However my code doesn't work due to errors I can't find. I've already looked at simular questions at stackoverflow and google, but could find the fix that made my code working.
I'm applying this code to spotify lists. This is the code I already have:
html:
<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
<select id="country" name="country">
<option value="GB">UK</option>
<option value="US">USA</option>
</select>
<select id="interval" name="interval">
<option value="daily">Daglijst</option>
<option value="weekly">Weeklijst</option>
</select>
<select id="chart" name="chart">
<option value="most_streamed">Meest gestreamd</option>
<option value="most_viral">Meest gedeeld</option>
</select>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>
spotify.js:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.open("GET", "spotifylist.php", true);
http_request.send();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.artist_name and jsonObj.track_name.
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=jsonObj.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
}
}
}
$("#spotifyform").submit(function(){
loadJSON();
return false;
});
spotifylist.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$chart = $_POST['chart'];
$country = $_POST['country'];
$interval = $_POST['interval'];
}
$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>
What currently goes wrong is that the php file is loaded when I press the submit button. This file contains the right json information. However this json isn't converted to a html table.
I would really appreciate it, if anybody could help me fix this problem
If you want the spotifylist div to load in the data when you press submit, you have to prevent the page from redirecting.
Make the form action:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>
And if possible, your input values (if you have any within the form tags):
"<?php echo $_POST['value']?>"
If you can, place your HTML code within a PHP file which executes everything from spotifylist.php.
There are a couple of problems in my guess.
You send your Form to the spotifylist.php which grabs an file and sends something back to the html. Probably JSON but where did you handle that data?
Maybe some Javascript which does something with that "string" that your php sends back?
And your loadJSON sends (whenever) a GET Request to the same php but without parameters or something.
So your php run into an error because there obviously no POST variables set, so your variables inside your if condition will never set ergo your data which comes back again?!? with errors
You should first get clear which technique you want to use.
It seems to me as you would take a little of both.
There are multiple ways to get information from an external server:
httprequest - not recommend, because of bad user experience.
file_get_contents - usually easy, but in this case it requires a lot of data handling. Php works server-side and javascript works client-side. It requires a lot more work to let these two work together.
$.ajax - in this case the best solution, because it doesn't require any php and $.ajax is able to directly parse the json data. Because the data is requested from an external site, you have to change the datatype to jsonp and perform a callback function.
It is very easy to transfer the data from the form to javascript:
// Automatically call this function when the page loads.
window.onload = function loadJSON()
{
// The HTML input of the form that is the input of this javascript document
var country2 = document.getElementById("country");
var chart2 = document.getElementById("chart");
var interval2 = document.getElementById("interval");
Build the url with the selected parameters on submit:
// Call the function when the form is submitted
$("#spotifyform").submit(function(e)
{
e.preventDefault(); // to prevent the page from reloading
// Save the choice of the <select> country in a variable named country2
var country = country2.options[country2.selectedIndex].value;
var chart = chart2.options[chart2.selectedIndex].value;
var interval = interval2.options[interval2.selectedIndex].value;
var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
Then get the right data and parse it directly with the json native parser.
// Get the data from the site and save this into the variable 'json'
$.ajax
({
'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
'dataType': 'jsonp', // Cross site request via jsonp
'error': function(xhr, status, error){ alert(error.message); },
'success': jsonParser // call function
}); // $.ajax
}); // $("#spotifyform").submit(function(e)
} // window.onload = function loadJSON()
Then do with the data whatever you want. You don't need to do an httprequest and you don't have to parse the data anymore.
function jsonParser(json)
{
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=json.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
} // function jsonParser(json)
I'm very new to PHP/Ajax/Html so here's my baby problem (I'm making a radio station site),
test.php queries my server for the currently playing song name.
listen.php displays this song name in the 'refreshTitle' div tag.
When my station changes song there is a 30-ish second delay, so what I want to do is get the song title every second and compare / delay the update of the display if the title is different to what is actually being heard, easy peasy right?! Here is listen.php:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if (window.XMLHttpRequest) { // for Firefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var d = new Date();
var t = d.toLocaleTimeString();
var the_data = 'test=' + t;
//append time purely for testing to make sure text updates
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
setInterval(
function () {
ajaxrequest('test.php', 'refreshTitle')
}, 1000); // refresh every 10000 milliseconds
//This time val should vary based on the song title retrieved during the last second
</script>
And somewhere down the rest of the page I have this:
echo "<div id=\"refreshTitle\" style=\"float:left; padding-top:6px;\">\n";
echo "</div>\n";
In test.php (the file with the song name) I have this:
if (isset($_POST['test'])) {
$str = $_POST['test']; // get data
echo $dnas_data['SONGTITLE'] . " Current time " . $str;
}
So basically every second I send the time to test.php, which echos it and that echo I assume is put into 'refreshTitle' with this line:
document.getElementById(tagID).innerHTML = request.responseText;
What I want to do is get the song title into my javascript in listen.php and only run the ajax request after some string comparison / delay logic.
Sorry for the long-winded description but I'm fairly confused and think I've done this whole thing backwards :) Please let me know any thoughts...
First, I would recommend to you to update your jQuery version (1.3 is kinda old, the current version is 2+).
What's more, AJAX requesting is very well abstracted in jQuery : you can use the load() function to simply load an element content.
Source : http://api.jquery.com/load/
I have an html page with this form
<form id="quick-search" autocomplete="off" class="form-wrapper cf" >
<div style="text-align: center;">
<input id="qsearch" name="qsearch" onkeyup="liveSearch()" placeholder="Search here..." required="" type="text">
<button onclick='ajaxFunction()' id="submitButton">Search</button>
</div>`
and this div where I put the results of ajaxFunction
<div id='ajaxDiv'>Your result will display here</div>
when I click the button the ajaxFunction executed. Just opens a php file where I make a sql query as user writes it in qsearch input form. Here is the JavaScript code:
function createRequestObject(){
var request_o;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_o = new XMLHttpRequest();
}
return request_o;
}
var http = createRequestObject()
function ajaxFunction(){
// Create a function that will receive data sent from the server
http .onreadystatechange = function(){
try{
if(http .readyState == 4){
if(http .status==200){
try{
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML= http .responseText;
}catch(err){
// display error message
alert("Error reading the response: " + err.toString());
return false;
}
}
}
else{
alert(http .readyState+" "+http .status);
}
}catch(e){
alert('Caught Expection: '+e.description+' '+http .status);
return false;
}
}
var par = document.getElementById('qsearch').value;
var queryString = "?par=" + par;
http.open("GET", "results3.php" + queryString, true);
http.send(null);
}
The code works well but the problem is that I need to click the button two times(with the same text in input field of course) to make result text stay in div. At first click the same results come out but the page automatic refresh and results(also the text in input form) disappear.At second click the page don't refresh show no problem.With the alert in code I can see the readyState and status. The states,status produced are 1,0->2,200->3,200->1,0. between state 3 and 1 results shown on page(clearly state 4 comes without problem) but why I have state 1 after 4? All this in Firefox 17.0.1
Thanks in advance for any help!
I work on this at least one day and I found the solution 10 min after I post my problem! The answer is here [Stop refreshing with ajax , javascript , php][1] [1]: Stop refreshing with ajax , javascript , php… I only had to add return false here: onclick='ajaxFunction();return false' and now it works perfect! Thanks!
I have the following code generating content on my site:
<div class="content" id="links">
<?php displayTitle("Links"); ?>
<?php displayContent("Links", $isLoggedIn); ?>
</div>
The content has a button that calls a Javascript function 'addLink()' to edit itself. Here is the Javascript with an Ajax call to change the content:
function addLink(){
var ajaxRequest; // The variable that makes Ajax possible!
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send(null);
}
'addLink.php' adds things to a table, theoretically allowing the content function 'displayContent()' to show the new entries in the table ('displayContent()' queries a table).
The PHP call works fine, but I have to refresh the page to see the changes.
Is there some problem with how I am doing this? Possibly because there are already PHP calls in the inner HTML when the page is loaded in the first place?
Any help is appreciated, I'm a bit of a beginner with Ajax.
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Sorry a little correction. You are attempting to access the pre-ajax php scripts inside ajax callback function. That's not how it works. You want the data that is retrived after-ajax call. Ajax retrives the output from the GET request, and store in ajaxRequest.responseText. Try replacing that and then see what you get.
In your addLink.php you should add the link and then echo out the data that you wish to display as the responseText. What had happened is that you inject the data VIA addLink but you never actually display it on the client side VIA ajax correctly. However, when you refresh the page, the script retrives what has been injected and display it accordingly.
In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.