Submit a URL as data in cakePHP - cakephp

I am using cakePHP 1.26.
I got an Input Text box which contains a URL and I want to submit the URL and stored it in the Database using Jquery AJAX.
Here is the HTML part:
<input type="text" id="testing" value="https://stackoverflow.com/questions/ask">
This is the JQuery part:
var whatContent=$("#testing").val();
var curl="http://localhost:8080/test/grab/"+whatContent;
$.ajax({
type: "POST",
url: curl,
success: function(data) {
alert(data);}
});
This is the code for the Action in the Controller:
function grab($w=null){
if($w!=null){
return $w;
}
}
The code worked and I could see the Alert Message pop up, but there was something missing in the message. I mean I supposed to see the whole URL like this:
https://stackoverflow.com/questions/ask
But not, I just saw part of it instead:
http://stackoverflow.com
Later I altered the value in the Input Text box like this:
<input type="text" id="testing" value="https://stackoverflow.com/faq">
But again, the returned value was still
http://stackoverflow.com
cakePHP seemed to conside the URL as some parameters rather than a URL.
Please help

When you append the content to the end of your "curl" variable like you are, you are attempting to add it to be retrieved through a GET variable and will get a result in a request like http://localhost:8080/test/grab/http://stackoverflow.com/questions/ask. Clearly this is an invalid request. Your GET variable parsing is not going to be consistent and a dangerous way of passing data back to your controller (especially if users will be able to edit the appended value).
Instead, you should use the data attribute in jQuery to pass this information back in your POST request as described in the instructions here: http://api.jquery.com/jQuery.ajax/
On the Cake side, you'll be able to receive this value as $this->data['IDValueYouConfigured']. For example, if your AJAX request was like:
var whatContent=$("#testing").val();
var curl="http://localhost:8080/test/grab/";
$.ajax({
type: "POST",
url: curl,
data: "formValue="+whatContent,
success: function(data) {
alert(data);}
});
where formValue is the IDValueYouConfigured that I mentioned earlier.
More importantly, you seem to be misunderstanding proper use of the Cake framework and could be performing all of these functions MUCH more simply using things like the JsHelper, FormHelper, etc. I would recommend using the most RECENT version of Cake (1.3.3) and follow through the Blog tutorial at least once. This will lead to better questions which will be more likely to get helpful answers. Hope this helps.

Related

AngularJs $http get not working 1st time but does on subsequent invocations

All:
I have an Iframe tag on a simple HTML page and inside this Iframe tag is a HTML form - lets call it a widget. Its a form where the user can enter search criteria and click on a button to obtain the search results. I have decided to use Angularjs to make the necessary DB calls to a REST service that returns the search results back to the widget for display.
In testing this I enter a value in a textbox on the widget, that value being a value that I know exists in a particular table I'm testing against.
Here is my $http get call:
$http
.get('http://localhost/XXXXService/folder/getfolders/' +
$scope.formData.srchterm **==>** mapped to search textbox
).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
//$scope.formData = response;
//$scope.nrdFolderDataArray = response;
console.log('Success retrieving data.');
console.log(response.length);
console.log('response:');
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('Error occurred retrieving data.');
console.log(response.status);
console.log('returned data count:');
console.log(response.size);
console.log('response:');
console.log(response);
});
This call is inside a function called "submitForm" that is mapped to the widget with a "ng-submit="submitForm()" attribute on the submit button. And yes there are several log statements so I can try and figure out what is going on here. And what is happening is this: after entering a value in the textbox, THE FIRST TIME the search button is clicked the .get command does not work. I does not make the call to the REST service. I know this because I wrote the REST service and made sure I put in plenty of log statements while doing so and there are no log statements in the log file from the REST service. Instead the errorCallback block runs and I see all those log statements in the console. The "response" (object?) after THE FIRST call looks like this:
Object {data: null, status: 0, config: Object, statusText: ""} Method = GET Status = (canceled) type xhr
Further, in FF there is no response data to view in the Net tab of Firebug upon THE FIRST call, but there is response data to view in all subsequent calls.
So, interestingly enough each subsequent invocation of that $http.get call works! I see log statements in the log file from the REST service method and the successCallback block runs and I can see my data via those console.log messages.
Also, if I were to change the search value in the text box, which would then be THE FIRST TIME we would be searching for data for that new key, once again, the call does not work, but does work on subsequent clicks on the "search" button for that new key value.
I really am not sure if I have a CORS issue here since, other than THE FIRST calls each subsequent $http.get call works like a champ. Its just that very first call or first call after the search key has changed that the $http.get does not want to work.
I have tried setting headers in the .get call and I have tried using
#CrossOrigin(origins = "http://localhost/7001") as per
https://spring.io/guides/gs/rest-service-cors/ but I continue to have this issue on the first time invoking this .get call.
I've been dealing with this issue for way too many hours now and would sure appreciate some input as to why this is happening.
I'm sorry for being verbose here. I wanted to explain my issue thoroughly.
Please help.
Thank you
-g

AngularJS $http.Post -> open the urllink + $http.get getting it

im still new with Angular and am trying to grasp the concept.
Currently I cant post code, but this is hopefully not a problem.
I have used https://docs.angularjs.org/api/ng/service/$http ... especially $http.post in order to Post some data I clicked in the current window
The following Code didnt work due to the error "$http function is not defined", even though $http was already declared... in the correct order I might add (I found other ppl who had issues with that due to the fact that they switched the parameters $scope, $http)
Thats my first Question is there a simple reason? I can add code tomorrow if necessary.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Second Question: Well, but $http.post(..) with parameter url to the second site worked fine.. and in order to use the data i most likely need to use $http.get() at the second site... which I understand.
But how do I need to configure the $http.post that I actually open the url in my browser?
Well I hope you can help me ... sry that I currently can't give you my codeexamples, but I hope it's enough :)

angular form submit get action append key value pairs

My goal was to have off a form submit for a get to be performed and as part of the uri, key value pairs appended like the following:
// GET /pets/42;q=11;r=22
Reading http://www.w3schools.com/tags/att_form_method.asp
description of form with setting form method to "get" I would have thought this was possible. In the world of angular, it seems like the expected behavior for a submit of a form results in post method. The controller can be written to generate any http verb but has the $http.get doesn't do what plain form get method would automatically and to generate a url like above, the controller would have to build the uri itself.
My apprehension of always using post off a form submit was the form in this case was part of a query/search action and not a data creation exercise. Maybe that's not the proper way to use form but has angular done away with automatically appended values from controls in key value pairs for a form with the $http.get service?
Of course you can do GET with query params in url.
The easiest way is to pass an object representing the key/value pairs to the params property of the $http config object.
var params = {q: 11, r:22};
$.get('/path/to/server/', {params: params}).then(....
Alternatively you can also create your own url string when you only have small number of params.
For further details read through the Usage section of $http docs

Play 2.3/Angular JS $resource/routing issue

So I'm trying to AJAX a single solr doc from my results list to a "doc view" view. I'm trying to use AngularJS to AJAX to my view render method and display the doc that way, but I can't seem to get the angular to work and I'm not sure I'm doing things correctly on the Play side either. Would you at least be willing to tell me if what I'm trying to do will work? The Angular error comes from the docText.text(); call. Here is my code:
Angular controller code:
var docText = $resource("http://localhost:9000/views/full-doc-text.html", {
text: {method: 'PUT'}
});
$scope.handleViewText = function(value) {
docText.text({doc: value});
}
Java code:
public static Result viewText() {
JsonNode json = request().body().asJson();
//do stuff here
return ok(viewtext.render(json));
}
route:
GET /views/full-doc-text.html controllers.Application.viewText()
I see three problems with the code above;
1.The definition of docText resource is not correct. if your read the angularjs manual here you'll see that $resource has 4 parameters. First one is resource url, second is parameter defaults, third one is custom actions and forth one is resource options where last three of them are optional. In your code you pass custom actions as the second parameter, which should be the third. And since you don't have any parameters in your resource url second parameter must be null. So first correction is:
var docText = $resource("http://localhost:9000/views/full-doc-text.html", null, {
text: {method: 'PUT'}
});
2.You define your text action's HTTP method as PUT however in your routes file you are handling GET requests for your desired action. You should change your route definition as:
PUT /views/full-doc-text.html controllers.Application.viewText()
3.PUT method is usually used for update operations when implementing a RESTFULL service. In your case you don't seem to be updating anything. So I suggest to use POST method just for convention.

Origin https://site.com is not allowed by Access-Control-Allow-Origin. using JSON

This is the first time that I encountered such problem, I have this code which came from the answers from this site and trying to experiment what the output is gonna be.
$.getJSON('https://api.twitter.com/1.1/friendships/lookup.json?screen_name=episod,twitterapi', function(data) {
console.log(data);
});
So when I run it, it shows like this, the "Access-Control-Allow-Origin". How can I fix this problem? Like allowing to get data from other location.
Any solution for this stuff? I'm using drupal 7, I might as well say it because it might be relevant to my problem though.
I saw this questions but, never helped and some of it seems vauge.
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
How to get the json data from this link
https://drupal.org/node/1937756
https://drupal.org/project/services_accept_origin
Any help would be appreciated. :)
The Twitter API does not support CORS requests, you have to use JSONP instead. You can trigger a JSONP request by adding the callback query parameter. Here is an example:
$.ajax({
url: "https://api.twitter.com/1.1/friendships/lookup.json?screen_name=episod,twitterapi",
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
Twitter's documentation for the callback parameter can be found here: https://dev.twitter.com/docs/things-every-developer-should-know

Resources