Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
I don't know where the problem actually is in. I sent data via post method to a laravel controller and it didn't reply with a valid json, the controller route and js code are given below:
Route
Route::post('cart/data/store/{id}', 'CartController#addToCart');
Controller
public function addToCart(Request $request, $id)
{
$product = Product::findOrfail($id);
if ($product->discount_price == 0) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->selling_price,
'weight' => 1,
'options' => [
'size' => $request->size,
'color' => $request->color,
'image' => $product->product_cover,
]
]);
return response()->json(['success' => 'Product added successfully on your cart!']);
} else {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->selling_price - $product->discount_price,
'weight' => 1,
'options' => [
'size' => $request->size,
'color' => $request->color,
'image' => $product->product_cover,
]
]);
return response()->json(['success' => 'Product added successfully on your cart!']);
}
}
JS code
function addToCart() {
var product_name = $('#product_name').text();
var id = $('#pid').val();
var quantity = $('#quantity').val();
var size = $('#size').text();
var color = $('#color').text();
var url = "/cart/data/store/" + id;
$.ajax({
type: 'POST',
dataType: 'json',
data: {
product_name: product_name,
color: color,
quantity: quantity,
size: size,
color: color,
},
url: url,
success: function(success) {
console.log(success);
},
error: function(xhr, status, error) {
console.error("An error occurred: " + error);
}
});
}
I tried many times but did not find any error but still it's showing
SyntaxError: Unexpected token '<', '<!-- topba... is not valid JSON
It's showing error I think any html topbar but I not found this type of error...
Related
I am creating an E-commerce web application In frontend I am using a template and in backend I am using Laravel 8, I need to post AddToCart data with ajax, but when I click AddToCar button I get and error
'Uncaught TypeError: a.getElementsByClassName is not a function'
My button
<button type="submit" class="btn btn-primary mb-2" onclick="addToCart">Add to Cart</button>
Ajax code
//Start Add to Cart Product
function addToCart(){
var product_name = $('#pname').text();
var id =$('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity =$('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url:"/cart/data/store/"+id,
success:function(data){
console.log(data);
}
})
}
My controller
public function AddToCart(Request $request, $id){
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->selling_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}else{
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $request->discount_price,
'weight' => 1,
'options' => [
'image' => $request->product_thambnail,
'color' => $request->color,
'size' => $request->size,
],
]);
return response()->json('Successfuly Added on Your Cart');
}
}
First of all, there are some things we can get better on the function like using const instead of var and not defining two times the variable on the object as they have the same name.
function addToCart() {
const id = $('#product_id').val();
const product_name = $('#pname').text();
const color = $('#color option:selected').text();
const size = $('#size option:selected').text();
const quantity = $('#qty').val();
$.ajax({
type:"POST",
datatype:'json',
data: {
color, size, quantity, product_name,
},
url: `"/cart/data/store/"${id}`,
success: console.log
});
}
Anyways, your main issue is an error that is not related or visible in your code as you are using a library/framework (in this case, seems like jquery). You gotta check the stacktrace to see what part of YOUR code is triggering the error. Maybe is not even on this snippets you're sharing here.
I'm trying to save multiple files, but the Request file() method is returning null. Help-me please
My front end:
<input type="file" name="arquivos" multiple />
External JS:
...
var form = document.forms['frmDados'];
...
In one function:
...
var formData = new FormData();
var ins = form.elements['arquivos'].files.length;
for (var x = 0; x < ins; x++) {
formData.append('arquivos[]', form.elements['arquivos'].files[x]);
}
// https://stackoverflow.com/questions/35192841/fetch-post-with-multipart-form-data
await fetch(window.location.href, {
method: method, // POST or PUT
body: formData,
headers: {
'X-CSRF-Token': form.elements['_token'].value
},
}).then((response) => {
...
My backend:
$arquivos = $request->file('arquivos'); // Illuminate\Http\Request
Log::info($arquivos);
Log::info($request->all());
My laravel.log: (I uploaded 2 files, but only shows 1 in the all() method)
[2020-04-07 14:40:11] local.INFO:
[2020-04-07 14:40:11] local.INFO: array (
'otheratribute' => '3',
'otheratribute2' => '1',
'otheratribute3' => '2020-03-03',
'otheratribute4' => '03:00',
'otheratribute5' => 'Tetandos',
'otheratribute6' => '1',
'otheratribute7' => '2020-04-01',
'arquivos[]' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'jgcjkpmefepjgcpg.png',
'mimeType' => 'image/png',
'size' => 392328,
'error' => 0,
'hashName' => NULL,
)),
)
What I intend to do:
try {
$infracao->upload($arquivos, true);
} catch (\Exception $e) {
return response($e->getMessage(), 503);
}
UPDATE 07/04/2020 18:21 GMT-3
I forgot to specify, this solution worked for POST Request, but not for PUT Request which is my problem, which is this and my beginning of solution is this.
I'm using the solution as middleware, and the result for the request is what I put in the question.
I think you just need to do
$request->arquivos
instead of
$request->file('arquivos')
And probably you could also do
$request->input('arquivos')
I want that when the validator fails go to same part of the register form in the home.blade.php and not to the begining of the page.
Can someone help me to do that?
Registercontroller.php
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'phone' => ['required', 'string'],
]);
if ($validator->fails()) {
return redirect('/#register')
->withErrors($validator)
->withInput();
}
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$customization = New Customization();
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
'cuenta' => $data['cuenta'],
'avatar' => "https://i0.wp.com/www.winhelponline.com/blog/wp-content/uploads/2017/12/user.png?fit=256%2C256&quality=100&ssl=1",
]);
$customization->user_id = $user->id;
$customization->save();
return $user;
}
This is the error on laravel:
Pls i need some help
Error Laravel
Simply remove the following from your validator function:
if ($validator->fails()) {
return redirect('/#register')
->withErrors($validator)
->withInput();
}
The validator function is expecting an instance of \Illuminate\Contracts\Validation\Validator to be returned.
So change to:
return Validator::make([
// Your rules here
]);
The controller will automatically redirect back with the errors on failure.
If you want to redirect somewhere else on failure, what you could do is overwrite the register method by adding the following in your controller:
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return redirect('/#register')
->withErrors($validator)
->withInput();
}
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
I'm trying to pass this array var data_array into my controller thru AJAX
This is the value of var data_array when I use alert(JSON.stringify(data_array));
This is my AJAX method
var project_details = $.extend({}, data_array);
$.ajax({
type: "POST",
url: "<?php echo base_url('PPMP_controller/submitPPMP'); ?>",
data: { data_array : $.param(project_details) },
dataType: 'json',
success: function(data) {
alert('PPMP submission success!');
alert(data);
},
error: function(errorw) {
console.log(errorw);
}
});
This is my PPMP_controller
public function submitPPMP(){
$data_array = $this->input->post('data_array');
$value = $this->PPMP_model->submitPPMP($data_array);
echo json_encode($value);
}
This is my model
function submitPPMP($data_array){
$date_format = 'DATE_W3C';
$date_submitted = standard_date($date_format);
$data = array(
'user_id' => 1,
'date_submitted' => $date_submitted,
'first_lvl_status' => 0,
'second_lvl_status' => 0,
'third_lvl_status' => 0,
'fourth_lvl_status' => 0,
'submitted' => 1
);
$this->db->insert('project', $data);
$id = $this->db->insert_id();
if(is_array($data_array) || is_object($data_array)){
return "yes";
foreach($data_array as $object){
$project_details = array(
'project_id' => $id,
'supply_id' => $object->supply_id,
'supply_description' => $object->supply_description,
'quantity' => $object->quantity,
'price' => $object->price,
'jan' => $object->jan,
'feb' => $object->feb,
'mar' => $object->mar,
'apr' => $object->apr,
'may' => $object->may,
'jun' => $object->jun,
'jul' => $object->jul,
'aug' => $object->aug,
'sep' => $object->sep,
'oct' => $object->oct,
'nov' => $object->nov,
'dec' => $object->dec
);
$this->db->insert('project_details', $project_details);
}
}
else{
return "no";
}
return $this->db->last_query();
}
However the array passed from controller to model is not an array since it doesn't go thru the line if(is_array($data_array) || is_object($data_array)) instead it goes to the else condition and return "no".
What might be causing this array not being passed an array from controller to model. Thank you for the help. I am using Codeigniter 3.0 as an MVC framework.
you are passing json to your model not array , when it comes to your model it should be ,
try var_dump($data_array) to check its data type i.e json or object or array
$data_array = json_decode($data_array); // to get object
$data_array = json_decode($data_array,true); // to get array
Your PPMP_controller should be
public function submitPPMP(){
$data_array = $this->input->post('data_array');
$data_array = json_decode($data_array);
$value = $this->PPMP_model->submitPPMP($data_array);
echo json_encode($value);
}
I have a php page that is making a couple of ajax calls. The first ajax call is made and on success it activates a second ajax function. Each function has die() at the end. No matter what I do, die() keeps outputting a "0" to the screen. I tried commenting the die() out of the first ajax function, but it never processes the ajax request when I do that. The loading gif just keeps spinning. When I comment out the die() in the second function, it outputs "0" twice. I have no clue why it keeps printing that to the screen.
This is the first function.
function json_info() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
// create a new array to store projects
$projectsArray = array();
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
$projectsArray = array();
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
$image = get_field('project_photo');
$image = $image['sizes']['thumbnail'];
$projectsArray[] = array(
'title' => get_the_title(),
'lat' => get_field('latitude'),
'long' => get_field('longitude'),
'status' => get_field('status'),
'industry' => get_field('industry'),
'state' => get_field('state'),
'link' => get_permalink(),
'photo' => $image,
'num' => $paged
);
endwhile; endif;
wp_reset_query();
} // end of isset
?>
<?php
echo json_encode($projectsArray);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info', 'json_info' );
add_action( 'wp_ajax_nopriv_json_info', 'json_info' );
And this is the second function:
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for earch of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','construction');
$statesAll = array('sc','tx','wa');
// set $statusArray dependent on whether or not "all" is selected
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
?>
<li class="group">
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
And this is the ajax call to both functions:
function run_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info',
'state' : state,
'status' : markets,
'services' : services
},
success:function(data) {
// This outputs the result of the ajax request
var jsonData = JSON.parse(data);
do_ajax();
} /*,
error: function(errorThrown){
console.log(errorThrown);
}*/
}); // end of ajax call for json_info
function do_ajax() {
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
}
I'm not sure what I'm missing or doing wrong that is causing the "0" to print to the screen.
Well, it turns out that I'm an idiot, and I was just overlooking the problem. There was a third function called by ajax, and I didn't have die() at the end of it. I was thinking the issue was in my second function since the 0 was showing up in the div where I was printing that content.