I'm sending an serialize ajax post request.
$.ajax({
type: 'post',
url: 'js/json.php',
data:{
'a': 'JRNLHDR-SAVE',
'formdata':$(_tr).find('[name^="formdata_jrnlhdr"]').serialize(),
},
success: function (data){
console.log(data);
},
error: function (er){
console.log(er);
}
});
Json data is correct
Array
(
[formdata_jrnlhdr] => Array
(
[153] => Array
(
[txid] => 153
[reference] => PH/21/JB0161
[description] => Adjustment Entry
)
)
)
I'm trying to read the data in php but it giving an error
Undefined index: txid, reference and description
foreach($journal_entry as $keys => $val){
print_r( $val['txid'] . $val['reference'] . $val['description'] );
}
That fault, because you miss your child array [153] .. and you call $keys in foreach, but still not using it.
Try this:
foreach($journal_entry as $val){
print_r( $val[153]['txid'] . $val[153]['reference'] . $val[153]['description'] );
}
Edit...
For dynamic array index, use this:
foreach($journal_entry as $key => $val){
print_r( $val[$key]['txid'] . $val[$key]['reference'] . $val[$key]['description'] );
}
Related
I am trying to query the WP Database but I am receiving an error of Call to a member function get_results() on null. I believe I need to somehow register wpdb but despite reading through multiple similar questions I can't piece together what needs to be done. Any help is greatly appreciated as I am new and learning Wordpress and Ajax.
My JS file is called zip-search-popup.js
(function($) {
$(document).ready(function() {
$('.zip-bar-button').click(function(event) {
event.preventDefault();
submittedZip = $("#zipcode-bar-input").val();
$.ajax({
//need an automatic URL so that this doesn't need to be updated
url: from_php.ajax_url,
type: "GET",
data: {
action : 'zip_search',
submittedZip : submittedZip,
},
success: function (response) {
console.log(response);
alert("working");
}
})
$('.zip-search-popup-con').fadeToggle(350);
})
$('.zip-search-dismiss').click(function() {
$('.zip-search-popup-con').toggle();
})
})
})(jQuery);
I have registered my scripts in functions.php and have my SQL query function within here as well.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//hook zip-search-popup function into ajax
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
//same hook for users not logged in
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
//query for pulling in shipping data
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
global $wpdb;
// The SQL query
$response = $wpdb-> get_results("SELECT {$wpdb->prefix}woocommerce_shipping_zones.zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"INNER JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON {$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id ".
"WHERE location_code = '$submittedZip' ");
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
);
wp_send_json( $response );
// echo $response;
die();
}
You should use the Wordpress-Way to use AJAX
All Ajax-Request will be recieved by wp-admin/admin-ajax.php which fires the Ajax-Hooks which run your PHP-Code. The Ajax-Hook depends from the action-parameter in your Ajax-Request.
With wp_localize_script() you can provide some data from PHP to Javascript, i.e. the ajax_url.
Place this code in your functions.php. This include the code that handles your Ajax-Request.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
// do some zip search
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
'foo' => 'bar'
);
wp_send_json( $response );
}
Now you can use the ajax_url provided by wp_localize_script(). Don't forget to send an action-parameter:
$.ajax({
url: from_php.ajax_url,
type: "GET",
data: {
action: 'zip_search',
submittedZip: submittedZip
},
success: function (response) {
console.log(response);
alert('it works');
}
});
I have a custom function that outputs a Json
However the Json Output has always quotes added and is thus unvalid.
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
return print_r($result, true);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
The result I get is: "[{\"bus_id\":\"BC025\",\"traject_id\":\"D\",\"traject_show\":[[\"06:00-08:16\"]]}]"
I just replaced the $result with a teststring. It is exactly same format that comes through the function.
How to get rid of those outer quotes?
function my_callback( $data ) {
$zz999_ids = do_shortcode('[wpv-view name="json-zz999-ids"]');
//$result = do_shortcode('[wpv-view name="json-traject-bus" ids="'.$zz999_ids.'"]');
$result = '[{"bus_id":"BC025","traject_id":"D","traject_show":[["06:00-08:16"]]}]';
$result = json_decode($result);
return $result;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2', '/traject2/', array(
'methods' => 'GET',
'callback' => 'my_callback',
) );
} );
For you better understanding about json_decode please visit here
I am getting the data from DB as array and then outputting them as a JSON.
Some parts of my code:
private function getUsers( ){
$users = $this->db->resource(dbMapper::USER);
return $this->usersToArray( $users );}
private function usersToArray( $users ){
$result = array( );
foreach ($users as $user){
$result[] = array(
'id' => intval( $user->get('id') ),
'name' => $user->get('name')
);
}
return $result;
}
public function getAllData( ){
$result = array( );
$result['users'] = $this->getUsers( );
$results = print_r($result['users'], true); echo $results;
return $result;
}
and then I get the JSON from this result:
$data = $model->getAllData( );
$this->_helper->json( $data );
The JSON output looks like this (I removed the data for debugging), but even if there are no data I have a syntax error in first letter of Array:
In my browser I got this: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
and if I put that JSOn to JSON validator, I got this:
Parse error on line 1:
Array( [0] => A
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
)
Not sure what is wrong with the Array in JSON...
The issue was with incorrect characters in the username field in DB, that caused the JSON error.
When doing
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
The response is
)]}'
["uvresp","03AJpayVHarkP_b40i5...stuff...VOrIy6m3ws",1,120]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The )]}' breaks things. I have no idea where that is coming from.
$g_recaptcha_response looks fine to me (what I am sending to google to verify).
The function to verify recaptcha
function verify_recaptcha ($g_recaptcha_response, $remote_address) {
# Verify captcha
$post_data = http_build_query(
array(
'secret' => 'secret',
'response' => $g_recaptcha_response,
'remoteip' => $remote_address
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
return $result->success;
}
Thanks.
Ok my bad. The above code works, I had a problem further downstream (query was trying to use a column that did not exist).
I'm using CakePHP v2.2.1 stable. I have a UsersController with the action add(). I'm trying to send the user info via ajax (from the home page to /users/add) and save the data. My code is something like this:
// /app/View/Pages/home.ctp
<?php
$data = array('User' => array('username' => 'vegeta_super_sayajin',
'password' => 'over9000!', 'email' => 'vegeta#supersayajin.com',
'profile_pic' => '/home/pics/scouter.jpg', 'firstname' => 'Vegeta',
'lastname' => 'Vegeta', 'level_id' => '9001'));
?>
<script type="text/javascript">
var data = <?php echo json_encode($data); ?> //convert $data into json format
$.ajax({url: '/users/add', data: "data="+data, type: 'post'});
</script>
How do I receive this data in the UsersController, so that I can process and save it?
Currently, I'm trying:
// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
//returns "Error: [object Object] in logfile
$this->log($this->request->data);
} else {
$this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}
$this->log($this->request->data) returns Error: [object Object] in the /app/tmp/logs/error.log file, and this user info does not exist in any of $this->request->params's indexes. All my googling so far has returned only complicated cakephp v1.3 techniques. How is this done in cakephp v2.2.1?
You can try the following code. It will work for you.
<?php
$data = array(
'User' => array(
'username' => 'vegeta_super_sayajin',
'password' => 'over9000!',
'email' => 'vegeta#supersayajin.com',
'profile_pic' => '/home/pics/scouter.jpg',
'firstname' => 'Vegeta',
'lastname' => 'Vegeta',
'level_id' => '9001')
);
?>
<script type="text/javascript">
var data = [<?php echo json_encode($data); ?>] //convert $data into json format
$.ajax({
url: 'checks/add',
data: "data="+JSON.stringify(data),
type: 'post'});
</script>
And in your controller's code:
// /app/Controller/UsersController.php
function add() {
if($this->request->is('post') {
$this->log(json_encode($this->request->data, true)); //returns "Error: [object Object] in logfile
} else {
$this->Session->setFlash(__("The user could not be saved :("));
}
$this->autoRender = false;
}
Here is the json_decode documentation. The second parameter true will convert the object into an array.