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 ;)
Related
i am submitting a form using Ajax and storing the data in the database. It is storing the data in the database and without reloading the page it is giving alert box showing that that content has been added.
The same page is showing the content of the database, i need that part to refresh automatically without reloading the page so that it can also fetch the just added information.
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.getElementsByName('cvalue')[0].value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("POST", "process/do_course.php", true);
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
if(myAjaxPostrequest.responseText=="true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = document.getElementById('c');
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
}
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
'c' is the ID of the div tag which has to be reloded.
Thanks
This seems a bit nonsense:
var refreshContent = container.innerHTML;
container.innerHTML = refreshContent;
That way you're not refreshing, the content is exactly the same.
I don't know exactly what do you mean by "DB content", assuming coursename is what you want to add to your DIV then you have to do something like:
container.innerHTML += '<p>'+ coursename +'</p>';
jQuery would benefit your work a lot, your current code via jQuery would look like
function submitformwithajax() {
var coursename = $("[name=cvalue]").val();
$.post("process/do_course.php", {cvalue: coursename}, function(response) {
if (response === "true")
{
alert("Course Has Been Successfully Added To The Curiculum !");
var container = $("#c");
// Not sure why you're setting the container to the container here
container.html(container.html());
}
else
$("#submitcourse").text("An error has occured making the request");
}, "text");
}
I don't know why you set the text of the container to the text in the container but that may be an issue you are having. If your server response returns the data that needs to be displayed in th area you can use jQuery (or if you really prefer, the DOM) to update the fields or elements (or add as needed) on the fly. If you need to refresh that section based off a GET request, then just make a GET request for the data in the success statement.
I would also recommend using JSON for the return type from the server instead of plain text. A {"success": true} will allow you to check if (response.success) instead of using string comparison there.
Also, as a final side note, in Javascript you should always prefer === over == as === verifies that value and type both match, the downside to this is that in Javascript 1 == "1" but 1 === "1" is not true.
EDIT
In response to your comment, should you not persue the jQuery route, you can still implement all of that which I have explained here however you'll have to manually parse the response:
var resposne = JSON.parse(myAjaxPostRequest.responseText);
From there you can still check if (response.success).
I, personally, recommend showing the students how to do it this long and complex way, and then teaching them how to do it with jQuery. Should any of them pursue a web development career then they will either use jQuery or something very similar in function to it and it's best they learn about these things early on instead of after they get hired. I also suggest JSON returns from the server because it's a more expressive way to return data, instead of just "true" (what is true?) you say {"success": true} so you can see the request was successful.
The easiest way to do this is going to be return the contents of the "c" element from the ajax call, and then replace the old contents of "c" with the content returned by the ajax call.
After seeing your code: You are not filling that table with AJAX. I can only give you this advice. Fill that table dynamically with Javascript.
Create function which will find div#c.
If div#c has some children, destroy them.
Create a new element table.
Fill that table with new rows.
This is how you can make a table dynamically with data from the server which is provided by Ajax. So after sending data from the form you can call this function and your table will be recreated.
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.
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...
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;
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.