I am posting an array to my wordpress database. The array is generated in Javascript and I am using JSON to pass it to php. Problem is when I view the user_meta table row I am presented with the following:
Meta_Key \"test\"
Meta_Value [\"1\",\"2\",\"3\",\"4\",\"2\",\"3\",\"4\",\"5\"]
This is how it appears in the database. Here is the rest of the code.
$.ajax({
url:"readJsonSave.php",
method: "post",
data: { array: JSON.stringify( array ), buildName:
JSON.stringify(buildName) },
success: function(res){
console.log(res);
}
})
});
ReadJsonSave.php
require_once("../../../../wp-load.php");
$buildName = $_POST['buildName'];
$myBuild = $_POST['array'];
$myBuild2 = json_decode('array');
echo $myBuild2;
print_r($myBuild);
$wpdb->insert('wp_usermeta', array(
'meta_key' => $buildName,
'meta_value' => $myBuild2
),
array(
)
);
There are several issues with your code. The wp_usermeta table requires a user_id for the associated meta, which it doesn't look like you're providing.
Also, instead of using $wpdb->insert you should be using update_user_meta( $user_id, $meta_key, $meta_value ).
EDIT: You have another issue in your code. $myBuild2 = json_decode('array'); should be $myBuild2 = json_decode( $myBuild );. You're not currently decoding the post var and that is why you're getting an unserialized string in the database.
This should work. readJsonSave.php:
<?php
require_once("../../../../wp-load.php");
$myBuild = wp_unslash( $_POST['array'] );
$myBuild2 = json_decode( $myBuild );
update_user_meta( $user_id, 'test', $myBuild2 ); // Update $user_id
array: JSON.stringify(array) => it could be because your array was already converted to a string and you are trying to convert it again. Check the value of the array you are passing. Try :
$.ajax({
url:"readJsonSave.php",
method: "post",
data: { array: array , buildName: buildName },
success: function(res){
console.log(res);
}
})
Related
I developed a contact form with pure PHP and HTML. I wanna insert the input values into the database with AJAX. Here is my Javascript/jQuery code:
var email = jQuery("#email").val();
var data = {
'email': email
}
jQuery.ajax({
type: "POST",
url: "http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php",
dataType: "json",
data: data,
success : function(data) {
// do something
}
});
And my contactform.php:
$date = date('Y-m-d H:i:s');
global $wpdb;
$wpdb->insert('myTableName', array(
'email' => $_POST["email"],
'date' => $date,
));
My code works well. My question is what is the correct way to do that? Because I think it's not a good idea to create a .php file inside the WordPress theme and use it just for inserting data into the database. I think it has security issues and users can see my script URL (http://mywebsitedomain.com/wp-content/themes/mytheme/contactform.php) that used in my javascript file for using ajax.
Do you have better ways to do that?
Create a function for inserting data and also enqueue script for ajax call and pass it in url. example like:
function mytheme_admin_scripts() {
wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/admin_script.js');
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts','mytheme_admin_scripts' );
Enqueue your js file which you have wrote your ajax call and pass my_ajax_object.ajx_url in your ajax url.
jQuery.ajax({
type : "POST",
url : my_ajax_object.ajax_url,
data : data,
dataType: "json",
cache: false,
success : function(data) {
// do something
}
});
I have the following jquery function which is supposed to post data to a php function which in the process it passes it to the external script for processing.
Below is my jquery function :
function order_confirmation(json) {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>home/confirm_order_received/",
data: json,
contentType: 'application/json',
dataType: 'json',
success: function (data) {
console.log(data);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
}
This function is supposed to pass the json data to my php function which is below here :
function confirm_order_received() {
$json = $this->input->post('json');
// Initialize curl
$curl = curl_init();
$externalscriptaddress = "http://197.237.132.178/api/order/order_upsert";
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
}
I have a problem of how I am supposed to access the data from the php side, I have tried accessing it through the post : $json = $this->input->post('json'); and passed it to the CURLOPT_POSTFIELDS => $json but I get an error since nothing has been passed. Please advise how can i pass the json data to an external script?
For getting raw post data (in your case) use file_get_contents("php://input")
Instead of data: json, you should use data: "json:json",
Using just data: json, will post the data, but it will not be assigned to a key. To access the data ou need to assign it to a key. By using data: "json:json",, you can access it with $json = $this->input->post('json');
The Problem is, the json file is not showing. Im using Xampp as local Server.
php file:
$array = array(
array(
"title" => "Erster Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
),
array(
"title" => "Zweiter Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
)
);
echo json_encode($json);
html file:
$ajax({
url:'localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
}
})
JavaScript use $.ajax and then full URL.
$.ajax({
url:'http://localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
});
You also need to encode your array in your php file.
echo json_encode($array);
Use json_encode in PHP
Returns a string containing the JSON representation of value.
Use $array to json_encode instead of $json.
echo json_encode($array);
/// ^^^^^^^^^
Change $ajax to $.ajax, this will remove the error in your code, everything else works fine
You are missing JSON headers in your PHP answer, Jquery may interpret your response as plain text or HTML...
Also, you are echoing $json and your array is $array.
Try this for PHP:
header('Content-type: application/json');
$array = [["title" => "Erster Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"],["title" => "Zweiter Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"]];
echo json_encode($array);
And this on your HTML:
$.ajax({type: "POST", url: "localhost/uebung/staticfeed.php", data:data, dataType: "json", timeout: 25000, success: function (result) {
$('#feeds').html('First array:' + result.[0].title + '<br />Seccond array:' + result.[1].title );
}});
You need to select the value INSIDE the array inside [result]...
Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}
drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it
That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.