3 Replies - 213 Views - Last Post: 16 May 2020 - 10:09 AM Rate Topic: -----

#1 justawebuser   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 83
  • Joined: 09-February 14

Get data posted by $.ajax via $request argument of Controlle

Posted 16 May 2020 - 07:41 AM

I'm using the following code to post an array of objects to an api Controller.
    $.ajax({
     url: "/api/links", 
     method:"post" , 
     data:  JSON.stringify(  this.results  )  , 
     contentType: 'application/x-www-form-urlencoded',
     context:this ,
     success:
      function(res){
    	 $("#res").html(res);
       }
    });  


The problem is $_POST array is empty while I could get the raw posted data using $raw = file_get_contents("php://input").
Somebody offered to use this:

    $_POST = json_decode($rawdata, true);


It may fill the $_POST and solve the problem but I'm using Laravel so I'm supposed to use the $request (of type Request) parameter of Controller method not pure PHP.
So I think there is a right and Laravel way for handling this.

By the way $rawdata is precisely what I've posted to the controller which is something like this:
[{"id":484,"LinkTitle":"contactus","URL":"https://url1..."},{"id":485,"LinkTitle":"faq","URL":"/faq"}]

I also tried wrapping it with {} before serializing in order to make it an object:


    JSON.stringify(  {"myData":this.results}  )



This way $_POST array was filled but not in a normal way. All I want is to access LinkTitle via $_POST which means I would be able to use $request argument passed to controller's method so i can do other things like validation etc...

EDIT :
Actually it's an array of objects and not just object/array. So I can't get it via $_POST["LinkTitle"] . All I said here is because I imagine if $_POST is populated correctly then I can use $request to validate and save my records at once via eloquent.Thank you

Thanks in advance

This post has been edited by justawebuser: 16 May 2020 - 08:13 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Get data posted by $.ajax via $request argument of Controlle

#2 astonecipher   User is offline

  • Enterprise Software Architect
  • member icon

Reputation: 3150
  • View blog
  • Posts: 11,954
  • Joined: 03-December 12

Re: Get data posted by $.ajax via $request argument of Controlle

Posted 16 May 2020 - 08:28 AM

form-url and json.stringify arenít going to match.

Are you serializing?
Was This Post Helpful? 1
  • +
  • -

#3 justawebuser   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 83
  • Joined: 09-February 14

Re: Get data posted by $.ajax via $request argument of Controlle

Posted 16 May 2020 - 10:04 AM

No. I actually meant stringify and not serialization.
It took me almost one day and struggled a lot to get data correctly using $request.
Finally I gave up. I finished it using raw input. Anyway thank you.
This is the complete code for anyone interested in Laravel , Vue and Jquery:

vue.blade.php:

@extends("master")@section("content")


<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div class="container" id="app">
 
   
   <p id='res' class='alert'>  </p>
 
 
    <table class="table table-bordered table-sm">
	
	 <tr class="w-100">
	   <td>  Title </td> 
	   <td>  URL </td>
	 </tr>
         
	 <tr v-for="res in results" >
	  <td>  <input :id=res.id :value=res.LinkTitle class="w-100">  </td>
	   <td> <input :id=res.id :value=res.URL class="w-100" dir='ltr'> </td> 
	  
	 </tr>
		
     </table>
	 
	 
	 <div class='w-100 text-left'>
	   <button class="btn btn-primary" @click="saveData">Save</button>
	 </div>
 

</div>



  <script>
     const vm = new Vue({
       el: '#app',
       created: function()
       {
          this.loadData();
       },
       data: {
         results: null

       },
       methods:{

           loadData: function()
           {
                $.ajax({url: "/api/links", context:this , success: function(jres){
                     this.results = JSON.parse(jres);
               }});

           }
		   ,
		   saveData: function()
           {
		 
				$.ajax({
				 
				url: "/api/links", 
				method:"post" , 
				data:  JSON.stringify(   this.results   )  , 
				contentType: 'application/x-www-form-urlencoded;charset=utf-8',
				context:this ,
				success:
				function(res){
					  $("#res").html(res);
				},

				error:
				function(xhr,status,error)
				{
					 $("#res").html(error);
				}


			});  
					

           }
       }

     });
   </script>



@stop


api.php:
Route::post('/links',"Api\[email protected]");


WriteController.php:
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class WriteController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        
    }

   
   public function links(Request $request)
    {
		
		//I couldn't use $request

		try
		{
		    $raw = file_get_contents("php://input");
		    $links = json_decode($raw, true);
	 
		   DB::table('tbl_links')->truncate();
		
		   $index = 1;
		   foreach($links as $lnk)
		   {
			 
			   
			   $lnk = (object)$lnk;
			   if(!$lnk->LinkTitle || !$lnk->URL)
			     continue;
			 
			   
			   $link = new \App\Link();
			   $link->id = $index;
			   $link->LinkTitle = $lnk->LinkTitle;
			   $link->URL = $lnk->URL;
			   $link->save();
			   
			   $index++;
	 
			   
		   }
		 
	 
		    return \bts_alert("لینک ها بروز رسانی شدند","success");
		  
		  
		}
		catch(\Exception $e)
		{
			 return \bts_alert($e->getMessage(),"warning");
			 
		}
		 
		 
    }
}

This post has been edited by justawebuser: 16 May 2020 - 09:34 PM

Was This Post Helpful? 0
  • +
  • -

#4 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4278
  • View blog
  • Posts: 13,562
  • Joined: 08-June 10

Re: Get data posted by $.ajax via $request argument of Controlle

Posted 16 May 2020 - 10:09 AM

First, you're using the wrong content type. JSON would use application/json, not application/x-www-form-urlencoded.

Second, $_POST can only contain key-value pairs (even if the value is a compound structure), but you only have a list of objects.

I suppose that you can hook into the request flow of the Laravel framework (at least that's possible in other major frameworks) so you can do your magic there.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1