PHP, run code without opening windows on the webbrowser - php

If I have a list of elements, and via javascript the user moves the elements in another order, can I, after each move, launch a php code (like a php page) but without having to call it in the browser?

Create an XmlHttpObject for the URL, send() it, check results to see if the call was successful, and discard the responseText. As an example, suppose you have the new order in a variable testUrl, e.g., "http://domain.com/script.php?order=1,4,3,2"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", testUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
if (xmlText == 'Success')
// do nothing
else
alert (xmlText);

An addition to the above answer - for the sake of posterity, in case someone has to debug your code some day :) I use the following function call to get that object: (I believe it makes the JS more readable and portable). You can check the return value and if null, alert the user that AJAX is not supported by the browser.
function getXmlHttpObject () {
var xmlHttpObject = null;
try {
xmlHttpObject = new XMLHttpRequest();
} catch (ex) {
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
} catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttpObject;
}

Related

Second drop down list based off of first drop down list using one php file

OK I did my first successful SQL query that generated a drop down box in PHP! (yes I am still a big noob)
So my next question....
If I hit the select button, must I create a new page or can I have a 2nd drop down box be generated on the same page based upon the the submission of first list?
I saw this: response to similar question
But I am still unsure of form action and method.Keep it Self? Do I need/should I use 2 separate forms? (I am not ready to tackle AJAX and far from ready to tackle Java so please keep those options off the table :) ) Or should I just pass on to a second file.
if it can be done can you explain the form action and method used in each form?
If you're not ready for AJAX or Javascript then you'll need to add a second PHP page which will process the user's selection from the first drop-down box and display the appropriate second drop-down.
If you're new to all this then I'd advise you to keep it simple to begin with! Submitting a form and displaying a new page is the most basic way.
So in your first page's HTML you'll need...
<form action="second_page.php" method="post">
<select name="selection"> ... your drop-down code goes here ... </select>
<button type="submit">Next</button>
</form>
Then in second_page.php you'll need...
$selection = $_POST['selection']; // The variable $selection holds the user's selection
You can then output a second page based on the value of $selection.
I will prefer doing it via Ajax and JQuery, something like this :
function getClassList(elem)
{
var contentRequests, contentarr; // The variable that makes Ajax possible!
try
{
// Opera 8.0+, Firefox, Safari
contentRequests = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
contentRequests = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
contentRequests = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
contentRequests.onreadystatechange = function()
{
if(contentRequests.readyState == 4&& contentRequests.status==200)
{
document.getElementById(elem).innerHTML = contentRequests.responseText;
}
}
var urltofetch="index.php?methodname=getclasses"
contentRequests.open("GET", urltofetch, true);
contentRequests.send(null);
}
function getStudentList(classelem,elem)
{
var classToFetch = classelem + " option:selected";
var contentRequests, contentarr; // The variable that makes Ajax possible!
try
{
// Opera 8.0+, Firefox, Safari
contentRequests = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
contentRequests = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
contentRequests = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
contentRequests.onreadystatechange = function()
{
if(contentRequests.readyState == 4&& contentRequests.status==200)
{
document.getElementById(elem).innerHTML = contentRequests.responseText;
}
}
var classname = $(classToFetch).text();
alert(classname);
var urltofetch="index.php?methodname=getstudents&cname="+classname
contentRequests.open("GET", urltofetch, true);
contentRequests.send(null);
}

Ajax to read PHP

I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);

AJAX Request returns 'undefined'

For some reason I always receive undefined if I return the value but if I'm trying to display it in alert I receive the php values.
function getXMLHttp() {
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) {
//Browser does not support AJAX
return false;
}
}
}
return xmlHttp;
}
function isUsernameExists() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
handleResponse(xmlHttp.responseText);
}
}
var str = document.getElementById('username').value.toString();
xmlHttp.open("GET", "ajax.php?username="+str, true);
xmlHttp.send(null);
}
Edit:
function handleResponse(response) {
return response.toString();
}
Thanks,
Guy Dor
It looks like you are trying to read the return value from this function:
function isUsernameExists() {
It doesn't have a return statement, so it will always be undefined.
I'm guessing you expect this return statement to pass the value you want:
return xmlHttp.responseText.toString();
But that is part of this function:
xmlHttp.onreadystatechange = function() {
Which is called automatically when the readystatechange event fires, and not by any function call you make.
Asynchronous JavaScript and XML rarely uses XML but is asynchronous. Anything you want to do with the data fetched needs to be done by the callback function you assign to onreadystatechange. It can call other functions, but it cannot return anything (at least not that will be received anywhere useful).
We can't see enough of your code to fully understand the situation, but you are dealing with an asynchronous operation and the only way to communicate the result of that asynch operation is to call a function with the value you got from that operation. You cannot just return from the function.
This is a common misunderstanding (the sixth time I've answered this issue today). The function on have for the ready state change is not called by any of your code. It's called by the browser internally when the ajax call completes. That means that returning your value from that function will do nothing and certainly won't communicate that result to any of your code. If you want to communicate that result to some of your code, then you need to call some of your code from inside that function and pass it the desired result so that code can act on it. This breaks the normal flow of programming, but is required when dealing with asynchronous operations.
you have a return statement in the function your create here,
xmlHttp.onreadystatechange = function() {
but there is no return statement in the function,
function isUsernameExists() {
just because you created the function within another function does not mean the code in that function gets run.
the code within the function you created will not run until a response is received from the server, by which point the original function that created the second function will have already finished execution.
the code does not halt to wait for a response from the server, it instead continues to run and finishes execution. the function that you created to handle the response from the server then gets run at a later time when a response is received.

inserting javascript variable into php/mysql

I have two file one is index.php another one is dbsubmit.php
In my index.php i got some javascript variable in between script tag..
var address = "Address of some places";
var latitude = 79.00256978;
var longitude = 125.89564725;
i want to pass these variables into my php script (dbsubmit.php) so that i can populate MySQL database. How can i solve this problem?? can anybody help me??
You could use something like this and than in php using $_GET you can retrieve the values
<script>
function send(url){
var request;
try{
request= new XMLHttpRequest();
} catch (e){
try{
request= new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
request.onreadystatechange = function(){
if(request.readyState == 4){
//alert(request.responseText); this would be the value we get back, anything php would print would be alerted here
}
}
request.open("GET", url, true);
request.send(null);
}
send("dsubmit.php?address="+address+"&latitude="+latitude+"&longitude"+longitude);
</script>
You can use AJAX to pass the variables to a PHP script, which in turn will be able to write them to a database.
Are you using some sort of javascript framework (jQuery, etc.) ? Because they make it really easy.
You just have to make another php script to get the variables from $_GET or $_POST and save them. AJAX effectively calls the php script passing it those vars.

Sending two Ajax requests to two different PHP scripts from single javascript function

Is it possible to send Ajax requests to two or more Php scripts simultaneously? I know that this can be achieved serially (getting response from 1 and then getting response from the other) but I am wondering is it possible simultaneously. Please assist me with the following code:
function calShowUpload(){
if (http.readyState == 4) {
res = http.responseText;
document.getElementById('maincontent').innerHTML=res;
}
}
function showUpload(obj)
{
http.open("GET", "./showUpload.php", true);
http.onreadystatechange = calShowUpload;
http.send(null);
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
}
catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
In the above example I know that I can call another function like showUpload(obj) inside calShowUpload() to achieve my objective, but I need something like this:
function showUpload(obj)
{
http.open("GET", "./showUpload.php", true);
http.open("GET", "./showDelete.php", true);
http.onreadystatechange = calShowUpload;
http.send(null);
}
You need two instances of the XMLHttpRequest or the second will stomp the first. The very, very easiest way to do this with your existing code is simply to create two instances and write your JS to use whichever one is appropriate to the task.
var http1 = getXHTTP(); // Use this for one request.
var http2 = getXHTTP(); // Use this for the other request.

Categories