send datas to php with ajax - Internal Server Error(500) - php

i try to send my datas to php with ajax but there's strange mistake.
this is my ajax script,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert(response);
});
}
i think this works correctly but in php side, i face 500 internal server error(500).
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
Above code is my php. For example, when i try to send $data to ajax,
i print my ids in json mode:
However, when i try to send $artistIds to ajax side, i gives 500 error why?

Selam :)
Right should be:
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json, true);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
look at json_decode(). If you wanna use this as an array, you have to set the second parameter to true, otherwise use $data->{'artistIds'}; :)

try something like this and see if you get a response.
$.getJSON('/json/crewonly/deleteDataAjax2',
{ 'artistIds' : artistIds },
function(response){
alert(response);
});
public function deleteDataAjax2() {
$json = $_REQUEST['artistIds'];
$data = json_decode($json);
var_dump($data);die(null);
}

Related

API callback response

I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing
If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...

How to pass JSON response from Controller back to AJAX success method in Laravel 5.4

I have a calling js script
setInterval(function(){
$.get( "/fetch-data", function( data ) {
console.log(data);
});
},1000);
and my Routes look like this
Route::get('/fetch-data', 'PageController#fetchData');
my controller method
public function fetchData()
{
$results_array = [];
$file = new \SplFileObject('file.csv');
$file->setFlags(\SplFileObject::READ_CSV);
foreach ($file as $row) {
$results_array[] = $row[0];
$results_array[] = $row[1];
$results_array[] = $row[2];
$results_array[] = $row[3];
...
}
return response()->json($results_array);
//$json = response()->json($results_array);
//return view('view.blade',compact($json));
}
Note that with return response()->json($results_array); the raw json text is displayed directly on the page. Not what I want.
While return view('view.blade',compact($json)); returns the whole html file. Still not what I want.
What I would like to achieve is that the raw json text that was returned from the controller be pass to the callback from the calling js script.
Any ideas?
The code works as expected.
setInterval(function(){
$.get( "/fetch-data", function( data ) {
// code now works
});
},1000);
and this question was answered HERE already.

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

Ajax and php - sending javascript array to php

i try to send data to my php scripts but i think i miss something.
First of all,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2', JSON.stringify({'artistIds': artistIds}),function(response){
if(response=='ok')
alert(artistIds);
});
}
Above code is my js file. i have artistIds in var artistIds. My goal is sending this array to my php script.In order to that, i make it json , i mean encode it with JSON.stringify
then in php side, i use below code.However, $array is always null. What might be the reason ?
public function deleteDataAjax2() {
$array=json_decode($_POST['artistIds']);
if (isset($array))
$this->sendJSONResponse('ok');
}
You are passing the data as a raw string of JSON, but your PHP is trying to find that string by parsing the data as application/x-www-form-urlencoded and then looking at the artistIds key.
Assuming the array is flat: Forget JSON. You don't need it.
$.post('/json/crewonly/deleteDataAjax2', {'artistIds': artistIds},function(response){
And:
$array = $_POST['artistIds'];
If the array isn't flat, then:
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
And (with suitable error checking added):
$json = $_POST['json'];
$data = json_decode($json);
$artists = $data['artistIds'];

Jquery post call back not works

Hi my jQuery callback function does not work.
Competitor = {
addCompetitorForSave: function($data) {
$.post('/competition/add', $data , function($json) {
}, 'json');
return $json; // I need to return json data .
}
}
after this I need to do next .
var data = $('someForm').serialize();
var $json = Competition.addCompetitorForSave(data);
Thanks a lot.
The post completes asynchronously but the alert runs synchronously. Hence the qa value hasn't been set yet. Instead of return a value here you need to pass an additional callback into addCompetitorForSave.
addCompetitorForSave: function($data, callback) {
var qa = 0;
$.post('/competition/add', $data , function($json) {
callback($json);
}, 'json');
}
var obj = ...;
obj.addCompetitorForSave(theData, function(qa) {
alert(qa);
});
The alert is called before the post has had a chance to complete. Put the alert inside the callback.
try:
addCompetitorForSave: function($data) {
var qa = 0;
$.post('/competition/add', $data , function($json) {
qa = $json; //this does not work
alert(qa); //getting 0;
}, 'json');
return qa;
}

Categories