I've been looking for a simple example of how to send POST data in a cross domain request in IE (with the XDomainRequest object).
I've been able to make a simple POST request, but haven't been able to add POST data to it.
Any help is appreciated, thanks!
Try something like this:
var xdr;
function err() {
alert('Error');
}
function timeo() {
alert('Time off');
}
function loadd() {
alert('Response: ' +xdr.responseText);
}
function stopdata() {
xdr.abort();
}
xdr = new XDomainRequest();
if (xdr) {
xdr.onerror = err;
xdr.ontimeout = timeo;
xdr.onload = loadd;
xdr.timeout = 10000;
xdr.open('POST','http://example.com');
xdr.send('foo=12345');
//xdr.send('foo=<?php echo $foo; ?>'); to send php variable
} else {
alert('XDR undefined');
}
Server side (php):
header('Access-Control-Allow-Origin: *');
if(isset($HTTP_RAW_POST_DATA)) {
parse_str($HTTP_RAW_POST_DATA); // here you will get variable $foo
if($foo == 12345) {
echo "Cool!"; // This is response body
}
}
Related
I don't have much experience with PHP, but what I'm trying to do is to write content to a file. For some reason the content is written to the file, but still returns 'failed to write to file!' with the 400 status code. But the contents are successfully written to the file. How?
php code (update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
I call update.php with following code:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
As you probably can tell it's quiet important to get the correct statuscode since I check for it and return if it's succesfull or not to the user. Anyone able to help me?
Thanks in advance!
Apperently the problem lays in the javascript check:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
should be
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
Also after I switched the if-statement (like told by #Jon Stirling), postman wasn't refreshed yet. So it was partially a wrong if-statement on the server side & wrong if-statement on the client side.
I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.
Tried to get answer, but returns 0.
JS in the head:
q = new XMLHttpRequest();
q.open('POST', ajaxUrl);
q.onreadystatechange = function () {
if (q.readyState === 4) {
console.log(q.response);
}
};
var data = {
'action': 'check_email'
};
q.send(JSON.stringify(data));
ajaxUrl links to admin_url('admin-ajax.php');
Code in the function.php:
function check_email() {
echo 'true or false';
die();
}
add_action('wp_ajax_check_email', 'check_email');
add_action('wp_ajax_nopriv_check_email', 'check_email');
Assuming a json request is valid, set the content-type to json
q.setRequestHeader('Content-Type', 'application/json');
if it isn't send application/x-www-form-urlencoded instead
q.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...
q.send('action=check_email');
q.responseText is what you're looking for.
I'm having an issue with my ajax POST for some reason the POST is never made! can't for the life of me work it out?
yeah so I used the network debug tool in firefox to check the POST request but the POST request never gets made..
The function is definitely getting called too as I have added an alert alert("start") to the beginning of the function which does run.
AJAX
<script>
function updateContentNow(pid2, status2) {
var mypostrequest = new ajaxRequest();
mypostrequest.onreadystatechange = function() {
if (mypostrequest.readyState == 4) {
if (mypostrequest.status == 200 || window.location.href.indexOf("http") == -1) {
document.getElementById("livestats").innerHTML = mypostrequest.responseText;
} else {
alert("An error has occured making the request");
}
}
}
var parameters = "cid=clientid&pid=6&statusinfo=approve";
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
UPDATED WORKING: thanks peps..
<script>
function updateContentNow(pid2,status2)
{
var mypostrequest=new XMLHttpRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("livestats").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var parameters="cid=<?=$clientID?>&pid="+pid2+"&statusinfo="+status2;
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
Are you using some external Ajax classes, at least ajaxRequest() object doesn't exist in plain JavaScript. Try to substitute this line
var mypostrequest = new ajaxRequest();
by that:
var mypostrequest=new XMLHttpRequest();
Then even calling your method with
updateContentNow("","");
at least makes the POST request as you easily can see with Firebug.