I got the following code from here
I've tried this code with variable data being equal to 'test=yes' or with data being equal to {test:'yes'}
Here is the php script
if(isset($_POST['test'])){
error_log("inside");
echo "and I'd also like to return this";
};
And here is the nodejs piece of code:
function postToPHP(data, path){
var httpreq = require('http');
var querystring = require("querystring");
var data = querystring.stringify(data);
var options = {
host : 'localhost',
path : 'www' + path, //path is well defined in the actual code
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : data.length
}
};
var buffer = "";
var reqPost = httpreq.request(options, function(res) {
res.on('data', function(d) {
buffer = buffer+data;
});
res.on('end', function() {
return buffer;
});
});
reqPost.write(data);
reqPost.end();
}
And the call of postToPhp
//treat message?
var message = "test=yes";
//OR
var message = "{test:'yes'}";
var buffer = postToPHP(message,"path");
console.log("buffer from PHP",buffer);
buffer is undefined
Nothing is shown in the error log and I assume something is not working with the code that I can't figure so I hope someone can help me figure this one out.
Related
I'm trying to load a php file into a div on submission of a form. At the moment everything fires bar this line $('#signupform').load('newsletter-signup-call.php');, I've just got a simple echo request in there and it doesn't fire. If I goto that template it works though.
Where am I going wrong? Could I possibly fire two Ajax calls (as that in itself works) but there seems to be issues with load.
<script>
$("#signupForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var email = $("#EmailAddress").val();
$.ajax({
type: "POST",
url: form.attr('action') + '?email=' + email,
data: form.serialize(),
beforeSend: function(){
$(".newsletter-loading").show().css({"display":"inline-block"});
},
success: function(data)
{
console.log(data); //data contain response from your php script
register_signup();
register_prefs();
(function() {
window.sib = {
equeue: [],
client_key: "xxx"
};
/* OPTIONAL: email for identify request*/
window.sib.email_id = email;
window.sendinblue = {};
for (var j = ['track', 'identify', 'trackLink', 'page'], i = 0; i < j.length; i++) {
(function(k) {
window.sendinblue[k] = function() {
var arg = Array.prototype.slice.call(arguments);
(window.sib[k] || function() {
var t = {};
t[k] = arg;
window.sib.equeue.push(t);
})(arg[0], arg[1], arg[2]);
};
})(j[i]);
}
var n = document.createElement("script"),
i = document.getElementsByTagName("script")[0];
n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();
})();
sendinblue.track('marketing');
$(".newsletter-loading").hide();
form.replaceWith("<br /><p>Thanks for signing up! You'll receive an email with your discount.</p>");
}
});
});
function register_prefs(){
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php');
}
function register_signup(){
ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
}
</script>
Try to console.log the response status to see what's going wrong
function register_prefs(){
//see if this function is triggered
console.log('register_prefs function triggered')
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php', function( response, status, xhr ){
console.log('Server response : ', response)//The serve response
console.log('Status Message : ', [xhr.status, xhr.statusText])//See the status of your request, if any error it should be displayed here
});
}
BUT, Why perform another server call with load, when your are already using ajax, you can return the html in the first call in a json object {Mydata: ..., MyHTML: ...} and just use $('#signupform').html(data.MyHTML) on success.
Also, not sure but I'm suspecting a malformed URL, try this instead '/newsletter-signup-call.php' or an absolute path just to be sure.
I am having a problem using post method in Angular 5 and PHP.
I have this method from a .ts class:
addPartners(partnerName)
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
this.name = JSON.stringify(partnerName)
console.log("hi "+ this.name)
return this.http.post('http://aff.local/addPartner.php', this.name, {
observe: 'response',
responseType: 'json'
}).pipe(map(
res=>{
console.log(res)
}
))
}
And I will call it on (click) event of a button:
addPartner(){
this.email = this.subscribeForm.get('emailTxt').value;
//console.log(this.email)
this.api.addPartners(this.email).subscribe(
(data)=>{
console.log(data);
this.subscribeForm.reset();
},
(error)=>{
console.log(error)
}
);
}
The PHP script is :
addPartner($partnerName);
echo $result;
?>
When I fill the textbox and click on the button, the value sent is empty.
When I change the method, by sending the variable in the url it work properly.
Here is the working script. In the api main class:
addPartners(partnerName)
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
this.name = JSON.stringify(partnerName)
console.log("hi "+ name)
return this.http.post('http://aff.local/addPartner.php?name='+ name, {
observe: 'response',
responseType: 'json'
}).pipe(map(
res=>{
console.log(res)
}
))
}
I just changed the url into:
http://aff.local/addPartner.php?name='+ name,
And in the php script I will get it using $_REQUEST['name'].
What I want is using the POST method because I need to send multiple data from a form.
if you want to use JSON.stringify so you can take params from the server side using :
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
or if we want to just take data using $_POST['paramName'] so we have to use the below in your client side:
let headerOptions = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
let data = {name: partnerName};
let body = this.formatData(test);
and format your data like that:
formatData(data) {
let returnData = '';
let count = 0;
for (let i in data) {
if (count == 0) {
returnData += i + '=' + data[i];
} else {
returnData += '&' + i + '=' + data[i];
}
count = count + 1;
}
return returnData;
}
In the POST-example you used this.name, but in the GET-example only name.
Try to use $_POST['name'] instead of $_REQUEST['name], because $_REQUEST['name] is a different variable then $_POST or $_GET and also differently treated.
Admittedly, there are similar questions lying around on Stack Overflow, but it seems none quite meet my requirements.
Here is what I'm looking to do:
Upload an entire form of data, one piece of which is a single file
Work with Codeigniter's file upload library
Up until here, all is well. The data gets in my database as I need it. But I'd also like to submit my form via an AJAX post:
Using the native HTML5 File API, not flash or an iframe solution
Preferably interfacing with the low-level .ajax() jQuery method
I think I could imagine how to do this by auto-uploading the file when the field's value changes using pure javascript, but I'd rather do it all in one fell swoop on for submit in jQuery. I'm thinking it's not possible to do via query strings as I need to pass the entire file object, but I'm a little lost on what to do at this point.
Can this be achieved?
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.
Check out fwrite() and jQuery.post().
On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
I have to create a web application using JQuery and PHP with cross-domain AJAX requests. So, I use JSONP to do my request. It works fine on Firefox, but not on Chrome and Opera.
I have one function for executing the request :
function update()
{
$.ajax({
url : url,
type : "GET",
dataType: "jsonp",
crossDomain : true,
jsonpCallback : "updateCallback",
async : false,
data : {'session_id' : sessionID,'user' : userName },
error : function (xhr, status, error) {
alert("Erreur de chargement du fichier '"+url+"' : "+xhr.responseText+" ("+status+" - "+error+")");
},
success: function(){
alert("Success !");
}
});
}
This the callback function :
function updateCallback(data)
{
var i = 0;
var messages = data.messages;
while(i < data.messages.length){
appendMessage(data.messages[i]);
i++;
}
saveLastMsgID = lastMsgID;
doUpdate = updateInProgress = false;
}
The PHP script called by the AJAX request :
<?php
/* ... */
function sendResponse($messages,$date)
{
header('content-type: application/json; charset=utf-8');
header("Access-control-allow-origin: *");
header ("Access-Control-Allow-Headers: x-requested-with", true);
header('Access-Control-Allow-Methods: GET,OPTIONS');
$datas = array();
for($i = 0 ; $i < count($messages) ; $i++){
$msg = $messages[$i];
$message = null;
$message->sender = $msg->getSender();
$message->date = $date;
$message->msg = stripslashes($msg->getContent());
$message->carrier = $carrier;
$datas[] = $message;
}
$data->messages = $datas;
echo $_GET['callback']. '('. json_encode($data) . ')';
}
?>
Thanks for your help!
Man, you've got alot of stuff in there. It's not really necessary. Try this. It lets jQuery handle your callback so the success function gets passed the object represented by the JSON embedded in the response:
function update()
{
$.ajax({
url : url,
dataType: "jsonp",
// async : false, <-------- THIS IS IGNORED BY JQUERY DUE TO JSONP DATATYPE
data : {'session_id' : sessionID,'user' : userName },
success: function(data){
// alert("Success !");
var i = 0;
var messages = data.messages;
while(i < data.messages.length){
appendMessage(data.messages[i]);
i++;
}
saveLastMsgID = lastMsgID;
doUpdate = updateInProgress = false;
}
});
}
JSON-P isn't JSON. It is JSON embedded in a JavaScript program. The MIME type should be application/javascript.
It is possible that Chrome and Opera are reacting to what appears to be an attempt to inject a function call into a JSON string.
I was wondering if you install any adblock plugins in your browser and your request url contained some keywords like "ad".
I had the similar issue, finally found it was the adblock caused the problem.
when user allow my app i receive this type of success url:
http://localhost/fbapp/app.php#access_token=AAAAALY8OpPABAM67auStdfgdfOdfgdfgdenqEt9QZCGD2a1h3iWFrhmNWqOf8l4a9RQ8tAJCM9y5QbYpsP6sT1g0ZCXDhtZCECZApGb&expires_in=6604
i am trying $_GET['access_token'] to save access token, but it's not working,
i want to know that how to get access token from this url..
From your use of $_GET, I'm assuming you are talking about PHP. Unfortunately, hash tags are never sent to the server. They only live on the client side so you need to use some javascript to then make a call to a PHP script.
Example:
<script type="text/javascript">
var HashSearch = new function () {
var params;
this.set = function (key, value) {
params[key] = value;
this.push();
};
this.remove = function (key, value) {
delete params[key];
this.push();
};
this.get = function (key, value) {
return params[key];
};
this.keyExists = function (key) {
return params.hasOwnProperty(key);
};
this.push= function () {
var hashBuilder = [], key, value;
for(key in params) if (params.hasOwnProperty(key)) {
key = escape(key), value = escape(params[key]); // escape(undefined) == "undefined"
hashBuilder.push(key + ( (value !== "undefined") ? '=' + value : "" ));
}
window.location.hash = hashBuilder.join("&");
};
(this.load = function () {
params = {}
var hashStr = window.location.hash, hashArray, keyVal
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
for(var i = 0; i < hashArray.length; i++) {
keyVal = hashArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
})();
}
$.ajax({
type: "POST",
url: '/store_access.php',
data: 'access_token='+escape(HashSearch.get('access_token'),
dataType: "html",
success: function(response) {
alert('Access Token Stored');
}
});
</script>
I found the HashSearch function here: Retrieve specific hash tag's value from url
Also, I assumed jquery on the post to your script, but you could use anything to make the call. You could even just add an image to the body with a url that includes the token.
You are using the client-side authentication auth URL instead of the server side URL which is why you are getting an access_token as part of the URL fragment instead of as a GET variable.
Remove response_type=token from your auth URL and then follow the Server Side Authentication.