Insert statement into custom WordPress database - javascript

I have a custom database that I want to insert items into from a WordPress front-end interface. When I submit the form, I can get the JSON values just fine, but for some reason, it doesn't seem to be inserting into the database. I do not get any error messages.
Here's what I'm doing (please note that I am testing the name variable, hence why it's not pulling from an input field):
I am using the auto_increment_id value from SHOW TABLE STATUS to create the commmittee_id value, and would prefer for that to be inserted as the primary key.
JavaScript
$(".addButton").click(function() {
var commitAddID = $(this).attr('id');
var name = "1name";
var date_created = $("#addCommCreated_input_"+commitAddID).val();
var status = $("#addCommStatus_input_"+commitAddID).val();
var disbanded = $("#addCommDisbanded_input_"+commitAddID).val();
var dataString = {
'action': 'addCommittee',
'committee_id': commitAddID,
'old_id': commitAddID,
'name': name,
'description': '',
'date_created': date_created,
'status': status,
'disbanded': disbanded
};
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
dataType: "json",
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
}
});
functions.php
// set up AJAX call for addCommittee
add_action('wp_ajax_addCommittee', 'addCommittee');
add_action('wp_ajax_nopriv_addCommittee', 'addCommittee');
function addCommittee() {
global $wpdb;
$committee_id = esc_sql($_POST['committee_id']);
$old_id = esc_sql($_POST['old_id']);
$name = esc_sql($_POST['name']);
$created = esc_sql($_POST['date_created']);
$status = esc_sql($_POST['status']);
$disbanded = esc_sql($_POST['disbanded']);
$desc= esc_sql($_POST['description']);
$wpdb->insert('wp_bubu_committees',
array(
'old_id' => '',
'name' => $name,
'description' => '',
'date_created' => $created,
'status' => $status,
'disbanded' => $disbanded
)
);
exit();
}
I have also localized the AJAX URL in functions.php. Any ideas?
Edit: Updated the code-- the action was set to the . I now am able to insert into the database, but it only allows me to insert one item. Attempting to insert additional items returns nothing, but the data does post to JSON.

Remove the data type json.
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
alert(response);
}
});

Related

Get tag, custom taxonomy and attachment data from get_pages function

I currently have some code which retrieves all pages submitted by the currently logged in author using the get_pages function. I am then passing the result to Javascript via Ajax. Everything works as expected, and I'm retrieving the pages that I should be.
My issue is, the object does not have any data for the tags, other custom taxonomies and attachments on this page.
Is there a way to attach this data to the returned object?
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxpages = get_pages($args);
echo json_encode($ajaxpages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
}
});
At this point, each entry will return something like:
ID: 100
comment_count: "0"
comment_status: "open"
filter: "raw"
guid: "https://example.com/?page_id=100"
menu_order: 0
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: "This is the post content"
post_content_filtered: ""
post_date: "2021-06-18 10:00:00"
post_date_gmt: "0000-00-00 00:00:00"
post_excerpt: "This is the excerpt"
post_mime_type: ""
post_modified: "2021-06-18 10:00:00"
post_modified_gmt: "0000-00-00 00:00:00"
post_name: ""
post_parent: 19
post_password: ""
post_status: "pending"
post_title: "Example page"
post_type: "page"
to_ping: ""
I would like it to also include data along the lines of:
tags: "example, test"
myCustomTaxonomy: "extra information, more data"
attachments: "https://example.com/wp-content/uploads/2021/06/myImage.png"
Is this possible?
In case it's useful, this is the solution I came up with. It certainly may not be efficient but it appears to suit my purposes at least.
What I ended up doing was populating a select list with each of the pages found in the first AJAX call. Selecting a page in this list then calls the second function which gets the various extra metadata for that page.
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxPages = get_pages($args);
echo json_encode($ajaxPages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
function get_ajax_meta()
{
$editId = $_POST['editId'];
$meta = [];
$editTags = get_the_tags($editId);
$editCustomTaxonomy1 = get_the_terms($editId, 'CustomTaxonomy1');
$editCustomTaxonomy2 = get_the_terms($editId, 'CustomTaxonomy2');
$media = get_attached_media('', $editId);
array_push($meta, (object)[
'tags' => $editTags,
'customTaxonomy1' => $customTaxonomy1,
'customTaxonomy1' => $customTaxonomy2,
'media' => $media
]);
echo json_encode($meta);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_meta', 'get_ajax_meta');
add_action('wp_ajax_nopriv_get_ajax_meta', 'get_ajax_meta');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
// populate the dropdown with the pages
if (pageList.length > 0) {
for (var i = 0; i < pageList.length; i++) {
$("select[name=edit-page]").append("<option value='" + pageList[i].ID + "'>" + pageList[i].post_title + "</option>");
}
}
}
});
$("body").on("change", "select[name=edit-page]", function () {
editId = $(this).val();
// get the meta information of the selected page (tags, custom taxonomies, attached files)
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { "editId": editId, action: "get_ajax_meta" },
success: function (response) {
pageMeta = response;
// get the tags
console.log(pageMeta[0].tags[i].name)
// get custom taxonomy 1 data
console.log(pageMeta[0].customTaxonomy1[i].name)
// get custom taxonomy 2 data
console.log(pageMeta[0].customTaxonomy2[i].name)
// get attached file data
if (Object.keys(pageMeta[0].media).length > 0) {
for (var i = 0; i < Object.keys(pageMeta[0].media).length; i++) {
console.log(pageMeta[0].media[Object.keys(pageMeta[i].media)[0]]);
}
}
}
});
});

when i pass static data it will be store data successfull.when i pass dynamic it will not store data.how to pass dynamic data

when i passed static it will be succefull stored in data base. when i pass dynamic data it will not stored in database.in my view form id is signupform which have 5 fields.
here is my .js file
$(document).on("submit","#signupform",function(e){
e.preventDefault();
//var view_id=$("#id_hid").val();
//alert(view_id);
console.log($('#signupform').serialize());
var data = {'username' : 'username' , 'password' : 'password' , 'email' : 'email' , 'mobileno' : 'mobileno' , 'address' : 'address' };
data = $('#signupform').serialize() + '&' + $.param(data);
$.ajax({
type:"POST",
data:data,//$('#signupform').serialize(),
dataType: "JSON",
url:"../welcome/add",
success:function(data){
//var json=$.parseJSON(data);
//$('#signupform').html(response);
alert(data);
}
});
});
** Here is my controller file**
public function add(){
$data=array();
$postData=array();
//prepare post data
$postData = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'mobileno' => $this->input->post('mobileno'),
'address' => $this->input->post('address')
);
//print_r($postData);
//insert post data
$insert = $this->home_model->insert_form($postData);
$data['msg']= "data insert successfully";
echo json_encode($data['msg']);
}
Here is my model file
function insert_form($data){
$insert=$this->db->insert('emp',$data);
if($insert){
return $this->db->insert_id();
} else {
return false;
}
echo json_encode($data);
}
If you want to post a string data, you can remove dataType: "JSON"
Or you can use this method
$(document).on('submit', '#signupform', function (e) {
e.preventDefault();
var data = {username: 'username', password: 'password', email: 'email', mobileno: 'mobileno', address: 'address'};
data = Object.assign({}, $('#signupform').serializeArray()[0], data);
console.log(data);
$.post('your backend url', data, function (result) {
console.log(result);
})
})
You don't need to define the data object. The serialize() method would do that for you. But, because you are making a POST you should use serializeArray() instead. serialize() is geared toward GET requests.
$(document).on("submit","#signupform",function(e){
var data;
e.preventDefault();
data = $('#signupform').serializeArray();
$.ajax({
type:"POST",
data:data,
dataType: "JSON",
url:"../welcome/add",
success:function(data){
//data is an object. If you want the text returned use data.msg
//$('#some-message-div').text(data.msg);
console.log(data); //an object with one property - 'msg'
}
});
});
The controller method can be simplified a lot. Because the field names exactly match the table column names there is no need to build the $postData array. The posted data already has that exact structure. $this->input->post() will return what you need.
public function add()
{
//insert post data
if($this->home_model->insert_form($this->input->post()))
{
$data['msg'] = "data insert successfully";
}
else
{
$data['msg'] = "insert failed";
}
echo json_encode($data);
}
The model can be much cleaner.
function insert_form($data)
{
if($this->db->insert('emp', $data))
{
return $this->db->insert_id();
}
//don't need else when the if condition calls return
return false;
}
The line echo json_encode($data); served no purpose. The way it was coded that line never executed - both the if and else blocks returned. Even if it did execute, it's the wrong thing for a model to do.

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)

$_POST empty after ajax post called

So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].

Categories

Resources