i have an ajax which I don't know if it is correct. I want to get the value from the controller and pass it to ajax.
ajax:
$.ajax({
type: "GET",
url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),
success: function(response) {
if (response != "Error")
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
event.preventDefault();
and in the controller:
public function swoosh_delete_child()
{
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response = $this->emp->delete_children($id);
}
model
public function delete_chilren($id){
.......//codes here.. etc. etc.
if success //
return "success";
else
return "Error";
}
i just want to pass/get the value of $reponse and pass it to the ajax and check if the value is error or not..
Just echo in the controller:
$response = $this->emp->delete_children($id);
And alert the response:
alert(response); //output: success / Error
in your controller:
you should have something like this
public function swoosh_delete_child(){
$P1 = $this->session->userdata('id');
parse_str($_SERVER['QUERY_STRING'],$_GET);
$id = $_GET['h'];
$response['status'] = $this->emp->delete_children($id);
echo json_encode($response);
}
then in your ajax, to access the response
$.ajax({
type: 'POST',
url: url: swoosh(id, path+'swoosh_employee/swoosh_delete_child', 'childdv'),,
dataType: 'json',
success: function(response){
if (response.status)
{
$('#success-delete').modal('show');
}
else
{
alert("Error");
}
}
});
Related
I am passing the hotel id as a parameter to my function to get all the rooms in that hotel. But it is returning an error. I want to return in a JSON format the id of the hotel.
this is my javascript function
function showRooms($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
var token = $('meta[name="_token"]').attr('content');
$.ajax({
url: '/rooms'+id,
type: "Get",
dataType: 'JSON',
data: "{id:" + JSON.stringify(id) + ", _token:" + token + "}",
success:function(data)
{
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
this is my controller
public function rooms(id $id){
$response = array();
$response =$id;
return response()->json($response);
}
this is my route
Route::get('/rooms', 'HomeController#rooms')->name('/rooms');
your URL url: '/rooms'+id, and Route::get('/rooms', 'HomeController#rooms')->name('/rooms'); not valid, please see my code i am edited your code
//Change your js function
function showRooms(hotel_plan_id) {
var id = hotel_plan_id;
if (id !== "") {
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('rooms', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert('xdata:' + data);
//$('#'+dependent).html(result);
},
error: function (result) {
alert("Error occur in the rooms()");
}
});
}
}
//Change your function
public function rooms($id){
return response()->json(['id'=>$id]);
}
//Change your route
Route::get('rooms/{id}', 'HomeController#rooms')->name('rooms');
***Use Route like this in routes.php file:**
Route::get('/rooms', 'HomeController#rooms');
public function rooms(Request $request){
$id = $request->get('id');
$response['id'] = $id;
**Or whatever you want to do and append in response varaible and return**
return response($response)->header('Content-Type', 'application/json');
}
In the below example my Ajax response is coming as 'success'[ type is string], and I am comparing the 'success' [type is string]. Then why does the control not enter into the if condition?
$.ajax({
url: "controller.php",
method: "POST",
data: { loginData : $("#loginForm").serialize()},
dataType: "text",
success: function (response) {
if(response=='success') // response coming as is 'success'
{
window.open('www.google.com');
}
},
error: function (request, status, error) {
/* error handling code*/
}
});
You are passing data as plain text. I recommend passing data as JSON because it's easier to catch the response from the server.
Also, you are using a variable that will contain more variables (the form inputs) in data: { loginData : $("#loginForm").serialize()}. I recommend you using .serializeArray() to send data as JSON variables that you can catch in the server script.
So:
$.ajax({
url: "controller.php",
method: "POST",
data: $("#loginForm").serializeArray(),
dataType: "json",
success: function (response) {
if(response["success"]) {
window.open('www.google.com');
}
},
error: function (request, status, error) {
// error handling code
}
});
And in controller.php:
<?php
if(isset($_POST['input'])) { // use your input's name instead
$response['success'] = true;
} else {
$response['success'] = false;
}
header('Content-Type: application/javascript');
echo json_encode($response);
?>
And also, with this last code snippet you can pass more than "success" (simply because you're using an array). Eg:
<?php
if(isset($_POST['input'])) { // use your input's name instead
$response['success'] = true;
$response['open'] = 'www.google.com';
} else {
$response['success'] = false;
}
header('Content-Type: application/javascript');
echo json_encode($response);
?>
Right, i only want a very simple ajax request to get this working. im new with yii 2.0 framework you see.
in my view index.php:
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { test: test },
success: function(data) {
alert(data);
}
});
}
Now when i call this i assume that it should go to my CasesController to an action called actionAjax.
public function actionAjax()
{
if(isset($_POST['test'])){
$test = "Ajax Worked!";
}else{
$test = "Ajax failed";
}
return $test;
}
EDIT::
Ok great, so this works up to here. I get back the alert that pops up with the new value for $test. However i want to be able to access this value in php as ultimately i will be accessing data from a database and ill be wanting to query and do various other things.
So how do i now use this variable in php instead of just the pop up alert()?
Here is how you can access the post data in controller:
public function actionAjax()
{
if(isset(Yii::$app->request->post('test'))){
$test = "Ajax Worked!";
// do your query stuff here
}else{
$test = "Ajax failed";
// do your query stuff here
}
// return Json
return \yii\helpers\Json::encode($test);
}
//Controller file code
public function actionAjax()
{
$data = Yii::$app->request->post('test');
if (isset($data)) {
$test = "Ajax Worked!";
} else {
$test = "Ajax failed";
}
return \yii\helpers\Json::encode($test);
}
//_form.php code
<script>
$(document).ready(function () {
$("#mausers-user_email").focusout(function () {
sendFirstCategory();
});
});
function sendFirstCategory() {
var test = "this is an ajax test";
$.ajax({
type: "POST",
url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax') ; ?>",
data: {test: test},
success: function (test) {
alert(test);
},
error: function (exception) {
alert(exception);
}
})
;
}
</script>
You can include js this way in your view file:
$script = <<< JS
$('#el').on('click', function(e) {
sendFirstCategory();
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END
function sendFirstCategory(){
var test = "this is an ajax test";
$.ajax({
url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
data: {test: test},
success: function(data) {
alert(data)
}
});
}
public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.
I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;