jquery AJAX call (Laravel 4 PHP): Unable to retrieve data on my Controller

Vishal Sharma
@vishal-pysGmK โ€ข Oct 8, 2024

I wrote the following code to make an AJAX post request to a function in my controller,

$.ajax({
url:"{{ URL::route('res_data') }}",
type:"POST",
data:{candidate:{{ json_encode($name)}}, ans : ans_array, stamps: timestamp,set:{{ $ques[0]->setnumber }}, total:{{ count($ques)}}}}).done(function(data){
console.log(data);}).fail(function(jqXHR, ajaxOptions, thrownError){
console.log(jqXHR);
console.log(ajaxOptions);
console.log(thrownError);});

The problem I face is the candidate key in 'data' tag.

json_encode($name)

stringify's the data, On going to the route res_data, I perform a decode to convert the data received into the object. Here's my Controller function,

publicfunction resultData(){
$res = array();
$count =0;
$res =Input::get('ans');foreach($res as $r){if($r >0)
$count = $count+1;}
$data = json_decode(Input::get('candidate'));//error on this

$entry =newResult;
$entry->id = $data->id;
$entry->name = $data->name;
$entry->gender = $data->gender;
$entry->email = $data->email;
$entry->fblink = $data->link;
$entry->submissions = $count;
$entry->setnumber =Input::get('set');
$entry->totalquestions =Input::get('total');
$entry->answers =Input::get('ans');
$entry->stamps =Input::get('stamps');
$entry->save();
return"success";
}

But, I get an error stating "json_decode() expects parameter 1 to be string, array given" The error says that the parameter is array, Hence to obtain the data as an object I tried a solution on the web and replaced the comment marked line to

$data = json_decode(json_encode(Input::get('candidate')), FALSE);

This satisfies the error I received before but now I get another error stating "preg_replace(): Parameter mismatch, pattern is a string while replacement is an array"

I don't understand this. I even tried leaving the data as array and tried accessing data as

$data['name']

but, Now another error, that says $data is non-array element. Can anyone help me with this?

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Vishal Sharma

    @vishal-pysGmK • Oct 20, 2014

    is there anyone who can at least give me a suggestion?

  • Vishal Sharma

    @vishal-pysGmK • Oct 20, 2014

    figured out ๐Ÿ˜’

  • Manish Goyal

    @manish-r2Hoep • Oct 20, 2014

    Vishal0203figured out ๐Ÿ˜’

    dataType option?

  • Kaustubh Katdare

    @thebigk • Oct 20, 2014

    Vishal0203figured out ๐Ÿ˜’

    Sorry that no concrete replies were received in time? Could you please share the fix for the readers?