Laravel "MethodNotAllowedHttpException in RouteCollection.php line 219" - javascript

I'm just wondering right now why this particular table I am interacting with the database returns an error like the above subject where in fact I am just using the same mechanism from other table. I am refering to my table "Inventory". My store method just simply returns an error stated in the subject above and I have checked all the parameters in controller and in my model and it seems there is no error. Can somebody help me spot the error here. Please help. Here are my codes.
InventoryController.php
public function store( Request $request ){
$prod_ids = $request['product_ids'];
$purchase_order_ids = $request['purchase_order_ids'];
$purchase_ids = $request['purchase_ids'];
$quantity = $request['purchaseQuantity'];
for($i = 0; $i < count($prod_ids); $i++){
Inventory::create([
'product_id' => $prod_ids[$i],
'purchase_order_id' => $purchase_order_ids[$i],
'purchase_id' => $purchase_ids[$i],
'quantity' => $quantity[$i]
]);
}
return json_encode(array('notify' => "Success"));
}
My model => Inventory.php
<?php
namespace App\Inventory;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $fillable =
['product_id','purchase_order_id','purchase_id','quantity'];
}
My Javascript:
$("#purchase_toInventoryID").click(function(e){
e.preventDefault();
var array_prodID = <?php echo json_encode(isset($array_prodID) ? $array_prodID : 0); ?>;
var array_poID = <?php echo json_encode(isset($array_poID) ? $array_poID : 0); ?>;
var array_purchaseID = <?php echo json_encode(isset($array_purchaseID) ? $array_purchaseID : 0); ?>;
var array_purchaseQuantity = <?php echo json_encode(isset($array_purchaseQuantity) ? $array_purchaseQuantity : 0); ?>;
$.post("{{ url('saveToInventory') }}", {
'product_ids': array_prodID,
'purchase_order_ids': array_poID,
'purchase_ids':array_purchaseID,
'purchaseQuantity': array_purchaseQuantity
}, function(data){
if(data.notify == "Success"){
console.log(data.notify);
}else{
console.log(data.notify);
}
}, 'json');
});
My routes.php
Route::post('saveToInventory', 'Inventory\InventoryController#store');

Related

How can I pass id of multiple row selection to print page at the time of inserting data

I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();

Having some issue with post/get request using jquery

I am passing some data over to a route when a specific option is selected from the form. I test the value and its coming over but when i try to use a if statement is doesn't work see code below:
$app->post('/fdfd', function ($request, $response) {
$params = $request->getParams();
$val = $params['file']; //value coming over is = "pipe"
$users = $this->db->query("SELECT * FROM `stock`")->fetchAll(PDO::FETCH_OBJ);
foreach ($users as $cat) {
if ($cat->category == $val) {
$name = $cat->name;
echo "<option value='test'>$name</option>";
} else {
echo "False";
}
}
})->setName('lazyy');
I am sure the value is coming over because if i change the if statement to == "pipe and print $val it shows pipe.
Is it that the value is taking long to come over from the form and the code is being run without it? Ive been trying to figure it out any help would be appreciated.
But if i change the value of $val explicitly to pipe it works. The code below works when i change $val to pipe.
$app->post('/fdfd', function ($request, $response) {
$params = $request->getParams();
$val = "pipe";
$users = $this->db->query("SELECT * FROM `stock`")->fetchAll(PDO::FETCH_OBJ);
sleep(2);
foreach ($users as $cat) {
if ($cat->category == $val) {
$name = $cat->name;
echo "<option value='test'>$val</option>";
} else {
echo "False";
}
}
})->setName('lazyy');
See jQuery code below if needed:
$("#catId").on("change", function() {
var category = document.getElementById("catId").value
$.post("{{ path_for('lazyy') }}", {
file:category
}, function(data) {
$("#dift").html(data);
});
})

Return Named Array in Ajax Request

I am trying to pass back an array with named indexes (e. g.: data.sugg_id) for a post request. This is how my javascript / jQuery looks like:
$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
'text' : text,
'ignore_warnings' : ignore_warnings
}),
function(data) {
sugg_id = data.sugg_id;
if (data.status == 'failure') {
warning_history = {}
showMessage(errorBox, data.message);
warnBox.fadeOut("fast");
}
My submit_text.php looks like:
<?
header("Content-Type: application/json");
$unit_id = $_POST["unit_id"];
$text = $_POST["text"];
$ignore_warnings = $_POST["ignore_warnings"];
$sugg_id = 24;
//$status = "success";
$status = $text;
$message = "";
$data = array("sugg_id" => $sugg_id, "status" => $status, "message" => $message);
echo json_encode($data);
?>
I tried to use alert(data.status) but it said "undefined". What am I doing wrong?
As suggested by #A. Wolff pass dataType
$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
'text' : text,
'ignore_warnings' : ignore_warnings
}),
function(data) {
sugg_id = data.sugg_id;
if (data.status == 'failure') {
warning_history = {}
showMessage(errorBox, data.message);
warnBox.fadeOut("fast");
}
}, "json");

How can i add Dynamic Json data into a Mysql Database.

How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called
JSON_decode
I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?
Here is the data located:
http://csgo.nssgaming.com/api.php
The current script:
<?php
require_once ('simple_html_dom.php');
$html = #file_get_html('http://csgolounge.com/');
$output = array();
if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));
// Source: http://php.net/manual/en/function.strip-tags.php#86964
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE)
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
else
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
} elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
$additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;
$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;
foreach($match->find('.teamtext') as $key => $team) {
$output[$id]["teams"][$key] = array(
"name" => $team->find('b')[0]->plaintext,
"percent" => $team->find('i')[0]->plaintext
);
if(#$team->parent()->find('img')[0])
$result = array("status" => "won", "team" => $key);
}
if($additional)
$result = $additional;
if(isset($result))
$output[$id]["result"] = $result;
}
echo json_encode($output);

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Categories