PHP curl form with no action and js events - javascript

I'm trying to use curl to post some data and retrieve it from a website that isn't mine, the websites form doesn't seem to have a form action and the page doesn't reload when you submit the data and there also seems to be some js behind the click of the button.
$url = "http://emonitoring.poczta-polska.pl/#";
$parm = "numer=RR123456789PL";
and here is the curl:
array(
CURLOPT_URL => $url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $parm,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE
);
I execute and init the curl as expected, just showing the important parts. Here is also the live http headers output:
POST /wssClient.php HTTP/1.1
Host: emonitoring.poczta-polska.pl
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Content-Type: application/x-www-form-urlencoded
Origin: http://kody.poczta-polska.pl
Referer: http://kody.poczta-polska.pl/
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Length: 1215
Content-Type: text/html; charset=UTF-8
Date: Mon, 30 Jun 2014 03:31:59 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: Apache
X-Cnection: close
At the moment it just shows the page and it doesn't look like that form was submitted, I've also tried putting the url as: "http://emonitoring.poczta-polska.pl/wssClient.php" and just get told to enter the number.

In such cases you go to chrome, hit F12, go to network, submit the form and see what is sent to the server. I see this posted
s:fggsbnqu033gqiipemr50fer56
n:RR123456789PL
l:
If you view source you see
if (jQuery('#numer').val().length == 19) {
var numer = dodajck(jQuery('#numer').val())
} else var numer = jQuery('#numer').val();
jQuery.ajax({
type: 'post',
cache: true,
dataType: 'html',
data: ({
s: 'fggsbnqu033gqiipemr50fer56',
n: numer,
l: ''
}),
url: 'wssClient.php',
The s:.... could mean you need to have a session on their server to be able to call the wssClient - if so, you will need to CURL with sessions
If you can call their server without a session or you have a session before you call you can curl using the parm is n= and not numer= and you need to have calculated the checksum using their function which can easily be translated to PHP
function dodajck(numer) {
// dodatkowe sprawdzenia i określenie wag oraz części numeru, która
// ma zostać zważona
//String wagi;
//String doWazenia;
var wagi = "3131313131313131313";
var doWazenia = String(numer);
// wyliczenie sumy iloczynów waga * cyfra
var suma = 0;
for (var i = 0; i < 19; i++)
suma = suma + Number(doWazenia.substring(i, i + 1)) * Number(wagi.substring(i, i + 1));
// ostateczne sprawdzenia
// przykład numeru 20-cyfrowego
// 00
// 1 - rodzaj?
// 590 -- kraj 590 = PL
// 0773 -- firma 0773 = PP
// 3 -- rodzaj przesyłki
// 12345678 - numer przesyłki
// 9 - CK
// ważone są numery od 1 do 19
var ck = 10 - suma % 10;
if (ck == 10) ck = 0;
return String(numer) + String(ck);
}

The form is submitted via AJAX. To see the exact HTTP request simply fire up the developer tools in Chrome or Firefox (F12). Navigate to the 'Network' tab, and hit the submission button on their website. You should see a request being fired off. If you open it up, you will be able to see everything you need to make the request yourself - URL, Parameters and their format, HTTP header values, etc. - and the response you're supposed to get.
Hope this helps!

Related

Unable to POST video file input using JS FormData object

I actually did a lot of research and tried different ways to upload a video file using JQuery's $.ajax() and FormData. I am using an updated version of Chrome and Firefox and aware that uploading of file using $.ajax() is possible for jQuery 1.6 and up. Right now I'm using jQuery-3.3.1.js
For whatever reason, I still can't make it work. I am getting an empty data when I echo $_FILES['myFile']['name'];
view.php
<div class="modal_body">
<form class="container_UserInfo" id="modalForm_uploadVideo">
<label class="modal_label" id="modalLbl_browseVideo">
Select Video
<input type="file" name="myFile" class="modalbtn_browseFiles" id="modalBtn_choose_video_file" value="Select Video" accept="video/*"/><br>
</label>
</form>
</div>
<button class="btn_modalFooter" id="modalBtn_uploadVideo_upload" name="modalBtnName_uploadVideo_upload">
Upload
</button>
view.js
$('#modalBtn_uploadVideo_upload').on('click',function(event){
if(hasInputFileLoaded()){
uploadVideo();
}else{
alert("No file input.");
}
});
function uploadVideo() {
var formData = new FormData();
formData.append('file', $('#modalBtn_choose_video_file')[0].files[0]);
console.log($('#modalBtn_choose_video_file')[0].files[0]); // console displays the selected file info.
$.ajax({
url: 'controller/upload_video.php',
type: 'POST',
data: formData,
processData: false, // tells jQuery not to process the data
contentType: false, // tells jQuery not to set contentType
success: function (data) {
console.log(data);
alert(data);
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internal Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
}
});
}
upload_video.php
$myFile = $_FILES['myFile']['name'];
echo "myFile: " . $myFile;
echo "myFile: " . $myFile; displays:
myFile:
This line:
console.log($('#modalBtn_choose_video_file')[0].files[0]); // console displays the selected file info.
shows me the information of the file that was selected and I'm sure it's not empty.
I dont know what's missing. It's able to pick up and run the upload_video.php script but gets nothing in $_FILES[]
I'd like to reiterate that the <form> is contained within a modal div. I don't know if it has anything to do with the problem.
Please help. I'd appreciate any suggestion.
Thank you.
**** EDIT ******
This is what I'm getting in XHR->Headers->Request Payload of Google's Developer Tools.
Request Payload
------WebKitFormBoundarybqKoBuiQ9WumYuTo
Content-Disposition: form-data; name="file"; filename="How to Configure Nginx VirtualHost in Ubuntu.mp4"
Content-Type: video/mp4
And for Request Headers
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 20360818
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarybqKoBuiQ9WumYuTo
Cookie: PHPSESSID=q669bu6jqodkpqpvu2hructsm7
Host: localhost
Origin: http://localhost
Referer: http://localhost/cai/landingpage.php
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
X-Requested-With: XMLHttpRequest
I've added the enctype="multipart/form-data" method="post" as suggested and var_dump($_FILES); and var_dump($_POST) but keep getting
NULL or array(0){}
I also replaced myFile with file in $_FILES[][]
$myFile = $_FILES['file']['name'];
echo "myFile: " . $myFile;
but did nothing to fix my problem.
What other troubleshooting can I do?
******* end of edit *******
You're sending the file data in the file property, not myFile, so your PHP should be changed to this:
$myFile = $_FILES['file']['name']; // note 'file' here
echo "myFile: " . $myFile;

How to get the next load of data inside jQuery DataTable

I am displaying SharePoint data inside a jQuery DataTables. The total number of rows is like 2000, but I am displaying only 100 on the first load.
When the page is loaded the data is displayed correctly. So, I wanted to get the next load of data inside the datatable, but I couldn't figure it out how to do that.
I thought of using bServerSide and iDeferLoading but these are giving me errors like the json format is not correct.
Below is my current code that I am testing at the moment. Can anyone tell me how can I get the rest of the results? How can I implement pagination when the user reaches the end of 100 rows?
Why bServerSide and iDeferLoading do not work in my case?
I have the same issue using jQuery and REST while doing a postback to SharePoint.
$(document).ready(function () {
window.StartTime = new Date();
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
SP.SOD.executeFunc('sp.search.js', 'Microsoft.SharePoint.Client.Search.Query.KeywordQuery', function () {
var queryText = "ContentTypeId:0x010066FA3DE3E334C841B418C82CC475A227*";
var clientContext = new SP.ClientContext.get_current();
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);
keywordQuery.set_queryText(queryText);
keywordQuery.set_rowLimit(50);
keywordQuery.set_trimDuplicates(false);
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
var results = searchExecutor.executeQuery(keywordQuery);
clientContext.executeQueryAsync(onQuerySuccess, onQueryError);
function onQuerySuccess() {
var rows = results.m_value.ResultTables[0].ResultRows;
var totalRows = results.m_value.ResultTables[0].TotalRows;
$("#example").DataTable({
"bDestory":true,
"bProcessing":true,
//"bServerSide": true,
"iTotalRecords":totalRows,
"iTotalDisplayRecords":10,
"iDeferLoading": totalRows,
"aaData":rows,
"aoColumns":[
{"mData":"Title"},
{"mData":"Path"}
]
});
console.log("After added to table: " + ((new Date() - window.StartTime) / (60 * 60)) + " seconds");
}
function onQueryError(sender, args) {
alert("call failed. Error: " + args.get_message());
}
});
});
});
This is the header response when I click on NEXT or dropdownlist when using bServerSide and iDeferLoading (Apparantly the Content-Type is returned as text/html):
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
X-SharePointHealthScore: 0
X-AspNet-Version: 4.0.30319
SPRequestGuid: 6fc9299d-cba4-c06b-92ee-423504bab93b
request-id: 6fc9299d-cba4-c06b-92ee-423504bab93b
X-FRAME-OPTIONS: SAMEORIGIN
SPRequestDuration: 84
SPIisLatency: 1
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4569
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: Tue, 01 Sep 2015 19:37:35 GMT
Content-Length: 23942
How can I force it to return JSON formated data?
Option bServerSide doesn't work for you because the data in the response has to be structured in a certain way, see Server-side processing (for DataTables 1.9) or Server-side processing (for DataTables 1.10).
I would remove this line keywordQuery.set_rowLimit(50); if it limits number of results and let the DataTables do the filtering, sorting and pagination.
Also remove invalid or irrelevant options in your DataTables initialization codes, so it looks like:
var rows = results.m_value.ResultTables[0].ResultRows;
$("#example").DataTable({
"aaData":rows,
"aoColumns":[
{"mData":"Title"},
{"mData":"Path"}
]
});

jquery $.post doesnt sent post data

im trying to make a post request to the server but the jquery doesnt sent any post date.
i already tried to use: (suggestions i found on the web)
var postdata = {'username':username,'password':password,'src':'web'};
instead of
var postdata = 'username=' + username + '&pass=' + password + '&src=web';
this is my jquery code:
var username = $('#uForm_un').val();
var password = $('#uForm_pw').val();
var postdata = 'username=' + username + '&pass=' + password + '&src=web';
console.log(postdata);//output: username=administrator&pass=password&src=web
$.post(
"inc/api/do.login.ajax",
postdata,
function (data) {
console.log(data);//output: a vardump($_POST) wich is empty.
}
);
browser data:
Remote Address:62.***.**.**:80
Request URL:***********/inc/api/do.login.ajax/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Cookie:anonymous=-81523622186; windowtop=100; LanguageId=1; CurrencyId=1; space_history=%7B%221%22%3A%2220%22%7D; eventId=1; OrderId=201424754035; filter_starttime=6%3A00; filter_endtime=12%3A00; _ga=GA1.2.2031844175.1410181977; __atuvc=13%7C37; PHPSESSID=4x1xc4ca4238a0b923820dcc509a6f75849b; filter_display_mode=grid; filter_search=; filter_where=eindhoven; filter_startdate=01/09/2014; filter_enddate=05/09/2014; filter_order=itemdate; filter_dayparts=; filter_distance=100000; filter_categories=; list=%2C2797
Host:********.nl
Pragma:no-cache
Referer:***************/index.php?action=editvisit
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:156
Content-Type:text/html; charset=utf-8
Date:Thu, 11 Sep 2014 09:15:03 GMT
Keep-Alive:timeout=5, max=88
Server:Apache/2.2.22 (Debian)
Vary:Accept-Encoding
X-Powered-By:PHP/5.4.4-14+deb7u14
EDIT:
now i use this code, but with the same result...
$.post( "inc/api/do.login.ajax",{
username : ""+$('#uForm_un').val()+"",
pass : ""+$('#uForm_pw').val()+"",
src : "web"
}).done(function(data) {
console.log(data);
}, "json" );
Solution:
change this:
inc/api/do.login.ajax
to
inc/api/do.login.ajax/index.php
with a get request it works fine but with a post...
sorry for taking your time and thanks! every answer was usefull!

How to force browser to open "save as" dialog for binary response?

I'm developing Zimbra Zimlet.
I'm requesting JSP from Javascript (both belong to the same Zimlet)
var jspUrl = this.getResource("my.jsp");
var callback = new AjxCallback(this, this._rpcCallback, ["param1", "param2"]);
AjxRpc.invoke(null, jspUrl, null, callback, true);
_rpcCallback function
automator_HandlerObject.prototype._rpcCallback = function(p1, p2, response) {
if (response.success == true) {
appCtxt.getAppController().setStatusMsg(response.text);
} else {
console.log("response error");
}
}
I need to return some binary file in response to that request. Here is JSP code
<%# page import="java.io.FileInputStream" %>
<%# page import="java.io.BufferedInputStream" %>
<%# page import="java.io.File" %>
<%# page import="java.io.IOException" %>
<%
ServletOutputStream outStream=response.getOutputStream();
File myfile = new File("/tmp/attachment.zip");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=attachment.zip");
response.setContentLength( (int) myfile.length( ) );
FileInputStream input = new FileInputStream(myfile);
BufferedInputStream buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read( )) != -1)
outStream.write(readBytes);
outStream.flush();
outStream.close();
buf.close();
%>
("application/x-download"/"application/force-download" also were tested with FireFox and Chrome)
I expected "save file" browser dialog to be appeared.
I tried
document.write(response.text)
in _rpcCallback function and I can see appropriate response headers
HTTP/1.1 200 OK
Date: Fri, 03 May 2013 08:16:49 GMT
Expires: Thu, 01-Jan-1970 00:00:00 GMT
Content-Type: application/octet-stream
Content-Length: 20021
Set-Cookie: JSESSIONID=11ebfk145b34z;Path=/zimlet
Content-Disposition: attachment;filename=attachment.zip
as well as binary response body content, but nothing happened.
What code _rpcCallback function must contain in order to show "download file" dialog instead of printing the file as text?
Tested with Zimbra Desktop 7.2.2 GA
Thanks to Julian the solution has been found and it is too simple:
window.open(fileUrl);

jquery how to get the status message returned by a ajax call of type post?

javascript
$('#send').on('click', function() {
$.ajax({
'url': $('#url').val(),
'type': 'post',
'complete': function (jqXHR, textStatus) {
var msg = "Status: " + jqXHR.status + " (" + jqXHR.statusText + " - " + textStatus + ")<br />";
msg += jqXHR.getAllResponseHeaders().replace(/\n/g, "<br />");
$('#results').html(msg);
}
});
});
php
header("HTTP/1.0 200 Some message here");
flush();
exit();
Results
Status: 200 (OK - success)
Date: Wed, 07 Dec 2011 21:57:50 GMT
X-Powered-By: PHP/5.3.6
Transfer-Encoding: chunked
Connection: Keep-Alive
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
Content-Type: text/html
Keep-Alive: timeout=5, max=100
Question
How do I get the "Some message here" part of the header?
http
http protocol
6.1 Status-Line
The first line of a Response message is the Status-Line, consisting of
the protocol version followed by a numeric status code and its
associated textual phrase, with each element separated by SP
characters. No CR or LF is allowed except in the final CRLF sequence.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
Got it. It's jqXHR.statusText.
$.get("test.php").complete(function(jqXHR) {
console.log(jqXHR.statusText);
});
Just tried it out in Chrome with your exact PHP code.
Have you tried xhrobject.getResponseHeader() yet? jQuery docs say it's also available there. If you don't know the header's name, try getAllResponseHeaders().
Also, can you see that message in your browser's debugging console (network tab, connection headers)? If it's not there, it will hardly be available from js.

Categories

Resources