How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}
Related
I am using SimpleXMLElement() to obtain data from a website, which is used to embed data. The code I am using is as follows:
$rss = new SimpleXMLElement('http://eliteprospects.com/rss_player_stats2.php?player='.$player_array[0]['embed_stats'], null, true);
foreach($rss->xpath('channel/item') as $item)
{
echo utf8_decode($item->description);
}
This works great, except for one issue, the data loads exceptionally slow from the other site. The page load goes from approximately 0.5-1s to 2.5-3s.
Is there a method that I can use, to load the asynchronously, or is there a faster function I should be using instead?
An idea that came to mind was to load a separate page within an iFrame after the initial page load, or is there a better method?
Is there a method that I can use, to load the asynchronously, or is
there a faster function I should be using instead?
Unfortunately, there is nothing to do about the long response time (trivially assuming that connection speed in not archaic). Also echoing out the results all at once might slow down the browser rendering and thus the page load time.
AJAX fits nicely here - wait for window.onload and trigger the AJAX call to your webservice (holds the snippet from question) to prepare the output buffer and return the response to browser. Afterwards set/replace the innerHTML value of selected DOM element with the response.responseText.
Pseudo-code
window.onload = function()
{
var url = 'http://example.com/webserice';
Ajax.get(url, function(response)
{
var responseText = response.responseText;
document.getElementById('someid').innerHTML = responseText;
}
}
The snippet I am using in pure JS, although jQuery has a lot more appealing way to do it
Ajax = {
request : {},
createRequest : function()
{
var request = false;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
else
{
request = false;
}
}
return request;
},
get : function(page, callback)
{
var self = this;
var request = this.createRequest();
if (! page)
{
return false;
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
delete self.request;
if (typeof callback == 'function')
{
callback(request);
}
else
{
self.update(request, callback);
}
var regex = /<script\b.*?>([\s\S]*?)<\/scri/ig;
var match;
while (match = regex.exec(request.responseText))
{
eval(match[1]);
}
}
}
request.open('GET', page, true);
request.setRequestHeader('X-Requested-With', 'ajax');
request.send(null);
}
}
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?
I am using a web app called ProcessMaker.
They do not have support for jquery. So I had to figure out how to integrate it myself. There were lots of people on their forums trying to get it done, so thankfully it now has been documented. If anyone would like to do so here is the link where I have detailed the process: jQuery with ProcessMaker
My question is now using the jquery ajax request.
In order to use jquery with processmaker I had to overcome 2 problems. The first the Smarty filtering since processmaker uses templating langauge. And the second the Maborak lib doesn't allow certain things.
So now I believe it to be a maborak issue, but I do not know for certain. All I know when I try to run my code, the error console (firefox 4.x) gives me the following error: jqXHR[i] is not a function.
This is happening at line 7323 of my jquery lib that I included (version 1.6.2).
I have Googled, and all I have come up with so far is that people are saying it can possibly be a befreSend issue and that disabling it fixes it.
Maybe I don't know how to disable it properly, but it isnt working still.
If anyone can help me with this, it would be very greatly appreciated.
Thanks,
Zedd
In Processmaker exist a library "makorak" this library generate problems with other libraries.. hence you Should use jquery as follows...
var $JQ = jQuery.noConflict();
$JQ("#myField").value = 'cochalo';
hope I've helped
Try this:
$.noConflict();
jQuery(document).ready(function($)){
$("button").click.function(){
$("p").text("jquery is still working");
}
}
before:
you need declare this:
var $j = jQuery.noConflict();
and... you must don't use $() any more
instead:
use $j()
example:
// Use jQuery via $j(...)
$j(document).ready(function() {
$j("div").hide();
});
that's all
read new documentation about ajax in dynaform in this
or
Write this function
function ajax(url, callback, error, method, cache, async) {
async = async || true;
//alert(cache);
if (typeof(cache) == 'undefined') {
cache = false;
}
if (typeof(method) == 'undefined') {
method = 'GET';
}
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp = new XMLHttpRequest();
} else // code for IE5, IE6
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
if (typeof(callback) == 'function') {
callback(xmlhttp.responseText);
}
} else {
if (typeof(error) == 'function') {
error(xmlhttp.status);
} else {
alert('خطا : لطفا مجددا تلاش کنید.');
}
}
}
}
var d = new Date();
var n = d.getTime();
var getExplode = url.split("?");
scriptName = url;
param = '';
if (getExplode.length > 1) {
scriptName = getExplode[0];
param = getExplode[1];
if (cache == false) {
param = param + "&n=" + n;
}
} else {
if (cache == false) {
param = param + "n=" + n;
}
}
if (method.toLowerCase() == 'post') {
xmlhttp.open("POST", scriptName, async);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
} else {
xmlhttp.open("GET", scriptName + '?' + param, async);
xmlhttp.send();
}
}
and use it like this
var url = ajaxUrl + "OperationRenovation.php?Command=GetDetail&IdDarkhast=" + ID + "&Code=" + Code + "&Mabna=" + Mabna;
ajax(url, function(Response) {
alert(response);
}, function() {
alert('مشکل در برقراری ارتباط با سرور');
}, 'post');
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 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.