Do AJAX functions have to be in the same file calling them? - php

I am able to call javascript functions from a JS file without any issues. When I move AJAX functions into the same file then the functions cannot be called. Do AJAX functions require that they are in the same file that they're called from?
Home.html
<button onclick=scale(id)>scale</button>
<button onclick=save(id)>Save</button>
Javascript.js
function scale(id){
//scales the element with the given id
//works
}
function save(id){
//Does not work unless in Home.html file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "SaveValue.php?id="+id, true);
xmlhttp.send();
SaveValue.php
//Sends value to mysql db
-Update-
When I moved the AJAX function into a different JS file by itself, and linked it in the html file, everything worked.

JavaScript functions which perform Ajax options are no different from any other function as far as loading them is concerned.
There is no requirement to include the function inline in the HTML document.
You do, of course, still, need a <script> element to load them (or resort to things like fetching the script data with XMLHttpRequest and running it through eval — which is not recommended!).
If you have a problem, then it is most likely due to the <script> element failing to load the file. The most common reasons for this are revealed by the developer tools in your browser:
The URL is wrong (the Network tab will tell you that you aren't getting a 200 OK response)
The Content-Type is not application/javascript (or the legacy text/javascript). The Console will report an error and the Network tab will show the Content-Type.
The HTML for the <script> element is wrong or in the wrong place (this will often be picked up by the use of a Markup Validator).

Related

easyXDM, AJAX and Enjin

This is going to be about the same issue as my previous question (Loading a php file into cross domain page with dynamic element height) but now with trying to use a new method.
I found a way to load my script into an ajax div locally but there still remains the issue of cross domain security not allowing the xmlhttprequest to call to my other server.
The issues here is still that on Site A, which is my web server that I have full access to and is hosting my scripting files, I can do whatever I want with the script and make it work. On Site B, which is the on Enjin server, I have no access to host scripts. I can place .js scripts there and run those, but I can't use php from their servers which creates my issue. To get around this right now, I am using an iframe, which is inefficient to say the least. It can't load a dynamic height from the contents being generated by the php file it is calling from Site A. I planned on fixing this with loading this into a div via AJAX but I am having a few issues with that.
My AJAX script is this:
<pre><code>function Ajax(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',10000);
}
}
xmlHttp.open("GET","http://sitea.com/twitch_api/stream_header.php",true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',10000);
}
</code></pre>
then obviously the div is following the script.
the script that this is calling is this:
http://pastebin.com/mC8kakKJ
Sorry, can't get all the code to parse correctly in the code block but i made a pastebin copy of the script
My questions here become. What does my script need to look like for use with easyXDM? I have no experience with a library like this or cors, so an example markup would be awesome.
I am also not all that versed in javascript/ajax which leads to my second question. I my ajax code listed above, how would i go about having that div populate with the desired file immediately then update every 300000ms (5 minutes).
Any help is appreciated. Have a post on the Enjin forums but not too many there have experience going to this depth.
You could use $.getJSON(), Enjin pages use jQuery. Just make sure your server response is wrapped in a callback function so the cross site request is allowed.

Call JavaScript Function From PHP Script Using jQuery getScript

I'm very new to jQuery & web development in general. I'm attempting to use jQuery's ".getScript()" method to load a couple JavaScript scripts that are written in a particular PHP file, but I think I'm missing something.
(NOTE: I noticed several different questions that looked like they had the potential to help me, but none did. If there's one you know of, feel free to point me in that direction. Thanks.)
When I debug this in Firebug it hits the ".getScript()" call & then jumps on to the next line, seemingly without executing.
Here's how I'm trying to do it:
jQuery.getScript("relative/path/to/script/phpScript.php", function(){
alert("I'm HERE!");
setValues(); // JavaScript function that's written by phpScript.php
});
In this case, the JavaScript is being generated by the "phpScript.php" file and my "alert()" never gets run, but I'm not sure why. Any ideas?
I did notice that I'm getting some kind of parse error by following a suggestion in another question. I don't know how to resolve that. Here's the code for that:
jQuery(document).ajaxError(function(event, request, settings){
alert('error loading: ' + request.status + "\nevent: "+ event);
for (var key in request){
if (request.hasOwnProperty(key)) {
alert(key + " -> " + request[key]);
}
}
});
BTW, we're running jQuery with "jQuery.noConflict();" set, which is why I'm not using the shorthand "$()" notation.
Here is a snippet from the response body from the GET call in getScript():
<html><script type="text/javascript">
function setValues()
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
jQuery("#Form_DB").text(window.formDB);
jQuery('#pertaining_to').text(window.pertainNAME);
jQuery("#Pertain_To_ID").text(window.pertainID);
jQuery("#Form_ID").text(window.formID);
jQuery("#Field_ID").text(window.fieldName);
}
</script>
<head>
Thanks in advance,
-Mark
If you're loading JS scripts, try writing them as discrete functions into a .js file (e.g.: jsscript.js) and then using this HTML line:
<script type='text/javascript' src='jsscript.js'></script>
Then you can just call the functions themselves without using .getScript().
(Of course, you need to put the above line before the point where you call the scripts.)
That seems like a much cleaner way of doing it than what you're currently attempting.
EDIT: Given your present circumstances (i.e.: a PHP page that generates JS scripts and a PHP page that calls the scripts), maybe you can so something like this?
//PHP page that generates the scripts
function gen_script() {
//JS script generated into $script variable
return $script;
}
//PHP page that calls the scripts
include ('generate.php');
echo gen_script();
I thought you may just edit your phpScript.php file as
function setValues(){
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
//...
}
That will be OK.

Use ajax to call a php method

Hi i would like to use ajax in my website where all requests pass are loaded in index.php (i use htacess for rewriting urls) so when i use ajax i always reload the current page and then use if(expressio) to check if the user has called a function with ajax but this cause that all the page is reloaded each time i use ajax.
I was wondering if there is a method to call a specific php method/function or property in the current page with ajax without reloading all the page.
I'm using the jquery library for ajax
If someone knows some other ways is ok!
A main use of ajax is that you call asynchronously something. Most often functions-methods that are called with ajax do rely on the same php file (if not then it's okay) with other stuff that you do not need to call asynchronously.
For example you have a method that is called via ajax to autocomplete a text field (like google search) in a file that there is other stuff you don't want to execute too.
If you are under some mvc then you have controller check this out and make sure that only the requested method is called (I've done it successfully). So it is easier controlled under an mvc, all things are in classes...
If not under mvc then I guess you have to implement something like controller in order to call only the methods you like. However there is a conition that should be espected, no code should be found out of classes cause it would be executed on "include", it would go like this:
file ajax handler
1.Check if an ajax call
2.if check false return;
3.if true then get the name of the class file
4. call the desired method (or methods, you have an execution flow predefined during to your needs)
So it can be done. It is important not to execute code that is not supposed to be executed since then undesired results (or errors) would occur.
in ajax i use the current url as the action of the request but this
cause the re-load of the whole page.
Since you have your own mvc it could go like this index.php/rt=request/action where request=the name of the controller (which in the end is a class), and action is the name of the action (which in the end is a method inside the class-controller you are requesting) for example
mysite.com/rt=user/create
My point is that you don't care what the current url is, all you care is to call the right method(=action) of the right class(=controller).
The login class is istantiater in all pages because it check if a user
is logged;
I don't really understand this (when you say pages you mean php files?), whatever it is I suggest (if haven't done already) to follow the single entry point (no need to do this for ajax calls) where every request hits only to index.php like I showed you above. Then a few lines of code on the very top can do the login check.
And a last thing what kind of ajax is this that reloads all the page, this an example how I do ajax for autocomplete in a text field:
put this as it is in head-script-javascript to make the connection
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
or even better you can have it in a separate file and include it wherever you need it
then I use a function to do the asunchronous call, what I am doing is similar to your needs because I too get data from html and pass it to php (read the comments) and then execute sql.
function getMatch()
{
//get the form values, I have one value here, you get as need as many as you need
var str = document.getElementById("categ_name").value ;
var url = "internal.php";//php file to execute
//now pass the html form parameters to php
//do you see here controller is defined, it is named asynch
//then see the action (method of controller class) it is called getMatch
//then see how I pass the html form data with str, it is the string to match
//comcateg is the mysql table to get the match
var params = "rt=asynch/getMatch&data=" + (str)+"&from=comcateg";
request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer
//Some http headers must be set along with any POST request.
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = updatePage;
request.send(params);
}////////////////////
Then when the answear will be back this function will be called because we defined so above in the code
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200)
{
//test
var r=request.responseText.split("$$");
alert(r[1]);
}
else{
//alert("status is " + request.status);
}
}
}
I think now you can do it without problem, remeber whatever would be echoed by php even errors all of them will come back in the request.responseText. This is a tutorial among others about mvc that I like, https://sites.google.com/site/mhabipi/php-reading-material/superMVC.htm?attredirects=0&d=1 it's written by Kevin Waterson but sadly phpro.org does not work anymore.

How to insert a PHP dropdown in a HTML / Javascript page

Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = 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
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

Categories