Im having some trouble here with a website im trying to renew.
In the head a script is called with the name "jquery.script.js" with some code
$.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json',
success: function(data){
fanarturl = data['url'];
alert(fanarturl);
alert(data.toSource());
if (data) {
$('#background').fadeOut(500, function(){
$(this).delay(100).attr('src', 'cache/'+movie_id+'_f.jpg');
$(this).fadeIn(500);
})
}
}
});
So this call's a file with the name "function.js.php".
if ($option == 'urlget') {
require('function.php');
$fan = get_fanart($mysql_tables, $_GET['id']);
$fan_js = array(
'url' => (isset($fan['url']) ? $fan['url'] : ''),
);
echo json_encode($fan_js);
}
And this call's a function with is:
function get_fanart($mysql_tables, $movie_id) {
$pos = strrpos($movie_id, "_");
$MovieID = substr($movie_id, ($pos + 1));
if(is_numeric($MovieID)){
$img_sql = 'SELECT id, url FROM ' . $mysql_tables[5]. ' WHERE type="fanart" AND id="'.$MovieID.'"';
$img_result = #mysql_query($img_sql);
if ($img_result) {
$get_img = mysql_fetch_assoc($img_result);
foreach($get_img as $key => $val) {
$fanart[$key] = $val;
}
}
return $fanart;
}}
The alart of the "jquery.script.js" show's : ({url:""})
Now the supid thing is that when I copy the code from "function.js.php" to "index.php"
It show's this: {"url":"http://image.tmdb.org/t/p/original/A82GPC0XeoZMBWDYTe4Dba32cme.jpg"}
Why is this URL not passed on to the "jquery.script.js" file?
Thanks in advance!
At the start of function.js.php you've got this:
if ($option == 'urlget') {
It shouldn't be $option, it should be $_GET['option']. (Or something like that - my PHP is a little rusty.)
Admittedly this sort of answer is more suited to codereview.stackexchange.com but your code has tons of ambiguities and a security vulnerability.
var promise = $.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json'
});
// This makes for better readability than a nest of callbacks
promise.done(function(data){
console.log(data);
$('#background').fadeOut(500, function(){
$(this).delay(100)
.attr('src', 'cache/'+movie_id+'_f.jpg')
.fadeIn(500);
});
});
promise.fail(function(data){
console.log('oh noes!', data); // #todo what do we do when 'function.js.php' fails?
});
function.js.php. Notice that we return different HTTP response codes depending on the results.
// #todo fill in db credentials
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$option = $_GET('option');
if ($option === 'urlget') {
require('function.php');
$fan_art = get_fanart($mysql_tables, intval($_GET['id']), $db);
if ($fan_art && count($fan_art)) {
http_response_code(200);
echo json_encode($fan_art);
} else if (is_array($fan_art)) {
http_response_code(404);
echo json_encode(array('errors' => array('no fan_art found')));
} else {
http_response_code(500);
echo json_encode(array('errors' => array('an error occured when fetching fan art')));
}
}
function.php. Notice that here we pass in the database connection and use bound parameters to insert variables into our SQL.
/**
*
* #param [String] $table - the table to fetch data from
* #param [Int] $movie_id
* #param [PDO] $db - A PDO database connection
* #return [False, Array] Returns false if query fails, otherwise returns array of results
*/
function get_fanart($table, $movie_id, $db) {
$statement = $db->prepare( "SELECT id, url FROM :table WHERE type = 'fanart' AND id = :id" );
$sth->bindParam(':table', $table); // default param type is string
$sth->bindParam(':id', $movie_id, PDO::PARAM_INT);
if ( $sth->execute() ) {
return $sth->fetchAll();
} else {
return false;
}
}
On a side comment, your file & variable naming scheme is pretty horrible. Naming a file .js.php implies that the PHP file renders javascript. Also naming your files function or functions is a maintainence nightmare - why not fan_art.json.php and fan_art.php.
Related
How do you run Classes from an external file from the functions.php?
I'm using WordPress and the Beaver Builder plugin. I have a pagination list with info from the WP db. This is on a page using a search template (search.php). It includes a file (get-jobs.php). In order to see the results, I have to use a PHP Snippet plugin to set a global variable on the page that recognizes the $result variable provided by get-jobs.php, as I use the built-in modules to layout the page.
This works so far. I can see my formatted results.
When the pagination button is clicked, a function is called from my js file(custom-script.js) to update the results.
function selectJobs() {
$.ajax({
url: site_url + '/get-jobs.php',
type: "GET",
data: {
ajax': '1',
'state': GetURLParameter('country'),
'limit': GetURLParameter('limit')
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
This doesn't work and I received a 403(Forbidden) error. I changed it to this:
function selectJobs(country) {
var country = country;
$.ajax({
url: ajaxurl,
type: "POST",
data: {
'action':'country_ajax_request',
'country' : country
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
...which got rid of the error, and submitted the request.
In my functions.php, I have this:
function country_ajax_request() {
//include_once( get_stylesheet_directory() .'/get-jobs.php');
MY FUNCTIONS GO HERE
}
add_action( 'wp_ajax_country_ajax_request', 'country_ajax_request' );
add_action( 'wp_ajax_nopriv_country_ajax_request', 'country_ajax_request' );
Here's an bit of what's in get-jobs.php:
<?php
$get = (!empty($get) ? $get : $_REQUEST);
if(isset($get['ajax']) && $get['ajax'] == 1) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
}
class GetJobs {
private $wpdb;
public function __construct($input) {
global $wpdb;
$this->wpdb = $wpdb;
$this->tableName = $this->wpdb->prefix . 'job_postings';
$this->country = (!empty($input['country']) ? $input['country'] : '');
$this->page = (!empty($input['page']) ? $input['page'] : '');
$this->limit = (!empty($input['limit']) ? $input['limit'] : 10);
}
public function getLocations() {
$result = [];
$states = $this->wpdb->get_results("SELECT country FROM " . $this->tableName . " WHERE deleted_at = '0000-00-00 00:00:00'");
foreach ($country as $key=>$row) {
$result[$row->country] = $row->country;
}
return $result;
}
// almost 200 more lines of this
}
$get['page'] = (!empty($get['page']) ? $get['page'] : 1);
$jobs = new GetJobs($get);
$query = $jobs->getQuery();
$jobsQuery = $jobs->getJobsQuery($query,(!empty($get['limit']) ? $get['limit'] : $jobs->limit));
$result['postings'] = $jobs->formatPostings($jobsQuery);
if(isset($get['ajax']) && $get['ajax'] == 1){
echo json_encode($result);
}
I tried to include the file, but that didn't work. It pulled data, but didn't seem go through the functions.
I want to reuse the existing file to perform the update list task. I don't want to rewrite get-jobs.php, if possible. I've used this same code just fine on other projects. Just not with this plugin.
Any thoughts or assistance as how I can approach this problem is appreciated.
Thanks.
UPDATE
I took another look at that include. It is pulling data. However, it's generates a json file, following by all of the html. The HTML is malformed. Here's what the beginning looks like:
<div id="postings" style="display: block;">{"states":{"AB":"AB","AZ":"AZ","BC":"BC","CA":"CA","FL":"FL","GA":"GA","IL":"IL","KS":"KS","NC":"NC","NS":"NS","ON":"ON","PA":"PA","QC":"QC","WA":"WA"},"category":{"":"","Accounting":"Accounting","Customs":"Customs","Finance":"Finance","Human Resources":"Human Resources","IT":"IT","Information Technology":"Information Technology","International":"International","Marketing":"Marketing","Marketing and Communications":"Marketing and Communications","Operations":"Operations","Project Management":"Project Management","Reception":"Reception","Sales":"Sales","Warehouse":"Warehouse"},"postings":"\n\t\t\t\t\t
I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).
I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
I want to populate my div minimal_table through ajax onchange event based on the chosen dropdown value. The <div class="minimal_table"> is the area of my page that I want to update every time I choose a value from my dropdown form. However, after my contents load, it returns no values from my database. I have checked the value being passed in my javascript using alert but it returns a right value. I also notice that it seems like it doesn't return true in the other_function.php if(isset($val_id))line even if I already chosen a value in the dropdown. Can somebody help me point out what is the wrong of my codes and what I am lacking? Thanks a lot. Here are my codes:
my_courses.php (ajax part)
$(':input').change(function(event){
event.preventDefault();
$('.minimal_table').html('<img src="../images/loading_trans.gif" style="position:relative; margin:350px; margin-top:250px;" />');
alert($(this).val());
var val_id = $(this).val();
var postData = {'val_id':val_id};
$.ajax({
url: "../includes/other_functions.php",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data){
setTimeout(function(){
$('.minimal_table').html(data);
},2000);
console.log(data);
},
});
});
other_functions.php
<?php
function ajax_request_val(){
$val_id = $_POST['val_id'];
$field = "course_type";
if(isset($val_id)){
$plans = db::getTable('plan',$field,$val_id);
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event',$field,$val_id);
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
else{
$plans = db::getTable('plan');
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event');
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
}
?>
databaseconnect.php
public static function getTable($tableName,$field='',$type_id='') {
if (!self::$db) self::connect();
if(!empty($type_id)){
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '` WHERE `'. $field .'` = `'. $type_id .'`;');
}
else{
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '`;');
}
}
Output:
Initial load
Loading the form dropdown menu search
Choosing value from dropdown returns right value indicated by an alert
After content load (returns no value on the div mini_table)
In other_functions.php you define the function ajax_request_val().
As far as I can see, there is no call to that function within the same file, so when you call it with Ajax, you just define the function and never call it.
You make an ajax call to other_functions.php but that file only contains a function that is never called.
There are lots of ways to approach this and tidy it up a bit but to fix the problem quickly you could try putting this at the top of other_functions.php:
if(isset($_POST['ajax'])){ echo ajax_request_val(); }
and then change the data in your ajax call as follows
var postData = {val_id:val_id, ajax:1 }
I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.