Call to a member function create() on a non-object Laravel - php

Im a beginner in Laravel. I have two login authentication types; using facebook API and using your own email.
Everytime I upload an image when im logging in with my own email, I got this error
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call to a member function create() on a non-object","file":"C:\base_app_folder\app\controllers\OnboardingController.php","line":133}}
But it's success uploading image when im logging in with Facebook API
Here's my Controller :
if (Input::hasFile('profile_pic')) {
$images = ImageUpload::handle(Input::file('profile_pic'));
$mainImage = $images[0];
$time = time();
$mainImageObj = $this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $mainImage['image_url'],
'width' => $mainImage['width'],
'height' => $mainImage['height'],
'created_fb' => $time,
'is_original' => $mainImage['is_original'],
'original_id' => null
));
$this->userDetails->update($this->userId, array(
'Profile_Pic_Url' => $mainImageObj->image_url
));
array_shift($images);
Log::info('images = '.print_r($images, true));
$retImage = "";
foreach ($images as $image) {
$this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $image['image_url'],
'width' => $image['width'],
'height' => $image['height'],
'created_fb' => $time,
'is_original' => $image['is_original'],
'original_id' => $mainImageObj->image_id
));
if ($image['width'] == 250) {
$retImage = $image['image_url'];
}
}
return Response::json(array(
'success' => true,
'message' => 'Upload succeeded!',
'image_thumbnail_url' => $retImage,
'image_url' => $mainImage['image_url']
));
} else {
App::abort(404);
}
}
Here's my View :
<form action="{{{ route('postEditProfile', array('profile_id' => Session::get('user_id'))) }}}" class="dropzone" id="profile-pic-upload">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
And here's the javascirpt:
<script type="text/javascript">
$(window).bind("load", function() {
var pic_height = $('.profile_pic').height();
var pic_width = $('.profile_pic').width();
var height_factor = pic_height/240;
var pic_width = pic_width/height_factor;
$('.profile_pic').css('height','240px');
$('.profile_pic').css('width',pic_width+"px");
});
$(document).ready(function () {
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
});
var routes = {
postEditProfile: "{{{ route('postOnboardingPhotos') }}}"
};
var onboarding = new Onboarding(routes);
});
</script>
Anyone knows how to solve it ? I've searching for the error message but it seems no one ever found this error message.

Did you forget to inject a dependency and assign $this->images to that dependency? Looks like you have an images repository and you forgot to take care of this.

Related

Ajax live edit is not wotking and got an 500 (Internal Server Error)?

i'm trying to modify a product but when i click the button a got that 500 (Internal Server Error)
this is ajax method
$(document).ready(function(){
fetch_customer_data();
$(document).on('click', '#btnModify', function(){
var name = $('#Name2').text();
var title = $('#Title2').text();
var mainPrice = $('#MainPrice2').text();
var discount = $('#DiscountPrice2').text();
var StockQ = $('#StockQuantity2').text();
var Desc = $('#Discription2').text();
var Features = $('#Features2').text();
var id = $("#id2").text();
if(name != ' ')
{
$.ajax({
url:"/Product/Update",
method:"POST",
data:{name:name, title:title , name:name , mainPrice:mainPrice , discount:discount ,StockQ:StockQ , Desc:Desc , Features:Features, id:id, _token:_token},
success:function(data)
{
fetch_customer_data();
}
});
}
else
{
alert('Something went wrong');
}
});
and this is the edit function
public function edit(Request $request)
{
if($request->ajax())
{
$data = array([
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
]
);
DB::table('products')
->where('id', $request->id)
->update($data);
echo '<div class="alert alert-success">Data Updated</div>';
}
}
Route :
Route::post('/Product/Update', [ProductsController::class, 'edit']);
Try this:
$data = array(
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
)
because you are using multi dimensional array instead of 2d array
maybe this will helpful

How to upload images with data in one form CI with Ajax

I create a form for adding an advertisement, where you enter a few text inputs, and under them a place with adding photos and if it was just adding photos without reloading the page - it worked, I just selected photos and sent the entire form with one button, uploaded photos to the server and I added photo names to the database. But I would like this form to be more useful and to preview these photos before sending the entire form, so I added the Ajax script. And the problem is that when you choose photos and upload them to the server I do not know how to transfer them to the main form.
I tried to add $this->create($photos) at the end of the upload function and pick them up in the create function. I pass them on, but as soon as Ajax has reloaded the first page when he uploads it. When I fill in the form's text fields and press send the form, then $ photos is NULL and I don't know how to transfer and save this data in the database? How do you make it work?
public function create()
{
if ( !empty( $_POST ) )
{
if ( $this->form_validation->run( 'site_ads_create' ) == true )
{
$activate_code = random_string();
if ( logged_in() == true )
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'subcat' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->session->userdata( 'email' ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 1,
);
}
else
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'subcat' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->input->post( 'email' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 0,
'activate_code' => $activate_code,
);
}
$add = $this->Site_model->create( 'ads' , $data );
$this->session->set_flashdata( 'alert' , 'Ogłoszenie zostało dodane.' );
//redirect( '/dodaj-ogloszenie' );
}
else
{
$this->session->set_flashdata( 'alert' , validation_errors() );
//refresh();
}
}
$data['cities'] = $this->Site_model->get_cities('cities', 'name', 'asc');
$data['categories'] = $this->Site_model->get_categories();
$this->load->view( 'create' , $data );
}
upload function
public function upload()
{
if($_FILES["files"]["name"] != '')
{
$output = '';
$path = BASEPATH . '../images/'. date('y').'_'.date('m').'/';
if ( !file_exists( $path ) )
{
mkdir( $path , 0777 );
}
$config['upload_path'] = 'images/'. date('y').'_'.date('m').'/';
$config["allowed_types"] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<div class="col-md-3">
<img src="'.base_url().'images/'. date('y').'_'.date('m').'/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$photos[] = $this->upload->data();
}
}
echo $output;
}
}
and a piece of the form with the ajax script
<form method='post' action='<?php echo base_url();?>ads/create' enctype='multipart/form-data'>
...
<div class="container">
<br /><br /><br />
<h3 align="center">Upload Multiple Files in Codeigniter using Ajax JQuery</h3><br />
<div class="col-md-6" align="right">
<label>Select Multiple Files</label>
</div>
<div class="col-md-6">
<input type="file" name="files" id="files" multiple />
</div>
<div style="clear:both"></div>
<br />
<br />
<div id="uploaded_images"></div>
</div>
<script>
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>ads/upload",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
$('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data)
{
$('#uploaded_images').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
</script>
<?php echo form_close(); ?>
If you want to preview image before upload, use FileReader to do that. This is the code,
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
//imgInp is ID form upload file
$("#imgInp").change(function(){
readURL(this);
});

Can't insert data into database using ajax

I am new to jquery and ajax and now I have a hard time finding a fix to this problem of mine when inserting data into database using ajax and codeigniter.
All errors are okay but when there's no error on the form, I get a database error and all the inputs become NULL.
Controller
public function add () {
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
// assume validation rules are already set.
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->user_model->save($data);
}
}
Ajax 1:
$(document).ready(function() {
$('#create-user').click( function(e) {
var is_valid = false;
var form_id = '#'+ $(this).parents('form').attr('id');
// Validate required fields are not blank
// do a js validation?
// Apply action
if(is_valid) {
var add_result = do_submit(form_id);
} else {
$('#error-msg').html(result.message); // if form is not valid
}
});
});
Ajax 2:
function do_submit(form_id) {
var url = $(form_id).attr("action");
var ajax_result = false;
var formData = {};
// Submit form using ajax
ajax_result = $.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
// return result;
// do something
console.log(result);
if (result.data) {
make_alert();
}
},
error: function(textStatus) {
/* Note: decide how all errors should be shown. */
swal({
title: "Error!",
text: "Oops, something went wrong. Check fields and try again.",
type: "error"
});
}
});
return ajax_result;
} // End do_submit()
I think you have a syntax error here
$this->load->model('user_model');
'data' => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
Should probably be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Your parameter array seems to be a key, but of what variable? So you need to have $data instead of 'data'.
To get post data in codeigniter we use
$this->input->post('field_name');
SO you need to change all post['field_name'] to post('field_name')
Your final code would be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Read https://www.codeigniter.com/user_guide/libraries/input.html

Display Zend Form Validation error in Ajax

There is a Zend Registration Form. Having as input username, email, password and confirm password. Validator for email is following:
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'E-mail address already exists'
),
),
),
),
));
There are 4 validators: Required Type, e-amil format and if there is someone with following e-mail in database.
Error messages will be:
- E-mail is required
- Email address format is invalid
- E-mail address already exists
Problem Trying to catch error messages and output using ajax. In RegisterController having following function:
public function ajaxAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
$post = $this->request->getPost();
$form->setData($post);
$response = $this->getResponse();
$hello = 1;
if (!$form->isValid()){
// email is invalid; print the reasons
$json= $form->getMessages();
$response->setContent(\Zend\Json\Json::encode($json));
}
return $response;
}
And jQuery file:
$( document ).ready(function() {
var urlform = "register/ajax";
$("#btnRegister").click( function() {
$("#Register").submit( function() {
return false;
});
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
async: true,
data: $(".form-signin").serialize(),
success: function (data) {
$("#rCheck").text(data);
console.log(data);
},
error: function (data) {
$("#rCheck").text(data);
console.log(data);
}
});
});
});
In Console i got something like this https://imagizer.imageshack.us/v2/558x205q90/661/uC09Da.png and in div with id #rCheck getting [Object][Object].
From the image you provided the error messages are correctly returned. The error is that you are trying to write directly an Object into your div.
You should have seached how to read an object with JavaScript. Try with this code :
success: function (data) {
data.forEach(function(datum) {
Object.keys(datum).forEach(function (key) {
$('<p>'+obj[key]+'</p>').appendTo('#rCheck');
});
});
console.log(data);
},
Or you may also do that within your ajaxAction :
$messages = array();
$errors = $form->getMessages();
foreach($errors as $key=>$row)
{
if (!empty($row) && $key != 'submit') {
foreach($row as $keyer => $rower)
{
$messages[$key][] = $rower;
}
}
}
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
}
return $response;
Here's is a good post on how to use Zend\Form with Ajax validation.

How to reload Zend Captcha image on click refresh button?

I apply a zend captcha in my php page now i require to add captcha reload button. Please give answer according to zend.
Just two quick snippets but I think you will get the idea. Adjust the element name and the selectors for your needs.
In your controller add a method to generate a fresh captcha
public function refreshAction()
{
$form = new Form_Contact();
$captcha = $form->getElement('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl() .
$captcha->getId() .
$captcha->getSuffix();
$this->_helper->json($data);
}
In your view script (I'm using mootools for the ajax-request)
document.addEvent('domready', function() {
$$('#contactForm img').addEvent('click', function() {
var jsonRequest = new Request.JSON({
url: "<?= $this->url(array('controller' => 'contact', 'action' => 'refresh'), 'default', false) ?>",
onSuccess: function(captcha) {
$('captcha-id').set('value', captcha.id);
$$('#contactForm img').set('src', captcha.src);
}
}).get();
});
});
Edit: Added pahan's jquery
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src', data.src);
$('#captcha-id').attr('value', data.id);
}
});
});
});
#user236501 Actually it can be any type of Zend Form Element (for example Button). You're even able to put clickable refresh link as Zend_Form_Element_Captcha description option like this:
$captcha = new Zend_Form_Element_Captcha('captcha', array(
'label' => 'Some text...',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'font' => './fonts/Arial.ttf',
'imgDir' => './captcha/',
'imgUrl' => 'http://some_host/captcha/'
),
'description' => '<div id="refreshcaptcha">Refresh Captcha Image</div>'
));
but in that case Description decorator's options should be modified, for example:
$this->getElement('captcha')->getDecorator('Description')->setOptions(array(
'escape' => false,
'style' => 'cursor: pointer; color: #ED1C24',
'tag' => 'div'
));
It can be done in form's init() method.
Sorry for my english. Btw I'm not sure if I put my comment in the right place ;)
#Benjamin Cremer
thanks for the code, works like charm :)
after reading this
I did it using jquery.
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src',data.src);
$('#captcha-id').attr('value',data.id);
}
});
});
});
In config/autoload/global.php add the following
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy','Zend\View\Strategy\PhpRendererStrategy'
),
),
in YourModule/src/YourModule create a new folder Ajax
Inside Yourmodule/Ajax create a file AjaxController.php
namespace YourModule\Ajax;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use YourModule\Forms\SignupForm;
class AjaxController extends AbstractActionController
{
public function refreshSignupCaptchaAction(){
$form = new SignupForm();
$captcha = $form->get('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl().$captcha->getId().$captcha->getSuffix();
return new JsonModel($data);
}
}
Add route inside module.config.php
'yourmodule-ajax' =>array(
'type' => 'segment',
'options' => array(
'route' => '/yourmodule/ajax/:action',
'constraints' => array(
'action' => '\w+',
),
'defaults' => array(
'controller' => 'YourModule\Ajax\AjaxController',
)
),
),
last in your template, I assume you are using jquery
<div class="form-group">
<div id="captcha" class="control-group <?php echo count($form->get('captcha')->getMessages()) > 0 ? 'has-error' : '' ?>">
<?php echo $this->formLabel($form->get('captcha')); ?>
<div class="col-xs-12 col-sm-6">
<a id="refreshcaptcha" class="btn btn-default pull-right">Refresh</a>
<?php echo $this->formElement($form->get('captcha')); ?>
<?php echo $this->formElementErrors($form->get('captcha')); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#refreshcaptcha').click(function() {
$.ajax({
url: '<?php echo $this->url('yourmodule-ajax', array('action'=>'refreshSignupCaptcha')) ?>',
dataType:'json',
success: function(data) {
$('#captcha img').attr('src', data.src);
$('#captcha input[type="hidden"]').attr('value', data.id);
$('#captcha input[type="text"]').focus();
}
});
return false;
});
});
</script>

Categories