Post a Form to a PHP File using XMLHTTPRequest/AJAX - php

I am a bit forgetful of PHP, is there a simpler way to post a form using JavaScript AJAX, don't want to add jQuery simply to post an ajax request, without having to pass the parameters?
I want to post the form via Ajax and not have to get the parameters and send them in the call, is this possible? Is there an alternative to the following code...
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
var parameters="name="+namevalue+"&age="+agevalue
mypostrequest.open("POST", "basicform.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
**mypostrequest.send(parameters)**
It is my intent to use POST instead of GET to hide what is being sent on the URL, this feels strange and it's the same as using a GET. Or am I reading this wrong?

Just don't use jQuery if you only want some plain simple Ajax.
This will do the job just fine:
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.open('GET', url)
httpRequest.send()
All kudos go to: https://gist.github.com/liamcurry/2597326
Now we could also add some more browser support (IE6 and older: http://caniuse.com/#search=XMLHttpRequest) # all those jQuery heads: jQuery 2 dropped support for IE8 and older so no 'extra support' there.
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject()
{
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try
{
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
catch(e) { }
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
All kudos go to: http://www.cristiandarie.ro/asp-ajax/Async.html
This post was sponsored by Google (a really powerfull tool, you type in stuff and it gives more stuff with answers)

Related

How to receive jQuery post response before completing execution of PHP script?

I have a simple jquery function that sends a post request to a PHP file like this:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
And a PHP file:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??
Thanks
It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.
In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.

split return data from old way ajax

i have page that do add new record by old way ajax, this code was add new record and return the error or done result message , how can i print the message on div and print result on other div. i try but some one tell me to use JOSN, how can i do that
<script language="JavaScript">
$(document).ready(function() {
});
$("#closeerr").live('click', function() {
$("#gadget").hide();
});
var HttPRequest = false;
function doCallAjax(Mode,Page,ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxItemsGroupsRecord.php';
var pmeters = "titems_groups_GroupName=" + encodeURI( document.getElementById("items_groups_GroupName").value) +
"&titems_groups_sys_type_ID=" + encodeURI( document.getElementById("items_groups_sys_type_ID").value ) +
'&myPage='+Page +
"&tID=" + ID +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "looding";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
If jQuery is an option... As mentioned in my comment I'd recommend you try out jQuery http://jquery.com/ as you look to be fairly new to JavaScript.
It makes AJAX requests a lot simpler and you don't have to worry about making XMLHttpRequest work cross browser.
For making an actual AJAX request see: http://api.jquery.com/jQuery.ajax/
Now if you want to use JSON you need to convert the data to return in your PHP script.
This is really easy, you just pass the data in json_encode() and it will convert the data to a JSON string. You then just echo it out so that it's returned to the AJAX request.
echo json_encode($data);
Now if you've setup your AJAX request to expect a JSON response then you can use the data that comes back. So something like this:
$.ajax({
url: 'request.php', // the php you want to call
dataType: 'json' // the type of data being returned
}).done(function(json) {
// you now have a json object
});
If you can only use native JavaScript...
If you can't use jQuery then it roughly works the same way. You'd have the code in your example for the AJAX request. You'd still use json_encode() in the PHP. The only difference is when the data comes back you'd need to parse it like so:
JSON.parse(json);
For more info on this last bit checkout: Parse JSON in JavaScript?

Check for username while typing in field?

I am fluent with HTML, and mostly PHP.
I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.
My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..
Do you know how to do this, or at least know a link that tells you how to do it?
This sounds like a problem for jQuery. I'd give you a long-winded example, but there are many people that would give you a much better one: like this guy.
Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):
function getXMLObject() {
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
return xmlHttp;// Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object
//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
if (xmlhttp) {
xmlhttp.open("POST", scriptAddressWithParams, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and here's an example of usage:
<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>

Is it possible to send an AJAX request on load?

Hello I have two dependants select box, the second one is popularited after onchange event.
The first one is loaded with a selected value (selected=selected), what I'm asking, it is possible to send the requested while the page is loading, ie as I have the the selected option, just send the request.
Javascript
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSubCat(catId,incat) {
var strURL="../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('subcat').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The PHP will be provided if needed
You really need to use jQuery and replace all of the above with:
function getSubCat(catId, incat)
{
$('#subcat').load("../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat);
}
// Run on load:
$( function(){
getSubCat(4, 5);
});
It will do the same thing. It's set up to run on load, and you don't have to worry about cross browser compatibility.
You will find yourself using jQuery selectors all the time and your code will be very lightweight. If you link the jQuery library to Google servers people will not even have to download it. Most people have it in cache already.
You could use the onload event like this:
window.onload = function(){
var selectbox = document.getElementById('select box id');
if (selectbox.value !== ''){
// your code to send ajax requests...
}
};
The code runs as soon as page loads. It then checks if the value of the specified select box is not empty meaning something is selected; in that case you put your code for the ajax request which will execute.
Since you are doing this before getting any input from the user, you could immediately make the call to the server, before the DOM is finished, before the page is fully loaded, and then just wait until the onload event takes place, or you get informed that the DOM tree is finished, and you can then safely change the value of any of the html elements.
This way you don't have the user wait for the browser to finish loading before you even start your request, which will improve the user experience.

Using two xmlhttprequest calls on a page

I have two divisions, <div id=statuslist></div><div id=customerlist></div>
The function sendReq() creates a xmlhttprequest and fetches the data into the division.
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
I have a problem,
The data fetched into the 'customerlist' gets copied onto 'statuslist'
If i change the order of function calls,
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
Now the data of 'statuslist' gets into 'customerlist'..
Whats the problem with the code?
That's also my problem right now. After a thorough research, I've found out that:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task
- W3Schools.com
Also, thanks to Two xmlHttpRequests in a single page which redirects me to this question Using two xmlhttprequest calls on a page, I was able to solve the problem. By the way, it is a modification of Addsy's answer.
First, create a ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task. Example:
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
Second, call the function and pass the necessary parameters. For example:
sendReq("orders_code_get.php?currentquery="+sql, function processResponse( response )
{
document.getElementById("orders_content").innerHTML="";
document.getElementById("orders_content").innerHTML=response;
});
I have proven and tested this code and it works.
I have had this before.
Basically you have a scope problem - you have something like this in your sendReq() function?
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
And so when you make a second request, the xmlhttp object is over-ridden
You need to create a closure where your xmlhttp objects don't clash
eg
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
... probably some other stuff here, setting url etc ...
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4&&xmlhttp.status='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
.. probably more stuff here ( including xmlhttp.send() ) !! ...
}
you can then pass the callback function as a parameter and when the data is successfully loaded, it will be passed to the callback function. Note that you will need to pass the actual function, not just its name (so no quotes around the function name)
Alternatively, you could do what i do which is just use jQuery - works for most of my js problems ;)
Hope this helps
In fact it is possible to run multiple async xhr call but you have to give them an unique id as parameter to be able to store and load them locally in your DOM.
For example, you'd like to loop on an array and make a ajax call for each object. It's a little bit tricky but this code works for me.
var xhrarray={};
for (var j=0; j<itemsvals.length; j++){
var labelval=itemsvals[j];
// call ajax list if present.
if(typeof labelval.mkdajaxlink != 'undefined'){
var divlabelvalue = '<div id="' + labelval.mkdid + '_' + item.mkdcck + '" class="mkditemvalue col-xs-12 ' + labelval.mkdclass + '"><div class="mkdlabel">' + labelval.mkdlabel + ' :</div><div id="'+ j +'_link_'+ labelval.mkdid +'" class="mkdvalue">'+labelval.mkdvalue+'</div></div>';
mkdwrapper.find('#' + item.mkdcck + ' .mkdinstadivbody').append(divlabelvalue);
xhrarray['xhr_'+item.mkdcck] = new XMLHttpRequest();
xhrarray['xhr_'+item.mkdcck].uniqueid=''+ j +'_link_'+ labelval.mkdid +'';
console.log(xhrarray['xhr_'+item.mkdcck].uniqueid);
xhrarray['xhr_'+item.mkdcck].open('POST', labelval.mkdajaxlink);
xhrarray['xhr_'+item.mkdcck].send();
console.log('data sent');
xhrarray['xhr_'+item.mkdcck].onreadystatechange=function() {
if (this.readyState == 4) {
console.log(''+this.uniqueid);
document.getElementById(''+this.uniqueid).innerHTML = this.responseText;
}
};
}
}
You have to set each xhr object in a global variable object and define a value xhrarray['xhr_'+item.mkdcck].uniqueid
to get its unique id and load its result where you want.
Hope that will help you in the future.

Categories