I need to post a single form to 2 different URLs. One is just a logging script so the response doesn't need to be passed back to the user.
Unfortunately in this instance I can't just post to a single PHP script and turn around and re-POST it using Curl. This has to be done in the user's browser.
This is some Javascript I'm using right now but it's failing at a seemingly random rate for almost all the major browsers (but works 95%+ of the time). The rest of the form does require Javascript to function so I know the problem isn't just that some users have Javascript turned off.
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
I'm calling that after building the request manually in another function, then calling the submit() function of the form.
Can anyone suggest an alternative that might work better? This seems to be working ~95% of the time but that 5% failure rate is a killer... Thanks!
Try using a framework that supports error checking any try repeating the request on failure.
JavaScript frameworks like jQuery support sending post requests and can be used to check if a request was successful. Also your code will be easier to write and maintain.
Related
What is the best way to just run a PHP script when the user clicks a button? It sends nothing back to the user whatsoever! (The PHP script only sends a PostgreSQL query.)
I have only found ways of returning data. I only want to run it.
You're looking for AJAX (asynchronous javascript). Just have a javascript function call the target script and either don't return anything OR don't do anything with the return value. Alternately, you could simply have form that submits to a hidden iframe on the page.
This is the best I could come up with. Hope it was what you were looking for.
/* Function that we create to handle backwards compatiblity to browsers.
What it does is to try diffrent types of XMLHttpRequests. */
function getXMLHttp() {
var xmlHttp;
try {
//Firefox, Opera, Safari, Chrome, IE7+
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
//Internet Explorer 6
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//Internet Explorer 5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
return xmlHttp;
}
// Here, we send the request
function send() {
/* We say the variable xmlHttp is the function
where we try the diffrent XMLHttpRequests*/
var xmlHttp = getXMLHttp();
// We open your PHP file...
xmlHttp.open("POST", "yourphpfile.php", true);
// ...and send it to the server
xmlHttp.send();
}
A little brief
Since you're not getting anything back to the user, you use POST and not GET. It sends a request to the server to the file. And as you said in your question, something was sent to a PostgreSQL server. However, that PHP script is runned on your hosting server that supports PHP.
The most basic way to do this would be an html form.
<form action="somePHPfile.php" method="post">
<input type="button" value="Run somePHPfile.php" />
</form>
You could also do what Ben D suggested, but that's not the most basic way of doing this. Using jquery:
$("#YOURbuttonID").click(function(){
$.post("yourPHPfile.php", function(){
alert("Success!");
});
});
You will need to use Ajax and then you can update a div etc so user knows if the query was executed properly or not.
As the title states, I am looking for a flag script, explained below:
It should be like any video site flag script: click the small grey flag once, it becomes colored and you cannot click it again. It should be done in ajax as I don't want my user to have his page reloaded (and all activity restarted) just because he made the mistake of flagging an item on my site.
The php behind should not add multiple flags from the same user - i though it would be a good idea if it checked for a cookie, if not set -> increment field in MySQL and set cookie, if set ->ignore.
This is really urgent, as I am a total noob at ajax and Javascript and I need it done by Tuesday...
The reason I need this is that I really want to know how it's done because a project that we are studying at school has something similar and my homework is to think of a solution that would accomplish the same thing, without looking at the initial source code. I thought of a solution but don't have the time to implement it because this week as well as the next one, I have a ton of exams and I really don't want to miss any...
Thanks in advance for any help you give me!
Cheers!
Make an ajaxrequest, and let that do you php handling, when its done you send the return to your page.
I made you a template. I guess you can do the PHP yourself?
function setFlag(state){
var ajaxRequest; // The variable that makes Ajax possible!
//Set AjaxRequest for all Major browsers, nothing to do here, this is standard
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 is lame!");
return false;
}
}
}
// When the Ajax Request waits for php you get some status codes, everything is done when it reaches 4. Add your javascript events etc here...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState < 4){
//document.getElementById('ajaxCatchbox').innerHTML = "Load...";
}
if(ajaxRequest.readyState == 4){
// Some Javascript to change your flag colour image
}
}
// this is here your php happens without page reload. (In the php file)
var queryString = "?state=" + state;
ajaxRequest.open("GET", "ThePhpFileThatDoesYourDatabaseHandling.php" + queryString, true);
ajaxRequest.send(null);
}
The PhP does your database and sets the right var on 1 so you'll know which flag is clicked. Every time you refresh the page you use this var to display which flag is clicked. Just when there is no flag clicked yet, you'll add this function and in the Javascript change it on the fly because on that moment you havent reloaded yet.
i added something like state to the function coz I thought you might want to know which flag is clicked but ofc you can add ID our flagnumber etc... and you can send that to php using the querystring...
Gr
I am writing this javascript that will be used on several other domains which calls a php script(only on my domain) to return an array. I am using xmlhttp and it works great when testing on my domain, but as soon as the javascript is placed or called from a separate domain it completely breaks. Anybody know how to make this request cross-domain?
Note: I had to perform a weird little hack to allow me to make two separate calls and make sure that they were both returned before processing. Anyways this does work perfectly every time on my domain.
This is tin the javascript file that calls my php code for the array
function getUrls(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp2 = new XMLHttpRequest();
}
else {
// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// code for IE5 and IE6
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
parsedJSONurls = JSON.parse(xmlhttp.responseText);
xmlhttp2.open("GET", "http://mydomain.com/connect.php?q=companies", true);
xmlhttp2.send();
}
}
xmlhttp2.onreadystatechange = function(){
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
parsedJSONcompanies = JSON.parse(xmlhttp2.responseText);
runLoop(parsedJSONurls, parsedJSONcompanies);
}
}
xmlhttp.open("GET", "http://mydomain.com/connect.php?q=urls", true);
xmlhttp.send();
}
Try adding this header to your connect.php file
header('Access-Control-Allow-Origin: http://domain1.com, http://domain2.com');
If you want to permit all domains instead of a whitelist
header('Access-Control-Allow-Origin: *');
https://developer.mozilla.org/en/http_access_control
The reason for this is the same origin policy. It was put in place to stop malicious scripts from accessing sensitive data from other websites. You should look into writing a JSONP request as a workaround for your problem.
There's an ongoing community wiki I started last year that explains many ways of circumventing the same origin policy. A solution that fits your situation can most likely be found there.
Same with others, it's caused by same origin policy.
Suppose page is at "a.com", no matter where JavaScript file is,
As long as you use XMLHttpRequest approach, you can only access data from a.com.
Even subdomain a.a.com can't access a.com.
You can have 2 options:
1) Use <script/> tag hack
JSONP is great, but it seems you don't rely on any library.
It's a JavaScript nature you can include JavaScript locating on other domain. <script/> tag hack is a simple technique which dynamically create and append <script/> node.
And its src attribute is the URL which is in different domain.
function getUrl(url) {
var scriptEl = document.createElement("script");
scriptEl.src = url;
scriptEl.async = true;
document.getElementsByTagName("head")[0].appendChild(scriptEl);
}
// Predefined callbacks
window.companyCallback = function (responseData) {
parsedJSONCompanies = responseData;
};
window.urlCallback = function (responseData) {
parseJSONurls = responseData;
};
getUrl("http://mydomain.com/connect.php?q=companies");
getUrl("http://mydomain.com/connect.php?q=urls");
Of course you also have to modify your PHP to meet the need.
<?php
header("content-type: application/json");
if ($_GET['q'] === "urls")
{
echo "companyCallback(";
json_encode($result);
echo ");";
}
else
{
echo "urlCallback(";
json_encode($result);
echo ");";
}
?>
2) Place proxy.php in different domain
The above method is what I recommended.
If you don't want to revamp your code heavily, use proxy technique instead.
You must have privilege to add a proxy.php on different hosts.
The content like this:
<?php
$url = "http://mydomain.com/connect.php?q=" . $_GET["q"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
NOTE: Be careful about security issue, you need to check where the request from.
In JavaScript, you just need to point the url in xmlhttp.open() to this same domain PHP.
xmlhttp.open("proxy.php?q=urls", true);
Hope it helps.
Like others said you could use JSON-p) for that or if the browsers supports(new A-graded browsers do) CORS you could use that instead.
As mentioned most non html5 dont allow cross browser ajax requests. To get around this I call a remote javascript script.
use javascript to add a line like
<script type="text/javascript" src="http://www.somemedomain.xxx/myjavascript.php?arg1=xxx&arg">
on the myjavascript.php file on the other server, you can process, collect information collected from the browser.
you have to encode the php file as javascript.
header( "content-type: application/javascript" ) //check php.net
This will work in ie6+
I have developed a PHP web app. I am giving an option to the user to update multiple issues on one go. In doing so, sometimes the user is encountering this error. Is there any way to increase the lenght of URL in apache?
Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.
However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."
Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:
jQuery Ajax POST example with PHP
(Note the sanitize posted data remark) and
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Basically, the difference is that the GET request has the url and parameters in one string and then sends null:
http.open("GET", url+"?"+params, true);
http.send(null);
whereas the POST request sends the url and the parameters in separate commands:
http.open("POST", url, true);
http.send(params);
Here is a working example:
ajaxPOST.html:
<html>
<head>
<script type="text/javascript">
function ajaxPOSTTest() {
try {
// Opera 8.0+, Firefox, Safari
ajaxPOSTTestRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
var url = "ajaxPOST.php";
var params = "lorem=ipsum&name=binny";
ajaxPOSTTestRequest.open("POST", url, true);
ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxPOSTTestRequest.send(params);
}
//Create a function that will receive data sent from the server
function ajaxCalled_POSTTest() {
if (ajaxPOSTTestRequest.readyState == 4) {
document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;
}
}
</script>
</head>
<body>
<button onclick="ajaxPOSTTest()">ajax POST Test</button>
<div id="output"></div>
</body>
</html>
ajaxPOST.php:
<?php
$lorem=$_POST['lorem'];
print $lorem.'<br>';
?>
I just sent over 12,000 characters without any problems.
I have a simple workaround.
Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.
I got this error after using $.getJSON() from JQuery. I just changed to post:
data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
.done(function (response) {
if (response instanceof Object)
var json = response;
else
var json = $.parseJSON(response);
// console.log(response);
// console.log(json);
jsonToDom(json);
if (json.reload != undefined && json.reload)
location.reload();
$("body").delay(1000).css("cursor", "default");
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
alert("Fehler!");
});
An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:
The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line. POST is designed
to allow a uniform method to cover the following functions:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
Providing a block of data, such as the result of submitting a
form, to a data-handling process;
Extending a database through an append operation.
Working on an AJAX website (HTML,CSS,JavaScript, AJAX, PHP, MySQL).
I have multiple javascript functions which take rows from mysql, wrap them in html tags, and embed them in the HTML (the usual usage of AJAX).
THE PROBLEM:
Everything is working perfect, except when I run the site with Firefox (for once its not InternetExplorer causing the trouble).
The site is currently in the developmental stage, so its offline, but running on the localhost (WampServer, apache, Windows XP SP3,VISTA,7).
All other cross-browser conflicts have been removed, and works perfectly on all major browsers including IE, Chrome, Opera and Safari, but I get absolutely nothing from the HTTPRequest (AJAX) if the browser is Firefox.
All browsers have the latest versions.
THE CODE:
I have a series of javascript functions, all of which are structured as follows:
function getDatay(){
var a = document.getElementById( 'item' ).innerHTML;
var ajaxRequest;
try{//Browser Support Code:
// code for IE7+, Firefox, Chrome, Opera, Safari:
ajaxRequest = new XMLHttpRequest();
} catch (e){
// code for IE6, IE5:
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser is not compatible - Browser Incompatibility Issue.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState < 4){
document.getElementById( 'theDiv' ).innerHTML = 'LOADING...';
}
if(ajaxRequest.readyState == 4){
document.getElementById( 'theDiv' ).innerHTML = ajaxRequest.responseText;
}
}
//Post vars to PHP Script and wait for response:
var url="01_retrieve_data_7.php";
url=url+"?a="+a;
ajaxRequest.open("POST", url, false);//must be false here to wait for ajaxRequest to complete.
ajaxRequest.send(null);
}
My money is on the final five lines of code being the cause of the problem.
Any suggestions how to get Firefox and AJAX working together are most welcome...
Had to post the jquery one-liner that bunch of code translates into!
$("#theDiv").text("LOADING...").load("01_retrieve_data_7.php?a="+$("#item").text());
Look at that : http://translate.google.fr/translate?js=y&prev=_t&hl=fr&ie=UTF-8&layout=1&eotf=1&u=http://www.siteduzero.com/tutoriel-3-100294-l-objet-xmlhttprequest.html&sl=fr&tl=en
Google messes up the codes so take a look at the french version for codes : http://www.siteduzero.com/tutoriel-3-100294-l-objet-xmlhttprequest.html
Before investigating your code, make sure to disable any firefox addons you've got installed.
Both ABP and Firebug are known to interfere under certain circumstances when FF tries to execute js