javascript with XMLHttpRequest's open method: using post and its parameters - php

Users of my website will, ideally, be sending a few hundred posts to a db server over the course of about an hour (basically its an online-experiment). The experiment is implemented in js, so I'm trying to use an XMLHttpRequest object to post the data the script collects.
The thing I'm uncertain about is how to use the POST parameter. I want to set about 8 different key/value pairs to the $_POST variable so it can be accessible to a .php page for processing before sent to the db server. I'm not interested in retrieving any information from the server itself, only sending it (which is why, and I'm not sure whether it's the correct approach, I'm setting the readyState conditional to '1'/open).
Here's the script I'm working with at the moment:
function postData(dataList) {
var xmlhttp = new XMLHttpRequest();
var processingUrl = "process_exercise_data.php";
var POSTBody = "";
POSTBody+="block_type="+encodeURIComponent(dataList[0]);
POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
POSTBody+="&error="+encodeURIComponent(dataList[7]);
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState==4) {
xmlhttp.send(POSTBody);
}
}
The main goal is to send the key/value pairs to the .php page using POST while remaining on the current page(simple AJAX request, if I'm not mistaken). Any comments or suggestions are very appreciated!
Remember, all I'm trying to accomplish is having the user, when he/she acts in a certain way under a certain condition (outside of the scope of this function), to call this function and POST this data to the server. A server response text isn't needed.
EDIT:
Now my question is this: Will I still be able to access the $_POST array in at the processing php page? Here's an example:
$block_type = $_POST['block.type'];

You don't want to set request headers. What you want is to send request body along. And the body should be like
'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])
etc. Guess you got the idea. Body is what you pass to the send() method of XMLHTTPRequest object.

Consider using jQuery, it will make your task so much easier. Using the jQuery.post method you only have to provide the data hash, you don't have to worry about serialization, correct escaping or readyState.

You must call send before readyState will change.
Replace
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState=4) {
xmlhttp.send(POSTBody);
}
with
xmlhttp.open("POST", processingUrl, false);
xmlhttp.send(POSTBody);
If you want to handle a response, add define xmlhttp.onreadystatechange:
xmlhttp.open("POST", processingUrl, false);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4) {
// handle response
}
};
xmlhttp.send(POSTBody);
Edit: I would also like to mention that = is not the JavaScript equality operator, it's the assignment operator. Use === for equality checking and == for type-converting equality checking.

Related

How to tell which Javascript file is requesting data in PHP?

I have two javascript files, call it
test1.js
test2.js
they are used to request data from the php file using the following:
var xmlhttp= new XMLHttpRequest();
xmlhttp.open("GET", "../forum/getSomething.php", true);
xmlhttp.send();
and I have a php file which is used to do some queries and return the encoded json obj back to one of the js files above, call it
getSomething.php
my question is, how can I tell which file js is making the request to the php? Ultimately, I want to state a condition and do something like the this:
# inside getSomething.php
# conditional statements
if request from test1.js
do A
else if request from test2.js
do B
Any tips would be helpful, thanks
This is not possible without having the different files actually specify this themselves - this can for instance be done by adding custom headers to the XMLHttpRequest, or by adding additional query params.
You can use HTTP_REFERER with HTTP_X_REQUESTED_WITH but it can be tricky I'll advice you can to identify each js request with ID
Example
xmlhttp.open("GET", "../forum/getSomething.php?action=test1", true);
Then PHP
switch ($_GET['action']) {
case "test1" :
// Do Test 1
break;
case "test2" :
// Do Test 2
break;
}
You can not generically write code that says "this is coming from script x" - JavaScript engines do not keep track of where any particular line of code come from.
You can always pass explicit data (i.e. in query string) differently from each script i.e.
xmlhttp.open("GET", "../forum/getSomething.php?from=test1", true);
Side note: consider using JQuery.ajax for more generic code...

how can i use php codes in javascript file while php is including the javascript variable?

cuIzgaraKay is a javascript code I want to use it in sql command as cuIzgaraKay.id(it gets the value correctly I checked it). However, I could not it. I googled it but I can't find what I search . How can i do it ? sorry for asking syntax error but I can't find it maybe ı have logical error
if(cuIzgaraKay){
<?php
include_once('../phps/kutuphane/inc.php');
$result = mysql_query("select id from bolge_db where parent_id="?>+ cuIzgaraKay.id + <?);
As far as I can tell, you're trying to execute an SQL query from the PHP page, using data from the Javascript code you're generating.
The Javascript is only evaluated on the client side of your page. That means that the server-side cannot know anything about the Javascript code.
What you need to do, is to generate the ID, and communicate it to the PHP backend, for example with a HTTP POST/GET request or something.
EDIT:
If you're new to Javascript, I'd suggest you look into the native JS object XMLHttpRequest. You use it like this:
/*
params:
url: relative URL on host, e.g. '/users/morten/data'
method: GET, POST, PUT, DELETE, HEAD or OPTIONS
data: data to send with request, e.g. POST form-data
ok_cb: function to call on success
fail_db: function to call on failure
*/
function http_req(url, method, data, ok_cb, fail_cb) {
var client = new XMLHttpRequest();
client.onreadystatechange = function () {
if(client.readyState == this.DONE) {
if(client.status == 200 || client.status == 302 || client.status == 304)
ok_cb(...);
else
fail_cb(...);
}
};
client.open(method, url, true);
client.send(data);
}
Or you can use jQuery or a ton of other frameworks to do the same thing.
EDIT:
what is method in there how can i write there and how can i get data from php – user1702486
The method is whatever HTTP request method you want to use. See the wikipedia page for more info: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
This code will POST to /page.php sending a data-string along.
If the request returns a successful code, the ok-callback will be called.
// handle HTTP OK
var ok = function(meth, res, url) {
console.log("OK: got " + res);
}
// handle all else
var fail = function(meth, res, url) {
console.log("UTTER UTTER FAILURE!\n" + res);
}
// make a HTTP POST to server/page.php sending the data along
// you can serialize the data and use XML or JSON or whatever instead
http_req("/page.php", "POST", "username=usr&password=passw&userid=12345", ok, fail);
On the PHP page, you will need to handle the POST by checking the data and returning an answer if appropriate. Something like this:
<?php
if (empty($_POST))
{
print_r($_POST);
...
// do something with the data and print something back
}
?>
If you've posted "data1=1234&data2=5678&str=hello%20mum" the $_POST array will look like this:
(
[data1] => 1234
[data2] => 5678
[str] => "hello%20mum"
)
You can't, javascript is client side and php is server side. So the php code gets executed before the javascript.

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 do i get the response back from server after issuing a request object(AJAX)

I was studying about AJAX and it was about form validation where as soon as the person fills in the username for signing up, it is checked using AJAX while he still can enter all the other fields. so i issued a request and on readystatechange i called a callback function. now i have studied PHP before this, but i never came across returning information from the server. I mean to say that what all goes in my PHP script, and how does i make sure that the request issued is responded as desired. i dont want the exact code, if just bits of it,or the algorithm can be improved,
For example, i know i passed the username along with the url to the php script, and then i checked if it matched any of the existing usernames in my database(MYSQL and queries) , and normally i would just print the form again if there's a match, else i will exit();
but what do i do when i want to respond back to the object request?
It's really quite easy when you get the hang of it. It's even easier if you use jQuery's AJAX, http://api.jquery.com/jQuery.ajax/ - though don't bloat your site with this unless you intend on using loads of javascript (and use google's cdn for it)
In javascript, you make an XHR request either GET or POST to your PHP script. Usually you'll need to create a separate file for the view to any AJAX requests, because AJAX requests shouldn't bring the webpage's template back as well (i.e. if you wanted to return '1', it should only return '1', not <html><body>1</body></html>. ... etc.
Example:
blah.com/index.php needs some AJAX requests.
blah.com has javascript that creates the ajax request by sending a datastring/url (e.g. ajax.php?act=verify_email&email=a#c
blah.com/ajax.php would then have some PHP code that could switch($_GET['act'] or $_POST['act']) with a 'case' statement of 'verify_email'. That code would run some regex or something, and return 1 or 0 to say 1(valid), 0 (invalid). The 'onreadystatechange' holds the status of the request, so I think its usually a function i.e.:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
You access the returned '0' or '1' through the xmlhttp.responseText, where xmlhttp is var xmlhttp =new XMLHttpRequest();
Then you just run the request
xmlhttp.open("GET","ajax.php?act=verify_email&email="+document.getElementById('email').value,true);
xmlhttp.send();
Update: In your case with the form, onblur (when they move out of focus of an element), you could run the AJAX request sending the value of the input, and then in the ajax.php script as a GET or POST request, you could run your validation query to check if the user exists already, or if the username isn't valid or whatever. Once the request has completed, it will return the results in the responseText value. Use firebug's console to check the result of an AJAX request if you can, its very useful.
This might not be what you mean but can't you:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
// do something with "xmlhttp.responseText"
var x = xmlhttp.responseText
}
And in the php just:
echo $x;
That works fine for transmitting strings and other info...

How to I post a value through the XMLHTTPRequest Object?

I have a set of links dynamically generated in a table. Each of the rows has a unique "id" property on it's tag. The goal is to get XMLHTTPRequest to tell the page 'deletepost.php' which record to remove from an outside database.
It changes a hidden input value to the value of the row (a number), and then submits that form
<script type="text/javascript">
var http = false ;
// instance the request object!!!!
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
/////////////////////////////////////////////////
function rdel(num) {
document.getElementById("pid_to_del").value = num;
//this element is a hidden <input> tag. this line changes the value.
http.open("POST", "deletepost.php", true); //this _SHOULD_ post the form
http.onreadystatechange = function() {
if(http.readyState == 4) {
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(http.responseText); // this alerts whatever deletepost.php says
}
}
http.send(null);
}
</script>
This function rdel() is called by one of the links, which looks like this:
delete
This is what deletepost.php looks like:
<?php
print_r($_POST);
?>
The page that makes the request alerts:
Array
(
)
An empty array. :( Why?!
Two things here, the first is that you actually have to put your post string (very similar to a query string) into the
http.send(null);
call. So you would do:
http.send('field1=value1')
Secondly, in order for to actually notify the server that there are values being posted, you must set the content type for your request using:
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Hope that helps
EDIT:
I see now that you are trying to use this request to sent a serialized copy of an html form to the server asynchronously. Javascript does not contain the functionality to do this, but certain libraries and plugins (such as JQuery and AjaxForm) do.
For your example, however, you should be able to accomplish this using:
http.send('pid_to_del=' + pid);
The quickest fix would be:
where you open the XMLHttpRequest object:
http.open("POST", "deletepost.php", true)
change the url to be "deletepost.php?number="+num
then in you php page change the POST to a GET.
$number = $_GET['number']
POST allows you to send large amounts of parameters/options around but unless your numbers are going to be more than 140 characters long, this will make no difference. There appears to be a common mis-conception that POST is more secure than GET, simply because it seems more obvious how to get a browser to manipulate the post variable. However, it is a very very small stretch to do the same thing with POST variables so security should not depend on POSTing rather than GETting. There's nothing wrong with using POST except that you don't seem to be able to get it to work easily. I would never do this directly in javascript. I would always use something like jquery. You could replace the whole script with the following and it would work in most browsers:
function rdel(num) {
$.post("/webroot/deletepost.php", {number: num},
function(dat){
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(dat.responseText); // this alerts whatever deletepost.php
});
}
by the way, in your selector $('tr#r'+num), the tr is unnecessary since the id's on a page are unique so the result will be the same as $('#r'+num) but would take longer to calculate the selector. Reference by id is the fastest, the former finds all tr tags and then finds the id within that collection, rather than using the 'native' getElementById function by just using id in the selector. In short, don't make jquery do anything you don't need it to do ;)

Categories