ajax laravel not inserting or code not working - ajax

i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i dont' know why although i am writing correctly
please help
here is my code
my blade file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row" style="matgin-top:50px;">
<div class="col-md-6">
<div class="card">
<div class="card-hehader bg-primary text-white">Add new product</div>
<form id="form" action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
#csrf
#method('POST')
<div class="form-group">
<label for="">product name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<div class="form-group">
<label for="">product image</label>
<input type="file" name="image" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<button type="submit" class="btn btn-info">add</button>
</form>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary">All Products</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = this;
$.ajax({
url:$(form).attr('action'),
method:$(form).attr('method'),
data:new FormData(form),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
succes:function(data){
if(data.code == 0){
$.each(data.error, function(prefix,val){
$(form).find('span.'+prefix+'_error').text(val[0]);
});
}
else{
$(form)[0].reset();
alert(data.msg);
// fetchAllProducts();
}
}
})
});
});
</script>
</body>
</html>
and my controller store function
public function store(Request $request)
{
$path = 'files/';
$file = $request->file('product_image');
$file_name = time().'_'.$file->getClientOriginalName();
// $upload = $file->storeAs($path, $file_name);
$upload = $file->storeAs($path, $file_name, 'public');
if($upload){
Product::insert([
'name'=>$request->name,
'image'=>$request->image,
]);
return response()->json(['code'=>1,'msg'=>'New product has been saved successfully']);
}
}

I check out your controller portion and found something messy, would you mind trying with the below code:
if ($request->has('image')) {
$fileName = time() . '_' . $request->image->getClientOriginalExtension();
$request->image->storeAs('Files', $fileName, 'image');
$product = new Product();
$product->name = $request->name;
$product->image = $fileName;
$product->save();
return response()->json(['code'=>1,'msg'=>'New product has been saved
successfully']);
}

Related

ErrorException Array to string conversion

i am facing ErrorException Array to string conversion, I am new in laravel. please help me in detail if you can,please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can please help me in detail if you can
This is my code
<?php
namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;
use App\Models\Test;
use File;
class JsonController extends Controller
{
public function index()
{
return view('json_form');
}
public function download(Request $request)
{
$data = $request->only('name','email','mobile_number');
$test['token'] = time();
$test['data'] = json_encode($data);
Test::insert($test);
$fileName = $test['token']. '_datafile.json';
File::put(public_path('/upload/json/'.$fileName),$test);
//return download(public_path('/upload/jsonfile/'.$fileName));
$headers = [ 'Content-Type' => 'application/json', ];
return response()->download($test, 'filename.json', $headers);
//return response()->download(public_path('file_path/from_public_dir.pdf'));
}
}
This is my jeson.blade.php
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Store Data To Json Format In Database - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.error{ color:red; }
</style>
</head>
<body>
<div class="container">
<h2 style="margin-top: 10px;">Laravel Store Data To Json Format In Database - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
<form id="laravel_json" method="post" action="json-file-download">
#csrf
<div class="form-group">
<label for="formGroupExampleInput">Name</label>
<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
</div>
<div class="form-group">
<label for="email">Email Id</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
</div>
<div class="form-group">
<label for="mobile_number">Mobile Number</label>
<input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>

How to use CSRF token in codeigniter with Ajax Post data in database with giving 403 Error..?

* While posting data in database in codeigniter first time my data is post to database , but when second time i am try to post data in database then it give me 403 ERROR .First Time code is work ,when second time i am post it give me 403 error data is not post or save in my database. *
View Page Code :
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2>Register</h2>
<!-- <form id="saveEmpForm"> -->
<?php
$attributes = array('id' => 'saveEmpForm');
echo form_open('register/insert', $attributes);
?>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<button type="submit" class="btn btn-primary" id="btn_add">Submit</button>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<script type="text/javascript">
$('#saveEmpForm').submit('click',function(){
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>register/insert",
dataType : "JSON",
data : {name:name, email:email, password:password, csrf_test_name: csrf_token},
success: function(response){
$('#name').val("");
$('#email').val("");
$('#password').val("");
alert('Success');
}
});
return false;
});
</script>
</body>
</html>
Controller code:
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('register_model');
}
public function index()
{
$this->load->view('register_view');
}
public function insert(){
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result=$this->register_model->insert_data($data);
echo json_encode($data);
}
}
Model Code :
class Register_model extends CI_Model{
public function insert_data($data)
{
$this->db->insert('emp',$data);
return $this->db->insert_id();
}
}
?>```

Twitter API app, does not showing pictures or videos

I created Twitter API app in Laravel. The application provide very weird layout. I cannot set up profile picture, or picture for tweet. I am getting only text pretty much.
I spent whole day to figure out, why my APP does not have picture, url or videos.
I appreciate any suggestions what might be wrong
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-
UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
<link rel="stylesheet" href="{{asset('/css/app.css')}}">
<title>Nancy's Twitter API App</title>
</head>
<body>
<h1 class="text-info text-center mt-5">Nancy's Tweets Api</h1>
<div class="container">
<div class="col align-self-center mb-5">
<form class="well" action="{{route('post.tweet')}}"
method="POST" enctype="multipart/form-data">
#csrf
#if(count($errors) > 0)
#foreach ($errors->all() as $error)
<div class="alert alert-danger"> {{$error}}</div>
#endforeach
#endif
<div class="form-group">
<label>Your Tweet</label>
<textarea class="form-control" name="tweet"
rows="3"></textarea>
</div>
<div class="form-group">
<label>Upload Filet</label>
<input type="file" class="form-control-file"
name="images[]" multiple>
</div>
<div class="from-group">
<button class="btn btn-success">Create
Tweet</button>
</div>
</form>
</div>
</div>
<div class="container">
<h3>Tweets:</h3>
#if(!empty($data))
#foreach ($data as $key => $tweet )
<div class="card text-primary bg-white mb-3" style="max-width:
150rem;">
<div class="card-body">
<p class="card-text"><h3>{{$tweet->text}}</h3></p>
#if(!empty($tweet->extented_entities->media)){
#foreach ($tweet->extented_entities->media as $i)
<img src="{{$i->media_url_https}}"
style="width:100px;">
#endforeach}
#endif
<div class="card-header">
<i class="fas fa-heart">{{$tweet-
>favorite_count}}</i>
<i class="fas fa-redo"> {{$tweet-
>retweet_count}}</i>
</div>
</div>
</div>
#endforeach
#else
<p>No Tweets Found</p>
#endif
</div>
</body>
</html>
class TwitterController extends Controller
{
//
public function twitterUserTimeline(){
$count = 10;
$format = 'array';
$data = Twitter::getUserTimeline([$count, $format]);
return view('twitter', compact('data'));
}
public function tweet(Request $request){
$this->validate($request, [
'tweet' => 'required'
]);
$newTweet = ['status' => $request->tweet];
if(!empty($request->images)){
foreach($request->images as $key => $value){
$uploadMedia = Twitter::uploadMedia(['media' => File::get($value-
>getRealPath())]);
if(!empty($uploadMedia)){
$newTweet['media_ids'][$uploadMedia->media_id_string] =
$uploadMedia->media_id_string;
}
}
}
$twitter = Twitter::postTweet($newTweet);
return back();
}
}

laravel using withErrors in a try catch

So i'm making this website where you can buy game consoles, so I made a crud, but I wanted that it was impossible to insert duplicates in the database, but when I create a dupicate you get a laravel error and that is not user friendly. So I wanted to show a normal message saying that you made a duplicate. so I made this.
public function store(Request $request)
{
try
{
$consoles = new consoles();
$consoles->naam = input::get('naam');
$consoles->releasedate = input::get('releasedate');
$consoles->company = input::get('company');
$consoles->price = input::get('price');
$consoles->created_at = null;
$consoles->updated_at = null;
$consoles->save();
}catch (\Exception $e)
{
return Redirect::to('console/create')
->withInput()
->withErrors(array('message' => 'duplicate'));
}
return redirect('consoles');
}
the problem is that ->withErrors(array('message' => 'duplicate')) doesn't show anything. what am I doing wrong.
EDIT
create.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }).val();
} );
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"> creating data</div>
<form method="POST" action="{{url('games/store/')}}">
naam: <br>
<input type="text" name="naam" required>*required<br>
releasedate: <br>
<input type="text" name="releasedate" id="datepicker" required>*required<br>
company: <br>
<input type="text" name="company" required>*required<br>
price: <br>
<input type="number" name="price" min="0" value="0" step=".01" required>*required<br>
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<input type="submit" name="create" value="create">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
When you set withErrors you don't need to pass the array, just write the error message like this ->withErrors('Duplicate');
In the view remember to include a check if there are errors
#if ($errors->count())
<div class="col-md-12">
<div class="alert alert-danger text-center">
#foreach ($errors->all() as $error)
<p>{{$error}}</p>
#endforeach
</div>
</div>
#endif
You can simply use with() to send the message to the view like
return Redirect::to('console/create')
->withInput()
->with('message', 'duplicate');
and access that in view as
#if ($message = Session::get('message'))
{{$message}}
#endif

Response is empty string

I am creating a simple upload files web application using laravel in the backend and I am trying to print the response that is sent from the server -which is supposed to be informed about the uploaded file- in the console, but it shows me an empty string.
here is my controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Storage;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postUpload(request $request){
// //
$result = print_r($request,true);
$time = Carbon::now();
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName();
//$upload_success = $file->storeAs('public',$file->getClientOriginalName());
$upload_success=Storage::disk('local')->put($fileName, fopen($file, 'r+'));
if ($upload_success) {
return response()->json(['request'=>$request->getContent()], 200);
}
else {
return response()->json('error', 400);
}
}
return response()->json('no file to upload', 400);
}
}
and my view where I am printing the response:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#upload').on("click",function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#file").upload("/upload",function(data){
$('#spin').css('display','none');
$('#msg').css('display','block');
console.log(data);
},function(prog,val){
$('#prog').html(val+"%");
$('#prog').width(''+val+'%');
if(val == 100){
$("#prog").html('Completed');
$('#spin').css('display','block');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div style="margin-top:5px"><input type="file" id="file" name="file" ></div>
<div style="margin-top:5px;margin-bottom: 5px">
<input type="button" id="upload" value="upload" class="btn btn-success btn-lg">
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100" id="prog"></div>
</div>
<div id="spin" style="display:none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</div>
<div class="alert alert-success" style="display: none" id="msg" style="text-align: center">
<strong>Success!</strong>You have uploaded the file successfully
</div>
</div>
</body>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
and here is a sample of what I get:
I would know if I am doing it wrong, and if not, why it is empty,
Thanks.
You're not using a form element.
Wrap your inputs in a basic html form:
<form method="POST" action="#">
#csrf
...
</form>
Then use jquery to post the form to the laravel route.

Resources