Send post data from Phonegap (Cordova) to server - codeigniter

I have a form in my Cordova app:
<form id='transport' method='POST' action='' enctype='application/json'>
<input type='hidden' id='data' name='data' value='' />
</form>
and I sent to server (pure js):
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user/';
document.getElementById('transport').submit();
but the data variable is empty when received on server.
On server I'm using Codeigniter.
Works perfectly in a web scenario, why not in Cordova? I know there is not the cross-domain problem, and I have allowed all domains (*) in config.xml.
Thanks.

Fixed! Just remove te slash (/) at the end of the URL.
This is because Codeigniter - with this slash - is expecting another parameter (due to its nature url-based) and if there is not, all the variables inside the controller (such as POST data) are null.
So this:
postdata = '{';
postdata += '"first_name": "Jon",';
postdata += '"last_name": "Snow"';
postdata += '}';
document.getElementById('data').value = postdata;
document.getElementById('transport').action = 'http://testserver.com/add_user';
document.getElementById('transport').submit();
it's correct.

You can achieve this with pure JS by using xmlhttp.
This one omits the wrapping of the data variable, so you get first_name and last_name as their own parameters.
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
params = "first_name=" + first_name + "&last_name=" + last_name;
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
You can also send the data as JSON like this:
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//Not sure if you need the Content-length here or not.
xmlhttp.send(JSON.stringify({"data"=>{"first_name"=>first_name, "last_name" => last_name}}));
}
I find this approach cleaner than using an invisible form when it isn't really needed.

Related

Taking value from text-field and sending it with AJAX request Javascript

I am trying to sync both client-side and server-side scripts that the client intakes a value from the textbox and sends it to the server, upon which the server displays that input as a cookie.
Here is the code that I have so far
function loadCookie() {
//[1] make a new request object
var xhttp = new XMLHttpRequest();
//[2] set the request options
xhttp.open("GET", "index.html", true);
//[3] define what you will do when you ge a response (callback)
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input_response").innerHTML = this.responseText;
}
};
//[4] finally send out the request
xhttp.send();
}
I have the and the button but I am having issue of the page re-loading itself instead of taking the value of the input and showing it as a cookie in the server. I'm suspecting it is having to do with the URL by the index.html

Laravel 5 X-CSRF-TOKEN 500 (Internal Server Error) in Ajax

Hello I have change password using Ajax (this is a short version of the code):
var password = document.querySelector('[name="password"]').value;
action = 'http://localhost:8012/market2/market2/public/account/query/';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("post",action + password, true);
xmlhttp.setRequestHeader("X-CSRF-TOKEN", document.getElementById('token-csrf').value);
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "false") {
document.getElementById("error_password").innerHTML = "You actually password is wrong!";
return false;
} else {
document.getElementById("error_password").innerHTML = "OK";
return true;
}
}
}
xmlhttp.send();
}
And my csrf-token:
<input type="hidden" name="_token" id="token-csrf" value="{{ csrf_token() }}">
I don't know did I correct add parameter X-CSRF-TOKEN to my script. First I have error ajax 419 (unknown status) so I added X-CSRF-TOKEN and now I have error 500 (Internal Server Error). I also tried this: Laravel 5.5 ajax call 419 (unknown status)
Edit Post:
Is't my query method:
public function queryPass($pass) {
$user = Auth::user();
$current_password = $user->password;
if(Hash::check($pass, $current_password)) {
$updatePassword = App\User::where('id', $user->id)->update(['password' => bcrypt($pass)]);
echo "true";
} else {
echo "false";
die;
}
}
And route:
Route::get('account/query/{pass?}', 'UsersController#queryPass');
First problem was that he missed use Illuminate\Support\Facades\Hash; at the top of his controller, he used use Hash;, second thing when we resolved that was that, he was returning a boolean from inside a controller, when he is supposed to return an object which implements __toString method or a string, so he returned a correct response in this case a string "true" and "false"

How I can catch and save to file data from form sended by AJAX in ColdFusion

I have the followign JavaScript code:
function upload(blob) {
var xhr = new XMLHttpRequest();
var url = "test.cfm";
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("randomname",blob);
xhr.open("POST",url,true);
xhr.send(fd); }
How can I catch it on server side by ColdFusion and Save blob object to File?
Can someone please some code sample. Thx.
PS. I am pretty new in CF.
Since you are using formdata, you can access the form variable with ajax, just like you would with normal http requests.
#form.randomname#
#form['randomname']#
So you could save the content in a file with
<cfscript>
fileWrite( 'c:\myfile.txt', form.randomname );
</cfscript>

How to XMLHttpRequest in Wordpress?

I'm trying to send a variable to the server, using XMLHttpRequest.
I tested it on local on a non-Wordpress file and it works.
But on production, on my Wordpress file, the onreadystatechange AJAX status doesn't get to 200.
Is there anything I need to be aware when XMLHttpRequesting in Wordpress?
<script>
params = "parameter=" + value;
request.open("POST", "../myfile.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + request.statusText );
}
};
request.send( params );
// 'request' is 'XMLHttpRequest()' or 'ActiveXObject("Microsoft.XMLHTTP")'
// depending on browser
</script>
To create the code I followed the 2nd example of my O'Reilly book.
Any suggestion'll be much appreciated!
Thanks
Ultimately there is nothing wrong with this script.
I think it was due to the work frame I was using (Roots theme for Wordpress).
I change it for Handcrafted and I solved the problem.

Upload file with AJAX

I have the script:
#
var xmlhttp;
var params = "file=Not sure what is it";
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if (xmlhttp.status==200)
alert('Upload done');
else
alert('Error!!!');
}
}
xmlhttp.open("POST", "http://localhost/ajax2.php", true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
#
This script send a POST request to server, now I just wonder that how can I set params as a file content to upload?
You can't do this solely with JavaScript, for security reasons. Try SWFUpload, Uploadify, or similar. These are Flash-based solutions that you can interact with via JavaScript.
Look how this library does it

Resources