Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.
Related
I would like to use an autocompletion in my application. I'm trying to use the jquery UI completion but nothing happens. I made an ajax to get all columns with a specific variable written by the user. The query is working, I have my array with all my columns back from the server. With this query reponse, I tried to do the jquery autocompletion in the success ajax but as I said nothing is happening.
Do you have an idea?
function autoCompleteRegate(){
$("#code_regate").keyup(function() {
// AJAX de l'auto-complete
var source = '/gestion/gestDepot/ajaxautocompleteregate';
var codeRegate = $("#code_regate").val();
$.ajax({
type : "POST",
url : source,
async : false,
dataType : 'json',
data : {
'codeRegate' : codeRegate
},
success : function(response) {
var availableTags = response;
$("#code_regate").autocomplete({
source: availableTags
});
}
});
});
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
echo json_encode($response);
}
Network query - form
Exemple of nothing happening
The answer from the server
You have to directly pass the cd_regate array instead of a multidimensional array. One workaround is you could process the json output on the backend side :
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
$json = [];
foreach ($response as $key => $value) {
array_push($json, $value->cd_regate); // the output will be "[774970, 774690, 774700,... ]"
}
echo json_encode($json);
}
I would suggest the following for your JavaScript:
$("#code_regate").autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url : '/gestion/gestDepot/ajaxautocompleteregate',
async : false,
dataType : 'json',
data : {
'codeRegate' : request.term
},
success : function(data) {
response(data);
}
});
}
});
This uses a function as a Source. From the API:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
When 1 or more letters are entered into the text field, this will be passed to the function under request.term and you can POST that to your script via AJAX. When you get the result data, it must be in an Array or an Object with the right format.
Am working on a form whereby am passing values from the frontend to the backend using AJAX. From the frontend, all the data is being passed fine except that after performing some logic on the backend, I need to transport the data to the frontend. The data is contained in 2 separate variables whereby I have converted each to a JSON object for transmission.
When I dd() the data in the backend I get it in form of a string.
The problem is when I log response in the console tab (from the AJAX code), I don't get any response from the backend.. Please assist?
Controller file containing PHP code
public
function validatePlanEntries(Request $request)
{
//dd($request->all());
//Other PHP logic
//Convert data to JSON format
$form = json_encode($oldata);
//dd($form);
$planJson = json_encode($plans_benefits);
$plans = compact(['planJson' , 'form']);
//dd($plans);
return $plans;
}
AJAX code getting the response from the controller above
<script>
//Other Js code
form.parsley().validate();
//Returns true if Parsley validation has no errors
if (form.parsley().isValid()){
$.ajax({
type: "POST",
url: "getplans",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
console.log(response);
},
failure: function(errMsg) {
alert(errMsg);
}
});
};
</script>
I wouldn't convert them to 2 separate JSON encoded values an instead add them to 1. So instead of...
//Convert data to JSON format
$form = json_encode($oldata);
//dd($form);
$planJson = json_encode($plans_benefits);
$plans = compact(['planJson' , 'form']);
//dd($plans);
return $plans;
Something like, build an array with both pieces of data and json_encode() the result...
return json_encode([ "form" => $oldata, "plan" => $plans_benefits]);
You will need to update your Javascript to extract the relevant parts of the response.
Update:
I'm not a Laravel person, but it seems you can use...
return \Response::json([ "form" => $oldata, "plan" => $plans_benefits]);
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
I am using angular as frontend and php as backend here is the code of angular.
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'uid':uid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
here is the process.php
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
problem is $formData is empty in php. however $uid is showing value.
in form i have two entry email and password but i don't know how can i use that in php because formdata is empty.
I checked in firebug and found data is posting.
{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}:""
But nothing is coming response tab of firebug.
Assuming you call your function with something like ng-submit="processForm(formData)" then this is all you actually need
$scope.processForm = function(formData) {
$http.post('process.php', {
formData: formData, // note the key is "formData", not "data"
uid: uid // no idea where uid comes from
});
};
Where you have
$scope.processForm = function($scope.formData) {
isn't even valid JavaScript. You cannot use object dot notation in function argument names. That should have been throwing an error in your console.
You also appeared to be incorrectly setting your request content-type. You are sending JSON, not application/x-www-form-urlencoded formatted data. Angular's default POST content-type (application/json) is sufficient.
Try like this..
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json);
$formData= $req->formData;
$uid= $req->uid;
$password = $req->formData->password;
$cpassword = $req->formData->cpassword;
OR convert into array using json_decode() with second argument as true.
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json,true);//converts into array format
$formData= $req['formData'];
//print_r($formData);
echo $formData['password'];
Am passing data to yii2 using ajax request but i keep on getting a 500 error
This is the ajax request code:
<?php
$script = <<< JS
$('form#forward_pr').on('beforeSubmit', function(e){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
error: function(err){
console.log("server error");
}
});
return false;
} ) ;
JS;
$this->registerJS($script);
?>
When i do console.log(keys) this returns
[0, 1]
This is my controller code:
if (Yii::$app->request->post()) {
echo $post = json_encode($_POST['keys']);
if (isset($_POST['keylist'])) {
$keys = \yii\helpers\Json::decode($_POST['keylist']);
print_r($keys);
}else{
echo "1";
}
The above always executes the error part of post request, What could be wrong;
You are sending your JSON as encoded (post) data body, not key value pairs. So your approach is not working this way.
There are two options to fix this:
refactor your controller into a RESTful service
in your controller use the JSON body rather than POST parameters
While the first option is preferred in the long run, the second option is pretty simple as a quick fix.
First, make sure you configure your app to parse JSON body conten.
IN config.php add this to the components array:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
Then in your controller use this to get the JSON parameters:
$model->load(Yii::$app->getRequest()->getBodyParams());
I'm a newbie.. But I also want use checkboxcoloumns in gridview (Kartik version).
1st thing.
Instead of writing
var keys = $('#grid').yiiGridView('getSelectedRows');
I have to write
var keys = $('#w4').yiiGridView('getSelectedRows');
2nd thing.
In the controller you can process the keylist, but don't try to decode it, simple use it int this way:
$keys = $_POST['keylist'];
and it seems it works for me!
Sorry for my english..