I would get a json (make from a db query) from a external script javascript.
my model:
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
my controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
public function getJson() {
$model = getModel();
$data = $model.getListQuery();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
JResponse::setHeader('Content-Disposition','attachment;filename="result.json"');
echo json_encode($data);
}
}
my javascript:
$.getJSON( "http://mediastore.dev/index.php?option=com_mediastore&task=getJson", function(data) {
console.log(data);
});
but the getJSON fails.
What's wrong ?
Thanks
Your controller code will throw PHP errors. It has to look like:
public function getJson() {
$model = $this->getModel();
$data = $model->getItems();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
echo json_encode($data);
JFactory::getApplication()->close();
}
Try to put the controller action to lowercase. I would also replace the $ with jQuery in your ajax call.
To see what is actually in the response of the ajax call I suggest to use firebug or the chrome developer console which will display the whole response and then you will find out very quick where the problem is.
Related
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,
]);
}
}
The Problem:
When I put a PHP file link in the browser, it works perfectly fine and updates my database as expected.
When I call it with ajax from node.js, it echoes the success message but the DB does not update.
The Session variables are undefined, so when I changed them to real numbers the code still did not work. What is going wrong?
My PHP Code:
subtract5.php:
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
session_start();
$cash_amount = $_SESSION['cash_amount'];
$userid = $_SESSION['id'];
$_SESSION['cash_amount'] -= 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount,$userid);
if($result)
{
echo $cash_amount;
}
else
{
session_start();
session_unset();
session_destroy();
}
?>
mysql.php:
<?php
class Mysql
{
protected $dsn;
protected $username;
protected $password;
public $db;
function __construct()
{
//change this to your info (myDBname, myName, myPass)
$this->dns= 'mysql:dbname=cashball_accounts;host=localhost;charset=utf8';
$this->username= 'myUser';
$this->password= 'myPass';
$this->db = new PDO($this->dns, $this->username, $this->password);
}
public function setCashAmount($cash_amount, $id)
{
$sql = "UPDATE users SET cash_amount = :cash_amount - 0.05 WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':cash_amount', $cash_amount, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$result = $stmt->execute();
return $result;
}
}
?>
My node.js (app.js) AJAX:
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
Recap:
PHP File works from site.com with the same AJAX code, and by putting its link in the browser.
PHP File is executed from node, but does not update the DB
PHP File has undefined $_SESSION variables but when replaced, the DB still does not update
Possible solutions:
Is there extra code i can put in AJAX to tell it to "pipe" the call to site.com to call the file instead of calling it straight from node?
Extra Info:
No errors in error logs or console
I need to use AJAX to input data into the file later on
Solution must be secure
Thanks for the help!
I want to call controller from ajax and send POST into database. After POST was sent, i will display database into dropdown list.
but i don't know what to do. here is my code.
ajax script inside view add_produk.php
<script>
function getId(val){
// ajax function
$.ajax({
type: "POST",
url: "<?php base_url();?>index.php/getdata",
data: "id_kategori="+val,
success: function(data){
$("#subcat").html(data);
}
});
}
</script>
i want to load controller getdata.php and send $_POST into this controller, Controller getdata.php :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Getdata extends CI_Controller
{
public function index()
{
if(!empty($_POST["id_kategori"])){
$idcat = $_POST["id_kategori"];
$sql = "SELECT * FROM sub_kategori WHERE id_kategori = $idcat";
$result = $this->db->query($sql);
foreach ($result as $subcat) {
?>
<option value="<?php echo $subcat["id_sub_kategori"];?>"><?php echo $city["nama_sub_kategori"];?></option>
<?php
}
}
}
}
?>
how i can fix my problem?
i think wrong in here data: "id_kategori="+val
i dont know php, but u can try "data:{id_kategori:val}"
good luck
I am currently working on a program that uses php jquery and bootstrap, I want to delete multiple data using checkbox. I search and found out that it must use AJAX to passing the paramater from view to controller. The Jquery work find and can get the value from checkbox. But when I use Ajax, the button not working. Nothing change. Please help me to find the problem on my code. Thank you
My Controller
public function hapusbeberapa()
{
$this->model_security->getsecurity();
$this->load->model('model_barang');
$arr = $this->input->post('data');
//$arrcode= json_encode($arr);
foreach($arr as $id)
{
$query = $this->model_barang->getID($id);
if($query->num_rows()>0)
{
$this->model_barang->getdelete($id);
//$this->session->set_flashdata('info',"Data Berhasil Dihapus");
}
}
}
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_barang extends CI_model {
public function getdelete($key)
{
$this->db->where('IDBarang',$key);
$this->db->delete('tBarang');
}
public function getID($key)
{
$this->db->where('IDBarang',$key);
$query = $this->db->get('tbarang');
return $query;
}
}
My View
<script src="<?php echo base_url();?>http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(barang/hapusbeberapa) ?>"+actMult, {data:favorite}););
});
});
</script>
</script>
use your script as:
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name=checkboxlist]:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(/barang/hapusbeberapa) ?>", {data:favorite}, function(returnData){
console.log(returnData);
});
});
});
</script>
it will work for sure,
the result will be same as you echo in controller's function, and check console log for check result, you can also check it by using alert(returnData) instead of console.log(returnData).
hope it helps
Try something like that:
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
favorite = favorite.join();
$.post
...
In Controller
$arr = $this->input->post('data');
$arr = explode(',', $arr);
I am having issues with wp_remote_get in my Wordpress plugin.
What I want to do is call a method inside my main public class with ajax. But the thing is that the call fails when the wp_remote_get function is used in it. It is supposed to do an API call and return the data to the jQuery. When I comment out the wp_remote_get the call works fine and response is given back. Any ideas how can I make this work?
Method that processes the call:
public function countryLookupApiCall() {
if (isset($_POST['action']) && isset($_POST['country'])) {
$country = $_POST['country'];
$apiKey = $this->getApiKey();
$url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
$response = wp_remote_get($url);
echo $response;
die();
}
}
jQuery:
jQuery(document).ready(function() {
jQuery("#countryLookupForm").submit(function(e){
var country = jQuery("#selectCountry").val();
var action = 'countryLookupResponse';
jQuery.ajax ({
type: 'POST',
url: countryLookup.ajaxurl,
dataType: 'json',
data: {action: action, country: country},
success: function(data) {
//do something with this data later on
var result = jQuery.parseJSON(data);
}
});
});
});
Wordpress actions are all registered well because the call works when I don't use the wp_remote_get
EDIT:
The solution was more than simple, I just needed to add e.preventDefault();
You need to add errors checking into your code. This can help you to figure out what is causing the problem.
public function countryLookupApiCall() {
if (isset($_POST['action']) && isset($_POST['country'])) {
$country = $_POST['country'];
$apiKey = $this->getApiKey();
$url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
$response = wp_remote_get($url);
if (is_wp_error($response)) {
$error_code = $response->get_error_code();
$error_message = $response->get_error_message();
$error_data = $response->get_error_data($error_code);
// Process the error here....
}
echo $response;
die();
}
}
Also you are using echo on wp_remote_get result. As defined in documentation wp_remote_get returs WP_Error or array instance. So you should use something like this:
echo $response['body'];