What I have ?
A single product page showing customs fields to be filled before add item to cart. I have added a button which should put all the values in the custom fields in a text file and save it without reloading the page.
What is my code?
in simple.php
<input type="submit" id="ajax-order-btn" class="button" value="Place Order via AJAX" />
in functions.php
<?php
add_action('wp_head', 'ajax_call_place_order');
function ajax_call_place_order() {
if ( is_product() ){
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(document).on("click", "#ajax-order-btn" ,function(e) {
e.preventDefault();
var data = {
'action': 'ajax_order',
};
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data);
});
});
</script>
<?php
}
}
add_action('wp_ajax_ajax_order', 'ajax_order_callback_wp');
add_action( 'wp_ajax_nopriv_ajax_order', 'ajax_order_callback_wp' );
function ajax_order_callback_wp() {
$custom_fields_value = ***What Should Go Here***
file_put_contents(wp_upload_dir()['basedir'].'/orders/AJAX_TEST.txt', $custom_fields_value);
}
?>
Currently you're not sending anything to your ajax_order_callback_wp function. To do this you must get the values from the form, by selecting the form and extracting the values.
Instead of listen for the button click, listen for the submit event on the form. Preventing this default behavior will stop the form from reloading the page.
Now the $.post function is responsible for sending data to your backend, but it currently only gets an object with 'action': 'ajax_order' sent with it. It needs the data from the form as well.
jQuery has a function called serialize which can be called on a form element to extract the data from the form. Pass that form data to the data object. Now your form data is included.
jQuery(document).ready(function($) {
var $form = $('form.cart');
$form.on("submit" ,function(e) {
e.preventDefault();
var data = {
'action': 'ajax_order',
'data': $form.serialize()
};
$.post(<?php echo admin_url("admin-ajax.php"); ?>, data);
});
});
On the receiving end you can now extract the value by reading out the global $_POST variable. This variable is available in every function and will contain values if something has been sent using the POST method. In your case you used the jQuery $.post, so $_POST is the way to go.
Because the property on the object is called data you'll need to access that property on the $_POST array to see what the values are.
function ajax_order_callback_wp() {
// If data is there, use it, otherwise use an empty array.
$data = $_POST[ 'data' ] ?? [];
file_put_contents(wp_upload_dir()['basedir'] . '/orders/AJAX_TEST.txt', $data );
}
If you need to know what $data contains, then you could send a response back to the client with the contents of $data to inspect it on the frontend. Add this to end of the PHP ajax_order_callback_wp function.
wp_send_json_success( $data );
And this to your $.post function in JavaScript.
$.post(<?php echo admin_url("admin-ajax.php"); ?>, data, function(response) {
console.log(response);
});
Related
I am looking to see if it possible to post and send information to the url and receive that information in the form of a $_GET request.
This is the link that will be clicked // Note that admin.php is the current page
Update
Once this linked is pressed,
$updateQuery = mysqli_query($dbconnection, "SELECT * FROM `PRODUCT` WHERE `p_id`={$_GET['id']}");
while($row=mysqli_fetch_array($updateQuery)) {
$p_name = $row['p_name'];
};
And receive the information to be automatically entered within this input box
<input type="text" class="ipbtn" value="<?php echo $p_name; ?>" placeholder="Name" name="p_name"/>
Now I am aware that this could possibly be done through the usage of Ajax, but on the other hand, I am not sure that changing the url is possible in such a way without refreshing the page. Thank you in advance for any possible suggestions.
Put the PHP in a SEPARATE FILE and use jQuery .post() to access it. This is the only way to "stay" on the same URL, without "refreshing" And .ajax() is just shorthand for .post() -- They are interchangeable with slightly different syntax:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jquery.ajax/
admin.php
<a onClick="goAdmin();"> Update </a>
<script>
function goAdmin(){
var action = 'update' // However these will be set
var id = 1 // This is just to show you how to pass them
$.post( "admin_post.php", { id: id, update: "update" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
</script>
admin_post.php
<?php
$updateQuery = mysqli_query($dbconnection, "SELECT * FROM `PRODUCT` WHERE `p_id`={$_POST['id']}");
while($row=mysqli_fetch_array($updateQuery)) {
$p_name = $row['p_name'];
echo $p_name;
};
I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.
I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));
I'm using Codeigniter and I have a dynamically created form with lots of input fields. I'm using jQuery and AJAX to submit form and I'm passing all the data from form as an object. This is my jQuery code:
$('body').on("submit", "#app-options-form", function(evnt){
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
// Prevent form submission
evnt.preventDefault();
// Get all form inputs
var inputs = $('#app-options-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"edit_form_submited" : true, "data" : data},
function (data) {
$('.response-container').html(data.result);
}, "json");
});
I'm having difficulties with validation of that form. If I put a field name as a parameter for set_rules(), it won't work because it will look for $_POST['field_name'] but this doesn't exist. The value of this field is passed as $_POST['data']['field_name'], because I'm passing all inputs as an object called "data".
So, is there any way to validate this form?
EDIT:
My PHP code:
// Get received data, here are all the input fields as $field_name=>$field_value
$data = $this->input->post('data');
// Try no. 1 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 2 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($value, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
// Try no. 3 for setting the rules
foreach($data as $key=>$value)
{
$this->form_validation->set_rules($this->input->post('data')['$key'], 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
These are my tries to set the rules, but none of them works
I have not tested this but it should work!
$("body").on("submit", "#app-options-form", function() {
// Prevent form submission
evnt.preventDefault();
// Show loader while AJAX is loading
$('.response-container').html('<img class="response-loader" src="<?php echo base_url();?>/img/loader.gif" >');
var form = $(this).serializeArray();
var data = {data: form};
$.post("<?php echo site_url('admin/ajax_app_options'); ?>", data, function(response) {
$('.response-container').html(response.result);
}, "json");
});
When you send a serialized string using $.post it come through as an array at the other end :)
Hope this helps!
After you edit
remove var data = {data: form}; from the above
Then with php do:
foreach ($this->input->post() as $key => $value) {
$this->form_validation->set_rules($key, 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
The reason you code wouldn't work is because Form_validation will be looking for the key in the $_POST array but it would need to look inside $_POST['data'].
The other option (which would be quite pointless, but follows using the data array) would be:
$data = $this->input->post('data');
foreach ($data as $key => $value) {
$this->form_validation->set_rules("data[$key]", 'Vrijednost', 'trim|xss_clean|max_length[5]');
}
I can't say this will definitely work though.
I'm trying to achieve something relatively straightforward - allow users to make comments on a view page, update the database and display the new content dynamically on the page without the whole page refreshing.
My efforts so far have been unsuccessful - there may be several issues with what I'm doing!
On the view page I have tried this (to send 2 variables to a CI controller function):
<script type="text/javascript">
function ajax(id, user_id) {
jQuery('#dynamicdiv').load('/controller/function/' + id + '/' + user_id);
}
</script>
<div id='dynamicdiv'>
</div>
I have a textarea to collect the user comment, in the controller function should I be able to call this as post data in order to write it to the database? If so, I would still need to send two other variables ($id and $user_id) to the ajax function.
<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id')",
); ?>
<?php echo anchor(current_url(), 'Post my Comment', $atts); ?>
and in the controller, which involves a different function (view) than the page I want the user to stay on:
$data = $this->model->database_query($id, $user_id);
echo $data; // from reading other posts it seems I would process the data within this function, to have it displayed on the page the user is viewing?
Any help appreciated!
Don't forget to block you default anchor behaviour (for example by adding return false; to your onclick parameter).
<?php $atts = array (
'class' => "alignright button",
'onClick' => "ajax('$id,$user_id'); return false;",
); ?>
you can make the ajax request as follows:
function ajax(id, user_id) {
$.ajax({
url: base_url + controller_name + '/' + action_name,
type: 'GET',
data: { id: id, user_id: user_id },
dataType: 'json',
success: function (data) {
// append the returned result to your #dynamicdiv
}
});
}
and in the controller:
$id = $this->input->get('id');
$user_id = $this->input->get('user_id');
$data = $this->model->database_query($id, $user_id);
echo json_encode($data);
Hope this helps