I have an API that requires a string parameter. I want to take the query parameter to the controller and process there. I tried $ajax_data = Input::get('query'); but it didnt work. Searched the same question but cant find a decent answer. Current error is $ajax_data is empty.
My ajax request:
const sendAPIRequest = function (csrf, f) {
$.ajax({
async: false,
url: 'api/apitest',
method: 'get',
data:{
query:"select?facet=on&q=*:*&rows=1&json.facet={Categories:{type:terms,field:price,limit:3}}"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkid);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrf.trim());
},
success: function (data) {
f(data);
},
error: function(xhr) {
//Do Something to handle error
}
});
};
My Controller API part:
public function apitest(){
$ajax_data = Input::get('query');
$user_type = UserAuthorizationHelper::user_authorization();
if ($user_type == Authorities::EDIT_ORGANISATIONS) {}
$query = new GuzzleHttp\Client();
try {
$response = $query->request('GET',SolrController::$url.$ajax_data);
} catch (GuzzleHttp\Exception\GuzzleException $e) {}
$data = $response->getBody()->getContents();
return response()->json(json_decode($data));
}
You are having a problem in this line:
$ajax_data = Input::get('query');
When you are making a request, Request object is sent with the data.
So, instead of Input replace it with Request's object, and you will get the desired output.
Something like this:
// Don't forget to import the Request's namespace
public function apitest(Request $request)
{
$ajax_data = $request->get('query');
// ... Rest of your code
}
Related
I am getting a 500 error code while fetching data from the database using Ajax in Laravel with the following function:
public function search(Request $request)
{
if ($request->ajax()) {
$query = $request->get('query');
$data = Constant_model::get_icons('fontawesomeicons', 'id', 'DESC', 20, $query);
}
return response($data->jsonSerialize(), Response::HTTP_OK);
}
get_icons function is:
public static function get_icons($table, $order_column, $order_type, $limit, $search = '')
{
$result = DB::table($table)
->select('*')
->orderBy($order_column, $order_type)
->where('icon_name', 'like', '%'.$search.'%')
->paginate($limit);
return $result;
}
I am trying to get the data using Ajax with the following Javascript:
$.ajax({
url: "/icons/search",
method: "GET",
data: {
search: query
},
dataType: 'json',
error: function (error) {
console.log(error);
},
success: function(response) {
alert(response);
}
});
Class App\Http\Controllers\Response. You forgot to use Response in above your code.
Put that in:
use Response;
Or just use a helper, if you don't want to import it:
return response()->json(...);
Now in your case, you must return it, like this:
return response()->json($data->jsonSerialize(), Response::HTTP_OK);
I'm making a phone app using PhoneGap with PHP on the server side. the Login function has been working fine, but AJAX returns an error [object Object] while PHP returns the correct value's in JSON.
it's for making a phone app for an existing website and using its database.
the data my PHP prints is correct yet I receive an error response from ajax.
Alert(response)
Gives an [object Object] return value on error
whenever I try
alert(response.val)
I strangely get undefined, but in the network, I can see the printed data is correct in JSON.
{{"user_id":"390","response":"Success"}}
but when I look in the console on my browser I see an unexpected error.
Unexpected parameter ':'
my ajax function is as follows
$(document).ready(function () {
$("#btnLogin").click(function () {
var gebr = $("#login_username").val().trim();
var pass = $("#login_password").val().trim();
var dataString = "username=" + gebr + "&password=" + pass + "&login=";
var msg = "";
$("#message").html("Authenticating...");
if (gebr != "" && pass != "") {
$.ajax({
type: "POST",
data: dataString,
dataType: "json",
//contentType: "application/javascript",
crossDomain: true,
url: "http://url/page/app/index.php?&jsoncallback=?",
headers: "application/json",
success: function (response) {
var user_id = response.user_id;
var success = response.response;
localStorage.setItem("user_id", user_id);
window.location = "home.html";
alert("login successfull");
},
error: function (response) {
$("#message").html("error..");
alert(response);
}
});
} else {
msg = "Please fill all fields!";
$("#message").html(msg);
}
return false;
});
PHP
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];
//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) {
$msg = "user not found!";
print json_encode($msg);
} else {
if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
//responds with this data
$user_id = $user['user_id'];
$response[] = array(
'user_id' => $user_id,
'response' => 'Success'
);
print json_encode($response);
} else {
$msg = "user is incorrect";
print json_encode($msg);
}
}
}
I have been wanting to get a successful response and saving the user_id in local storage so it can be used on a different page.
Edit:
after using console.log on the response i got an odd object.
abort: function abort()
always: function always()
catch: function catch()
done: function add()
fail: function add()
getAllResponseHeaders: function getAllResponseHeaders()
getResponseHeader: function getResponseHeader()
overrideMimeType: function overrideMimeType()
pipe: function pipe()
progress: function add()
promise: function promise()
readyState: 4
setRequestHeader: function setRequestHeader()
state: function state()
status: 200
statusCode: function statusCode()
statusText: "load"
then: function then()
<prototype>: {…
which is strange because none of these functions are made and the only thing which i can recognize is the statuscode.
You need to correct your JSON. {{"user_id":"390","response":"Success"}} is not valid JSON. It needs to be {"user_id":"390","response":"Success"}.
You're getting a strange object in your console.log because your response in the error: function (response)... is actually the jqXHR jQuery object and will not return your response directly in its arguments. Stick with success: function(response)... and output whatever your server sends back.
I have a project in Cakephp 3.6 in which 3 actions in MessageController are called by Ajax. I have a problem, however, when I send a request to one of the action, XHR returns to me this:
{
"message": "CSRF token mismatch.",
"url": "\/messages\/changepriority\/8",
"code": 403,
"file": "D:\\xampp\\htdocs\\myapp\\vendor\\cakephp\\cakephp\\src\\Http\\Middleware\\CsrfProtectionMiddleware.php",
"line": 195
}
This is one of the action what I try to call from Ajax:
public function changepriority($id=null)
{
$this->autoRender = false;
$message = $this->Messages->get($id);
$message->priority = ($message->priority === false) ? true : false;
if ($this->Messages->save($message)) {
echo json_encode($message);
}
}
And this is my ajax:
$(".email-star").click(function(){
var idmessage = this.id;
$.ajax({
headers : {
'X-CSRF-Token': $('[name="_csrfToken"]').val()
},
dataType: "json",
type: "POST",
evalScripts: true,
async:true,
url: '<?php echo Router::url(array('controller'=>'Messages','action'=>'changepriority'));?>' +'/'+idmessage,
success: function(data){
if(data['priority'] === false) {
$("#imp_" + idmessage).removeClass("fas").removeClass('full-star').addClass( "far" );
}
else {
$("#imp_" + idmessage).removeClass("far").addClass( "fas" ).addClass("full-star");
}
}
});
});
I have read the documentation about Cross Site Request Forgery, and I tried to turn off the Csrf for these action first with:
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
and then with:
public function beforeFilter(Event $event)
{
$this->Security->setConfig('unlockedActions', ['index', 'changepriority']);
}
But nothing. The Xhr return always the CSRF token mismatch.
What can I do ?
Edit:
I change the action in this way:
public function changepriority($id=null)
{
$this->autoRender = false;
$message = $this->Messages->get($id);
$message->priority = ($message->priority === false) ? true : false;
if ($this->Messages->save($message)) {
$content = json_encode($message);
$this->response->getBody()->write($content);
$this->response = $this->response->withType('json');
return $this->response;
}
}
In that way the action works. Can it be like that?
First check your $('[name="_csrfToken"]').val() output.
If you didn't get any output, need to check csrfToken hidden field is exist or not. Just right click in your page and click View Page Source
If not exist, you don't follow proper way when you create Form. Basically, when forms are created with the Cake\View\Helper\FormHelper, a hidden field is added containing the CSRF token.
If everything is correct, add the following line inside your ajax call after header
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
Ps. Disabling the CSRF is not recommended by cakePHP and most of the developer aware of this. Hope this help.
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', <?= json_encode($this->request->getAttribute('csrfToken')) ?>);
},
My Controller
public function electricityBillAddToCart(){
$accountNumber = Input::get( 'accountNumber' );
$amount = Input::get( 'amount' );
$userId = Auth::user()->id;
$type = TransactionTypes::ELECTRICITY;
if(is_numeric($accountNumber)) {
CartHelper::addToCart($userId, $accountNumber, $amount, $type);
return Response::json("Okay");
}
return Response::json("Error");
}
The above function is called using the following ajax request
$.ajax({
url: "/addToCart/electricityBill",
type: "POST",
dataType:"json",
data: {'accountNumber': reloadto, 'amount': amount},
success: function (re) {
console.log("Success");
},
error: function(re) {
console.log("Error");
}
The response to the front end would be []"okay", and "Error" would be printed in the console. If the static function that I call before sending the response is commented out it would work fine (it would return "okay", and print "Success"). The code that I comment is
CartHelper::addToCart($userId, $accountNumber, $amount, $type);
Anyone knows why this is?
I found the problem. There was an echo in the CartHelper class. Once that was deleted, it worked fine
Using this git-hub library:
http://github.com/philsturgeon/codeigniter-restserver
How do I use the PUT feature to save its data?
example: example.com/put/some-data/some-data/...
you can use it like this: but take in count that PUT is less commonly used and not supported by most browsers
function somename_put()
{
$data = array('somedata: '. $this->put('some-data'));
$this->response($data);
}
You can do it with an ajax request e.g.
(assumes use of jQuery)
$.ajax({
url: '/index.php/my_controller/somedata',
type: 'PUT',
success: function(result) {
console.log(result);
}
});
According this (link: https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L915), $this->put only return if passed a param to it (so that works: $username = $this->put('username')). But in REST_Controller, $this->_put_args is protected so, you will extend this class and can access it like: $params = $this->_put_args.
In short (this is just an example, you may improve it as you need);
<?php
// route: /api/users/123
class Users extends REST_Controller
{
...
// update a user's data
public function user_put() {
$params = $this->_put_args;
// you need sanitize input here, "db" is a pseudo
$username = $db->escape($params['username']);
$userpass = $db->escape($params['userpass']);
$db->update(array(
'username' => $username,
'userpass' => $userpass
), (int) $params['id']);
if (!$db->error) {
// suppose right code should be 201 for PUT
$this->response('Created', 201);
} else {
$this->response('Internal Server Error', 500);
}
}
}
?>
<script>
// Some ajax library
Ajax("/api/users/123", {
method: "PUT",
data: {username:"John", userpass:"new pass"},
onSuccess: function(){ console.log("Success!"); }
...
});
</script>