I am hosting an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). How the root directory looks is this:
index.html, src/index.js, src/send_payment.php
I am trying to return a simple string at the moment from the php file using getJSON with jsonp (for security). Here is non-working code:
index.js
var json_obj = {
"data_value": 5489798123489725,
"payment_amount": 10.50,
}
var json_str = JSON.stringify(json_obj);
$.getJSON("https://localhost:443/src/send_payment.php?callback=?", "json_str=" + json_str, function (data) {
try {
console.log("SUCCESS >> " + JSON.stringify(data));
}
catch (e) {
console.log("ERROR >> " + e.toString());
}
});
send_payment.php
<?php
try {
// 1. get data
$json_str = $_GET["json_str"];
// 2. parse the json string
$json_obj = json_decode($json_str);
// 3. get the parameters
$data_value = $json_obj->{"data_value"};
$payment_amount = $json_obj->{"payment_amount"};
}
catch (Exception $e) {
trigger_error("ERROR >> exception = " + $e->getMessage(), E_USER_ERROR);
}
return "test successful";
?>
I'm not sure if the code is right or missing anything, but the issue is that I get 404 (Page not found) from getJSON. Is the URL wrong? I am accessing IIS locally, thus the localhost in the URL. I get error 405 (Method not allowed) when using AJAX POST instead with the same URL. Thank you.
I would recommend you to go for $.ajax and POST method like below:
$.ajax({
type: 'POST',
url: 'src/send_payment.php',
async: false,
data: {'data_value': 5489798123489725,'payment_amount': 10.5 },
success: function (response) {
//do whatever you want here }
});
Related
I am developing a responsive user interface in CakePHP 4.x which occasionally uses Ajax requests.
My Ajax requests are performing just fine but I am having a lot of trouble incorporating a CSV-file in the request so my controller can handle the data. What I want to accomplish is that that I can choose a CSV-file, press submit and that the Ajax-request sends the file to the controller and uses the independent rows to update the database.
My code:
Javscript:
function importProducts() {
/* Getting form data */
let form = document.getElementById('importProductsForm');
let formData = new FormData();
let file = $(form.products_file).prop('files')[0];
formData.append("csv_file", file);
/* Moving product stock */
ajaxRequest('Products', 'importProducts', formData, processImportProducts);
}
function ajaxRequest(controller, action, data = null, callback = null) {
$.ajax({
url : "<?=$this->Url->build(['controller' => '']);?>" + "/" + controller + "/" + action,
type : 'POST',
data : {
'data': data
},
dataType :'json',
/*processData: false,*/
/*contentType: false,*/
success : function(dataArray) {
let response = dataArray.response;
if (typeof response.data !== 'undefined') {
data = response.data;
if (callback != null) {
callback(data);
}
} else if (response.success == 0) {
data = null;
giveError(response.errorTemplate);
} else {
data = null;
if (callback != null) {
callback(data);
}
}
},
error : function(request,error)
{
console.error(error);
}
});
}
At the moment the controller function does not do anything special but receiving and setting the data:
public function importProducts() {
$this->RequestHandler->renderAs($this, 'json');
$response = [];
if($this->request->is('post')) {
$data = $this->request->getData();
$response['test'] = $data;
} else {
$response['success'] = 0;
}
$this->set(compact('response'));
$this->viewBuilder()->setOption('serialize', true);
$this->RequestHandler->renderAs($this, 'json');
}
After some research I discovered I could use the FormData object to send the file. The error I then received was 'illegal invocation'. After some more research I discovered this had to with automatic string parsing by Ajax. According to some other StackOverflow posts I could resolve this by setting the processdata and contenttype properties to false. This fixed the problem but resulted in an Ajax request which always would be empty (that does not contain any data). I tested this without the CSV-file with a regular data object that contains a variable with a string but also resulted in a empty request (no data send to controller).
So my problem is that without the processdata property as false I get the 'illegal invocation' error, otherwise with processdata as false I literary do not receive any data in my controller. I am looking for solution to resolve this problem so I can send my CSV-file or at least the data within the file to my controller.
Other solutions than using the FormData are also welcome, for example I tried to read the CSV-file in Javascript and turn this into another object (with the jquery csv api) to send to the controller, sadly without success until now.
Sorry but I spent a half a day practicing first with gadgets.io.makeRequest, and can not understand why the request response contains an error. The code is Javascript working as OpenSocial gadget:
requestURI = "https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg";
makeGETRequest(requestURI);
...
function makeGETRequest(url) {
try {
var params = {};
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
params[gadgets.io.RequestParameters.HEADERS] = {
"Accept" : "application/rdf+xml",
"OSLC-Core-Version": "2.0"
}
gadgets.io.makeRequest(url, function(obj) {
console.log("===== HTTP REQUEST START =====");
console.log("Method : GET");
console.log("URL : " + url);
console.log("Response : " + obj.text);
console.log("====== HTTP REQUEST END ======");
}, params);
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
When I do the same request with REST Client in Firefox, everything works properly. But if I do that with the code above, then I get an error in the log (abbreviated):
===== HTTP REQUEST START =====
common.js:311 Method : GET
common.js:312 URL : https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.…roject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg
common.js:313 Response : {"errorMessage":"Illegal character in query at index 178: https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg","errorClass":"java.lang.IllegalArgumentException","errorTrace":["java.net.URI.create(URI.java:871)","org.apache.http.client.methods.HttpGet.<init>
...
common.js:314 ====== HTTP REQUEST END ======
I tried to replace greater and less symbols by their hex values but there's no result. And there's no ideas currently.
May be somebody could make a fresh sight to the code and define the problem on the fly. Help me please, I'm at a dead end.
Thank you very much in advance for any advice!
The error in your Response indicates the Java system on the server side can't create a valid URI from your query. Therefor it throws back an error
My best guess would be the dot just before query=true in oslc.query=true. And therefor all following uses of oslcDOT .
From RFC 1738 specification:
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
I discovered that gadgets.io.makeRequest isn't very stable as I would like to expect. May be I do some wrong but sometimes this function completes without any feedback and without starting the response function in the parameters. I changed to next code:
function makeGETRequest(urlValue) {
try {
$.ajax({
url: urlValue,
type: 'GET',
dataType: 'text',
headers: {
'Accept': 'application/rdf+xml',
'OSLC-Core-Version': '2.0'
},
success: function (result) {
var data = result;
},
error: function (error) {
console.log("Can not perform HTTP request because of error: " + error.message);
}
});
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
And there's no problem!
My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here
I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .
I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?
I am having problems with a JSON AJAX callback when the returned JSON object contains no data. My code is as follows:
$.ajax({
type: "POST",
url: "includes/get_menu_name.php",
headers: {"cache-control": "no-cache"},
data: data,
success: function(html) {
//alert(html);
var app_data = "";
if (html.MenuData != 0) {
$.each( $.parseJSON(html).MenuData, function() {
app_data += "<li data-short='"+this['dish_short']+"' data-desc='"+this['dish_desc']+"' data-dish_id='"+this['dish_id']+"'>"+this['dish_name']+"</li>";
});
$('.listbox').show();
$('.nameslist').html(app_data);
$('li').hover(function() {
$(this).addClass('hover2');
},function(){
$(this).removeClass('hover2');
});
if (html == "") {
$('.listbox').hide();
}
$('li').click(function() {
//alert($('li', this).data('short'));
$('.price').val("");
var main_name = $(this, 'li').text();
$('.main_name').val(main_name);
//$('.price').val($(this).find('.ajaxid').text());
if(main_name.length > 40) {
$('.short_name').val($(this).data('short'))
} else {
$('.short_name').val(main_name);
}
if($(this).data('desc')!="") {
$('.dish_desc').val($(this).data('desc'));
}
var dish_id=$(this).data('dish_id');
$('.main_name').data('dish_id', dish_id);
$('.listbox').hide();
});
}
}
});//end ajax
The error comes back as:
TypeError:$.parseJSON(...) is null
I have tried various methods to check if there is data within the callback but none seem to work. I am very new to using JSON and is wondering whether I should add a different call back via the php page if there is no data to return, however would like to find out if there is a way to do this via the javascript.
$.ajax with post will return HTML in string format you need something like this!
success:function(html)
{
if(html)
{
try
{
html = JSON.parse(html);
if(html.MenuData)
{
// do something interesting
}
else
{
// failed
}
}
catch(e)
{
// failed
}
}
else
{
// failed because response is empty
}
}
Here you can specify dataType to use as json
$.ajax({
type: 'POST',
url: ajaxURL,
data:data,
dataType: 'json',
success: function(data){
JSON.parse(data);
}
});
And in server side script you must have to encode data using json_encode function.
While fetching json via ajax, here are a few things to note (incase it catches your issue too)
1) Content-Type
Json parsing will work fluently when Content-type: application/json
A html fetch (meaning Content-Type: text/html or equivalent) needs manually parsing json as String.
2) Jquery version
This shouldn't be a problem since it has subsided since version: 1.5 (you might be using latest one, 1.9)
Here is a link to the json related bug: http://bugs.jquery.com/ticket/8108
For json intensive coding, people often use jquery-json (http://code.google.com/p/jquery-json/) which a wrapper over simple jquery. You may want to consider if fix isn't easy.
I hope it answers atleast partially. Thanks..