I am not able to make it work:
also it is always redirecting to `action/create' whereas i want to not to redirect to that action.
my code is like this in footer view:
<script>
jQuery(document).ready(function($) {
$("#quick-contact").on('submit',function(event) {
// $("#quick-contact").on('beforeSubmit',function(event) {
event.preventDefault(); // stopping submitting
console.log("step1");
var form = $(this);
var formData = form.serialize();
// var data = $(this).serializeArray();
var url = $(this).attr('/quick-contact/create');
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
dataType: 'json',
data: formData
})
.done(function(response) {
if (response.data.success == true) {
alert("Wow you commented");
}
})
.fail(function() {
console.log("error");
});
// return false;
});
});
</script>
<?php //pjax::begin(['enablePushState' => false]); ?>
<div id="contact-form">
<?php $form = ActiveForm::begin(['action'=>'/quick-contact/create','id'=>'quick-contact','method'=>'post']); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'message')->textarea(['rows' => 2]) ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<div id="quick-contact-form">
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>
// display error message
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif; ?>
</div></div>
<?php // pjax::end(); ?>
and in controller action like:
public function actionCreate()
{
$model = new QuickContact();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
var_dump($_POST);
if ($model->load(Yii::$app->requset->post()) && $model->save()) {
Yii::$app->session->setFlash('success','Thanks We will get in touch with you');
// $st = Yii::$app->getTable;
// $email_template = $st->email_template(1);
Yii::$app->mailer->compose()
->setTo('info#mywebsolutions.co.in')
->setFrom(['info#mywebsolutions.co.in'])
->setSubject('QuickContact')
->setHtmlBody('Request from - '.$model->name.'<br>'.'Email - '.$model->email. '<br>'.'Message - '.$model->message)
->send();
/* Yii::$app->mailer->compose('template', ['id' => 1, 'email_template' => $email_template, 'sender_name'=>$model->name,'message'=>$model->address])
->setTo($this->email)
->setFrom([$email => "vedic"])
->setSubject($this->subject)
//->setHtmlBody('Hi '.$this->name.'<br>'.'Welcome to Nexgen'.'<br>'.'We confirm of having received your Enquiry/feedback as below'.'<br>'.$this->body )
->send();
*/
}else{
Yii::$app->session->setFlash('error','There was an error in submission.');
}
//return $this->render('/site/index');
}
// return $this->renderPartial('/site/index');
}
updated jquery script code:
Now ajax request is going through, but the response I am getting is like:
name Unknown Property
message Getting unknown property: yii\web\Application::requset
code 0
type yii\base\UnknownPropertyException
file /var/www/clients/client2/web238/web/vendor/yiisoft/yii2/base/Component.php
just replace the
$("#quick-contact").submit(function(event) {
with
$("#quick-contact").on('beforeSubmit',function(event) {
Update
The reason you are getting the error is because you have several errors in your console regarding the 3rd party scripts, and until unless you remove them you wont be able to get it working, you need to fix the following
Another thing that is missing is the return false; statement in your beforeSubmit event you should add this line after the ajax call, to prevent form submission.
$("#quick-contact").on('beforeSubmit',function(event) {
//....your code for ajax call
return false;
});
Update 2
The reason for the error is the spelling for the requset which should be rather request you need to change the line
if ($model->load(Yii::$app->requset->post()) && $model->save()) {
to
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if you still into problems please add a separate question as this question addresses the ajax part only which is solved already.
Related
Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}
This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.
Thanks guys for looking into my question. I have this form that I use ajax to submit to the mysql database using laravel. I'm trying to pull the most recent entry which would be the user's submission. I am error free, however I'm getting the most recent before the user submitted form. I wrote the code in the IndexController. Maybe i should use Jquery/Java? Here is what I have:
Route:
Route::resource('/', 'IndexController');
IndexController:
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return view('index', compact('recent'));
}
Html:
<div class ="row">
<div class ="col-lg-12 contact">
<div id = "ctn-box" class = "row pad-med">
{!!Form::open(array('url' => 'contacts', 'class' => 'contacting')) !!}
<h1 class = "txtc">CONTACTO</h1>
<div class = "form-group col-xs-3">
{!!Form::label('name', 'Nombre:')!!}
{!!Form::text('name', null, ['class'=> 'form-control area'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('email', 'Email:')!!}
{!!Form::email('email', null, ['class'=> 'form-control area', 'placeholder' => 'example#gmail.com'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('phone', 'Número de Teléfono:')!!}
{!!Form::text('phone', null, ['class'=> 'form-control area', 'placeholder' => '657-084-052'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::submit('Contacto', ['class'=> 'btn btn-danger outline form-control contact', 'id' => 'fuck'])!!}
</div>
{!! Form::close() !!}
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias {{$recent->name}}!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
</div>
<div class = 'contact-info'>
<iframe class = "googimg" frameborder="0" scrolling="no" src="https://maps.google.com/maps?hl=en&q=Passatge hort dels velluters, 5&ie=UTF8&t=roadmap&z=15&iwloc=B&output=embed"><div><small>embedgooglemaps.com</small></div><div><small>multihoster premium</small></div></iframe>
<div class = "address txtc">
<h1 class = "contacts">Passatge Hort dels Velluters<br> 5, 08008 Barcelona</h1>
<h2 class = "contacts">657-084-052</h2>
</div>
</div>
</div>
</div>
Ajax:
//INDEX CONTACT SUBMISSION//
$('.contacting').on('submit', function(e) {
var base_url = 'http://rem-edu-es.eu1.frbit.net/';
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: base_url + "contacts",
data: data,
success: function (data) {
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}
});
});
Before suggesting anything, I should tell you that there could be a little issue with the site. I clicked the "Contact" button without filling the fields. Guess what? I got a response: "Muchas Gracias New Guy..." I guess the last person used "New Guy" as his name. Sounds insecure?!
Now, to my answer, I'll suggest you do it with jQuery, in the success callback of $.ajax(). Something like this:
IndexController
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return json_encode(compact('recent')); // Returning view(...) means the ajax call will receive HTML page content
}
HTML
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias <span id = "newGuy"></span>!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
jQuery
success: function (res) { // note that I'm changing "data" to "res". It is the result of the ajax call
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#newGuy').text(res.name);
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}
I've created a restful API using laravel controllers. I have a PhotosController which has a destroy($id) method for resource deletion. also I have a piece of javascript code that sends a DELETE request to my app. the result should be the deletion of the photo with $id id. but laravel doesn't route my request to destroy method. instead it sends an 401 Unauthorized error.
the thing is that I want to send DELETE request to my app via Ajax, but laravel doesn't let my request to be routed!
routes.php file :
Route::resource('photos', 'PhotosController');
destroy method :
public function destroy($id)
{
try{
unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
Session::forget('photo');
$msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
return Response::json(array('success' => $msg));
}catch (Exception $e){
App::abort(500, $e->getMessage());
}
}
my Ajax request :
$.ajax(
{
url: "/photos/" + name,
method : "DELETE", // Or POST : result is the same
data :{
_token : $("input[name=_token]").val(),
_method : 'DELETE'
},
success: function(data, textStatus, jqXHR ){
parent.replaceWith("");
toastr.success(data['success']);
$("#overlay").hide();
},
beforeSend : function(jqXHR, settings ){
$("#overlay").show();
},
error : function(jqXHR, textStatus, errorThrown ){
toastr.error(jqXHR.responseText);
$("#overlay").hide();
}
}
);
Thanks for your help.
I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.
VIEW WITH RESOURCE TO DELETE
<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
<i class="fa fa-trash fa-lg"></i>
</a>
JQUERY TO PROMPT CONFIRMATION MODAL
$('.delete-plan').on('click', function(e) {
e.preventDefault();
var data = {
'route': $(this).attr('href'),
'redirect': $(this).data('redirect'),
'modal_title': 'Delete Plan',
'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
'lang': $(this).data('lang')
};
loadDestroyModal(data);
});
function loadDestroyModal(data) {
$.get('/ajax/destroy-modal', { data: data }, function(modal) {
$('body').append(modal);
$('#destroy-modal').modal('show');
});
}
AJAX CONTROLLER
// routed by /ajax/destroy-modal
public function destroyModal() {
$data = Input::get('data');
$params = [
'route' => $data['route'],
'redirect' => $data['redirect'],
'title' => $data['modal_title'],
'content' => $data['content_view'],
'lang' => $data['lang']
];
return View::make('_helpers.modal-destroy', $params);
}
DESTROY CONFIRMATION MODAL (_helpers.modal-destroy)
<div id="destroy-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true"><i class="fa fa-times"></i></span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">{{ $title }}</h4>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
<button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JQUERY TO PROCESS DESTROY METHOD AND REDIRECT FLASH MESSAGE
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
var redirect = $(this).data('redirect');
var lang = $(this).data('lang');
$(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');
$.ajax({
'url': $(this).data('route'),
'type': 'DELETE',
'success': function(response) {
if (response) {
redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
} else {
redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
}
}
});
});
PLANS CONTROLLER
public function destroy($id)
{
try
{
Stripe::plans()->destroy(['id' => $id]);
return Response::json(TRUE);
}
catch (Exception $e)
{
return Response::json(FALSE);
}
}
JQUERY FOR REDIRECTION
function redirectWithFlashMessage(redirect, type, status, lang) {
var params = {
type: type,
status: status,
lang: lang
};
$.get('/ajax/flash', params, function(response) {
window.location.href = redirect;
});
}
AJAX CONTROLLER (Redirect with Flash)
public function flashData() {
$message_type = 'success' == Input::get('status') ? 'success' : 'failure';
$message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];
Session::flash($message_type, $message);
return ['status' => $message_type, 'message' => $message];
}
It's a lot of code but once setup it's extremely easy to replicate.
I think your system's requiring the authentication for controller action "destroy" method. So you need to login before calling that method.
If you're using the middleware "auth" (app\Http\Middleware\Authenticate.php), you can easy find the "handle" function that returning "Unauthorized" error.
Hope this will help.
I am new to Laravel but have managed to get a contact form working and showing validation errors when there are some.
However I do have one problem and have no idea how to handle it in Laravel. When a message is sent (validation rules pass) I would like to display an alert box (Bootstrap style) saying 'Thanks, message has been sent'.
CODE
public function postContact()
{
$formData = Input::all();
// input validator with its rules
$validator = Validator::make(
array(
'name' => $formData['name'],
'email' => $formData['email'],
'subject' => $formData['subject'],
'message' => $formData['message']
),
array(
'name' => 'required|min:3',
'email' => 'required|email',
'subject' => 'required|min:6',
'message' => 'required|min:5'
)
);
if ($validator -> passes()) {
// data is valid
Mail::send('emails.message', $formData, function($message) use ($formData) {
$message -> from($formData['email'], $formData['name']);
$message -> to('info#company.com', 'John Doe') -> subject($formData['subject']);
});
return View::make('contact');
} else {
// data is invalid
return Redirect::to('/contact') -> withErrors($validator);
}
}
How can I achieve this in Laravel 4?
You could use the with method of the Redirect class:
if ($validator -> passes()) {
// data is valid
Mail::send('emails.message', $formData, function($message) use ($formData) {
$message -> from($formData['email'], $formData['name']);
$message -> to('info#company.com', 'John Doe') -> subject($formData['subject']);
});
//Redirect to contact page
return Redirect::to('/contact')->with('success', true)->with('message','That was great!');
} else {
// data is invalid
return Redirect::to('/contact') -> withErrors($validator);
}
You will be redirected to the contact page with the session variables success and message set.
Use them for an alert in your view, e.g. in a Bootstrap Alert:
with Blade
#if(Session::has('success'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> {{ Session::get('message', '') }}
</div>
#endif
without Blade
<?php if(Session::has('success')): ?>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> <?php echo Session::get('message', ''); ?>
</div>
<?php endif; ?>
If you are using them like this you can even provide success alerts, info alerts, or any alert you want to.
When your data is INVALID you use the withErrors() method to pass some data (erros) to your route.
You can use the same process with any kind of data.
For example:
return View::make('contact')->withMessage("Thanks, message has been sent");
This method withMessage() will create a new variable message and store it in the Session for one request cycle.
So, in your view you can access it like this:
#if(Session::has('message'))
<div class="alert-box success">
{{ Session::get('message') }}
</div>
#endif
I assume you are using Bootstrap so this answer will show the message in pop up window (I test it on Laravel 5)
return View::make('contact')->with('message', "Thanks, message has been sent");
Make sure this code will be added in footer
<!-- Show Pop up Window if there is message called back -->
<?php
if(session('message'))
{
echo '<script>
document.getElementById("popup_message").click();
</script>';
}
?>
Add this function in helper.php so you can use it anywhere in your code
function message_pop_up_window($message)
{
$display = '
<a class="popup_message" id="popup_message" data-toggle="modal" data-target="#message" href="#"></a>
<div class="modal fade" id="message" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messsage </h4>
</div>
<div class="modal-body">
<p>'.$message.'</p>
</div>
</div>
</div>
</div>
</div>';
return $display;
}
Then call the function in you page
{!! message_pop_up_window($message) !!}
I need to edit the data to db and make it a view on instant and using angular xeditables, but i am unable to pass the data to process.php (to update the db and retrieve back the data)
How can I pass the data using $http.post
Code snippet
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="http://code.angularjs.org/1.0.8/angular-mocks.js"></script>
<link href="angular-xeditable-0.1.8/css/xeditable.css" rel="stylesheet">
<script src="angular-xeditable-0.1.8/js/xeditable.js"></script>
<script>
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', ['$scope','$filter','$http', function($scope, $filter,$http) {
$scope.user = {
name: 'awesome user',
status: 2,
group: 4
};
$scope.statuses = [
{value: 1, text: 'status1'},
{value: 2, text: 'status2'},
{value: 3, text: 'status3'},
{value: 4, text: 'status4'}
];
$scope.groups = [
{value: 1, text: 'user'},
{value: 2, text: 'customer'},
{value: 3, text: 'vip'},
{value: 4, text: 'admin'}
];
$scope.errors = [];
$scope.msgs = [];
$scope.saveUser = function()
{ // $scope.user already updated!
return $http.post('/saveUser', $scope.user).error(function(err) {});
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http.post('include/process.php', {'name': $scope.name, 'status': $scope.status, 'group': $scope.group}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
};
}]);
app.run(function($httpBackend) {
$httpBackend.whenPOST(/\/saveUser/).respond(function(method, url, data) {
data = angular.fromJson(data);
});
});
</script>
HTML
.....
<div ng-app="app" ng-controller="Ctrl">
<form editable-form name="editableForm" >
<ul>
<li class="err" ng-repeat="error in errors"> {{ error}} </li>
</ul>
<ul>
<li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
</ul>
<div class="pull-right">
<!-- button to show form -->
<button type="button" class="btn btn-default btn-sm" ng-click="editableForm.$show()" ng-show="!editableForm.$visible"> Edit </button>
<!-- buttons to submit / cancel form -->
<span ng-show="editableForm.$visible">
<button type="submit" class="btn btn-primary btn-sm" ng-disabled="editableForm.$waiting" onaftersave="saveUser()"> Save </button>
<button type="button" class="btn btn-default btn-sm" ng-disabled="editableForm.$waiting" ng-click="editableForm.$cancel()"> Cancel </button>
</span> </div>
<div>
<!-- editable username (text with validation) -->
<span class="title">User name: </span> <span editable-text="user.name" e-id="myid" e-name="name" e-required>{{ user.name || 'empty' }}</span>
</div>
<div>
<!-- editable status (select-local) -->
<span class="title">Status: </span> <span editable-select="user.status" e-name="status" e-ng-options="s.value as s.text for s in statuses"> {{ (statuses | filter:{value: user.status})[0].text || 'Select' }} </span> </div>
<div>
<!-- editable group (select-remote) -->
<span class="title">Group: </span> <span editable-select="user.group" e-name="group" e-ng-options="g.value as g.text for g in groups"> {{ (groups | filter:{value: user.group})[0].text || 'Select' }} </span> </div>
</form>
</div>
....
PROCESS.PHP
<?php
$data = json_decode(file_get_contents("php://input"));
$name = mysql_real_escape_string($data->name);
$status = mysql_real_escape_string($data->status);
$group = mysql_real_escape_string($data->group);
if ($group == 'vip') {
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
I don't know if it would be useful to you or someone else.
Afaik, you cannot use http.post with angular to update a database (at least in my case, with php and mysql). You need to use $http() like follows:
var request = $http({
method: "post",
url: "include/process.php",
data: {
name: $scope.name,
status: $scope.status,
group: $scope.group
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Then, in PHP, retrieve it like:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$name = $request->name;
#$status = $request->status;
#$group = $request->group;
...
?>
With the values at $name, $status and $group you'll be able to update your database.
UPDATE: Your process.php is not called because you have a "return $http.post('/saveUser', $scope.user)" line first in $scope.saveUser = function(), which immediately ends execution of the saveUser function. See return statement in Javascript:
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.