How to convert Javascript JSON.stringify() to PHP Array - javascript

I've been banging my head against the wall for 2 days now, searching back and forth for solution for this problem, please enlighten me with this one:
I have this JavaScript Code that include a blade file and pass a data through it.
const loadTemplate = (locationinfo) => {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
#include('pages/business-space/templates/t1',[
'locationinfo'=>'${JSON.stringify(locationinfo)}', //this is the code
])
</div>`;
return info;
}
When I log JSON.stringify(locationinfo) in my console it is just a plain json string:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
In my t1.blade.php if I echo the locationinfo variable it still displays the same:
echo $locationinfo;
//and the result:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
But When I tried to decode it using json_decode it becomes null. Here is my code:
$arr = json_decode($locationinfo); //this is null
foreach ($arr as $key => $value) {
echo $key;
}
Another Error:
$arr = json_decode($locationinfo, true);
foreach ($arr as $key => $value) {
echo $key;
}
//error: foreach() argument must be of type array|object, null given
Why is this happening? Thanks in advance.

First make sure that $locationinfo is exactly a json string. I suspect it is a php associative array.
Try echo $locationinfo['id'];. If value appears u don't want to decode it. Use
$locationinfo directly withot json decode.
If it is a json, Try using like this,
$arr = json_decode($locationinfo, true);

Add a stripslashes.
$data = json_decode(stripslashes($data),true);
Demo : http://codepad.org/XX9QD3iX
Answered here : https://stackoverflow.com/a/37599821/19168006
Edit : example in demo has stdClass error, this is the working one :
http://codepad.org/lfJJu5yA

you can't pass js data to php ,because php renderd first.
but
you can call ajax and return blade to response
your ajax call
const loadTemplate = (locationinfo) => {
$.ajax({
data: {
'locationinfo': locationinfo,
},
type: "post",
url: "{{route('someRoute')}}",
success: function (data) {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
${data}
</div>`;
return info;
},
error: function () {
//has error
}
});
}
your route
Route::get('/getAjaxData', [AjaxController::class,'show']) ->name('someRoute'); // but i use __invoke controller
your controller
<?php
namespace YOUR_NAMESPACE;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function show(Request $request)
{
$data = $request->input('locationinfo');
return view('pages/business-space/templates/t1')->with([
'locationinfo' => $data,
]);
}
}

Related

CakePHP can't get ajax GET working

I can't seem to get AJAX POST or GET working with my CAKEPHP site. I am trying to create autocomplete but can't seem to submit or fetch the data using ajax. I can get auto complete working using tags but I cannot display the data from my table. I am not sure what is going wrong if i'm not using the right url or some other problem.
Here is my search.ctp
<?php use Cake\Routing\Router; ?>
<?php echo $this->Form->input('id', ['type' => 'text']); ?>
<script>
$.ajax({
type: "POST",
url: "<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});
</script>
Here is my search function in my InvoicesController.
public function search()
{
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax'))
{
$name = $this->request->query['term'];
$resultArr = $this->Invoices
->find()
->where(
['Invoices.id LIKE' => ($name . '%')],
['Invoices.id' => 'string']
);
$resultsArr = [];
foreach ($resultArr as $result)
{
$resultsArr[] = (strval($result['id']));
}
$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', ['resultsArr']);
}
}
This is the error that is produced when I try to type in an ID.
This is what i want to produce which I have been able to do by using an array in search.ctp
and here is my table I am trying to fetch the IDs from.
There are two methods.
$this->request->query('term');
$_REQUEST['term'];

How to show AJAX response data inside div

I am using Laravel framework. I get stuck on this. I get data successfully. But, when I want to display the data, it displays me data in array form. Can anyone help me how to display the Listing. I have one layout inside div
<div class="col-md-9 col-sm-9 col-xs-12" id="ajaxListings">
#include('layouts.publicLayout.get-listings')// here i have implemented layout
</div>
and
function filteredlistings(){
$.ajax({
url:'search-listings',
data:{
'service_name':title,
'location':location
},
type:"get",
success:function(allData)
{
$("#ajaxListings").html(allData);
},
error: function()
{
alert('error');
}
});
}
And here is my function :
public function search_listings(Request $request){
if($request->ajax()){
$data = $_GET;
$users = DB::table('users')
->join('business_services', 'users.id', '=', 'business_services.user_id')
->join('listings','users.id', '=', 'listings.user_id')
->select('users.id', 'business_services.name', 'business_services.list_id','listings.location')
->where(['business_services.name'=>$data['service_name'],'users.service_name'=>"Seller"])
->where('listings.location','like','%'.$data['location'].'%')
->get();
$users = json_decode(json_encode($users),true);
foreach($users as $alluser){
$ids[] = $alluser['id'];
}
$allData="";
if(!empty($ids)){
$allData = User::with('listings')->whereIn('id',$ids)->get();
$allData = json_decode(json_encode($allData),true);
}
$title = "Nails";
echo "<pre>"; print_r($allData); die;
}
}
Iguess that you want to return the layout + the data, so you could use :
return view('layouts.publicLayout.get-listings',compact('allData'));
Instead of :
echo "<pre>"; print_r($allData); die;
You could access your data inside the layout using $allData.
Hope this helps.
The issue is this:
echo "<pre>"; print_r($allData); die;
Instead of print_r, return the data as JSON so that it can be parsed by jQuery:
return response()->json($allData);
Then in your jQuery success function you can iterate over the data
success:function(allData)
{
// simple example showing the firstnames
var example = '';
$.each(allData, function(){
example += ', ' + this.firstname;
});
$("#ajaxListings").text(example);
},

How to get multiple return value from php by javaScript / jquery?

This is my javaScript code :
$(document).ready(function() {
$('#IMDB').click(function() {
var MovieID = $('#MovieID').val();
$.post('action/action.php', { url: "http://api.themoviedb.org/3/movie/"+MovieID
+"?append_to_response=credits,images&api_key=myapikey" }, function(data) {
$("#test").html(data);
});
});
});
When I click the button I get imdb id from my input field which I inserted
then I get the actual result from php. this is my php code.
<?php
$url = $_POST['url'];
$url2 = file_get_contents($url);
$json = json_decode($url2, true); //This will convert it to an array
$title = $json['original_title'];
$imdb = $json['imdb_id'];
echo $title;
echo $imdb;
return true;
?>
But I get result like this :
Batman: The Killing Jokett4853102
One is movie title and another is imdb id in same html tage. but I want to display my each result in each html tag like this :
$("#test").html(data); // result 1 -- movie title
$("#test2").html(data); // result 2 --- imdb id
Please help me how to get multiple value?
It would probably be easiest just to output the entire JSON structure and work with that in Javascript, but if you just want the title and id, change your individual echo calls to one with a hash:
header('Content-Type: application/json');
echo json_encode(array(
'title' => $title,
'id' => $imdb
));
Then you can reference them in your javascript using:
var id = data.id;
var title = data.title;
You could simply return an array instead of separated values :
return json_encode([$title,$imdb]);
Then in your js parse the returned data and pluck the attributes you want from it :
data = JSON.parse(data);
$("#test").html(data[0]);
$("#test2").html(data[1]);
Or you could add json to the $.post request the you don't have to parse the returned data :
$.post('action/action.php', { url: ...}, function(data) {
$("#test").html(data[0]);
$("#test2").html(data[1]);
}, "json");
//__^^^^__
Hope this helps.

My AJAX function works correctly, but sometimes I get a JSON object undefined

i am building the next interface:
as you can see, this interface has two links shown as buttons, one to add products and the other one to rest products.
when i click in the link "addProduct" then it calculates the new total which is shown in the following interface:
The code involved in this operation, involves 2 files:
JQuery Ajax File:
$.ajax({
async:true,
type:"POST",
url: "masProducto.php",
datatype:"JSON",
data: {
tecantidad: tecantidad.val(),
valorId:id
},
success:function (jsonStr) {
var cantidad=jsonStr.cantidad;
var fila=$("#ticket_"+jsonStr.id);
var tetotal=fila.find(".precioTotal");
var teprecio=parseFloat(fila.find("input[type=hidden]").val());
var teCosteTotal=$("#importeTotal");
teCosteTotal.text(jsonStr.total+"€");
tetotal.text(teprecio*cantidad+"€");
var resumenTotal=$("#resumenTicket td:nth-child(3)");
resumenTotal.text(jsonStr.total+"€");
var resumenNumProductos=$("#resumenTicket td:nth-child(1)");
resumenNumProductos.text(jsonStr.numTotalProductos+" Items en la cesta");
},
error:function(err){
alert(err);
},
timeout:4000
});
The file masProducto.php where the JSON object is built:
<?php
include 'functions.php';
include('./ShoppingCart.php');
include('./Item.php');
sec_session_start(); //Nuestra manera personalizada segura de iniciar sesión php.
if (!isset($_SESSION['cesta'])){
header('Location: ./login.php?error=1');
}
else {
$cesta=new ShoppingCart();
$cesta=unserialize($_SESSION['cesta']);
}
header('Content-Type: application/json');
$listaItems=$cesta->getItems();
$numEltos=$cesta->count();
$tecantidad=$_POST['tecantidad'];
$id=$_POST['valorId'];
foreach ($listaItems as $celda){
if($id===$celda['item']->getId()){
$cesta->updateItem($celda['item'],$tecantidad);
}
}
$_SESSION['cesta']=serialize($cesta);
if(isset($id)){
$data = array(
"cantidad" => $tecantidad,
"id" => $id,
"total" => $cesta->calcularTotal(),
"numTotalProductos" => $numEltos
);
echo json_encode($data);
}
?>
I am using PHP OOP, and i use to objects for my shopping basket which are the "Soppingcart" and "Item".
My problem is that this code works right, but when i click fast to the plus (or rest button), it gives me back an undefined object.
I would apreciate if some could help me, because i dont even know how to look for the solution for this problem.
for more details you can enter in this website www.galeonweb.es/Index.php, where if you loggin with "test#example.com" and password "123456" you can see what is my problem better.
Thank you in advance
First off this line is pretty bad practice
if (!isset($_SESSION['cesta'])){
header('Location: ./login.php?error=1');
}
You should rather have something like
if (!isset($_SESSION['cesta'])){
echo json_encode(array(code => 2, message => 'Session invalid'));
}
And redirect the user to the login page from jQuery.
You would then need to modify the rest accordingly
if(isset($id)){
$data = array(
"code" => 0,
"message" => "Success",
"data" => array(
"cantidad" => $tecantidad,
"id" => $id,
"total" => $cesta->calcularTotal(),
"numTotalProductos" => $numEltos
)
);
echo json_encode($data);
}
I would also add the following to that
else {
echo json_encode(array('code' => 1, 'message' => 'Item not found' ));
}
Furthermore rather than test if an id is passed at the very end I would do
if(isset($id)){
$found = false;
foreach ($listaItems as $celda){
if($id===$celda['item']->getId()){
$cesta->updateItem($celda['item'],$tecantidad);
$found = true;
}
}
}
else
{
echo json_encode(array(code => 1, message => 'Fatal error, id not set'));
}
And replace
if(isset($id)){
$data = array(
With
if($found === true){
$data = array(
You'll of course have to adapt your javascript accordingly to parse the response.
Those changes should give you a better idea of what is going wrong. But, as I said in my comment, using a debug tool like Firebug will also go a long way.
Have you tried non async?
$.ajax({
async:false,
type:"POST",
url: "masProducto.php",
datatype:"JSON",
...

Jquery autocomplete with Ajax from PHP not working

The following ajax call
var whatever = [];
$.ajax({
url: "myScript.php",
success: function (response) {
whatever = response.split(",");
}
});
is generating:
"ABC,DEF,GHI,JKL,"
Which are the values I want to use in JQuery autocomplete:
$('#conta').autocomplete({
source:whatever
});
However, nothing is displayed in the autocomplete popup.
If I type the values directly in JS, it works perfectly:
var whatever=[
"ABC",
"DEF","GHI","JKL"
];
But why isn't it working when generated by PHP?
try put $('#conta').autocomplete({
source:whatever
});
in the success callback function
In your source your php array needs to have rows with a "label" key like this:
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Also if your database rows are not encoded in utf8 you need to encode them otherwise it will be "null":
$results[] = array('label' => utf8_encode($key['nome']));
UPDATE:
myScript.php:
...
foreach($rows as $key)
{
$results[] = array('label' => ($key['nome']));
}
echo json_encode($results);
Javascript:
$(function(){
$('#conta').autocomplete({
source:"myScript.php"
});
});

Categories