Use Ajax WordPress Checkbox To Get Template - php

I am trying to load a content template based on the checkbox but want to use AJAX to improve my coding structure but not sure how. I have no prior experience to AJAX so I would really appreciate your help.
HTML
<input type="checkbox" class="checkbox" id"content_one">
<input type="checkbox" class="checkbox" id="content_two">
PHP/Jquery
jQuery(document).ready( function() {
if ($('#content_one').is(':checked')) {
<?php get_template('content_one'); ?> //displays a post loop
}
if ($('#content_two').is(':checked')) {
<?php get_template('content_two'); ?> //displays a post loop
}
});

If you want to ajax you need to register the action in wordpress, it would be something like this.
add_action('wp_ajax_your_action_name', 'my_fallback_function')
add_action('wp_enqueue_scripts', 'my_script');
And you need to specify your function here, in the functions.php, it would be something like this
function my_fallback_function()
{
$param = $_GET['param'];
echo get_template($param);
wp_die();
}
function my_script()
{
wp_localize_script(
'ajaxUrl',
'ajaxObject',
array('ajax_url' => admin_url( 'admin-ajax.php' )
);
}
Then we need to specify the ajax call from the client side it would be something like this
$(document).ready(function() {
$("input[type='checkbox']").click((e) => {
const content = $(e.target).val();
const params = {
'action': 'your_action_name' // should be the same in the wp_ajax,
'param': content
};
$.ajax({
method: 'GET',
url: ajaxObject.ajax_url
data: params,
done(function(respond){
//append your respond here
})
})
})
})
<label for="checkbox1"><input type="checkbox" name="checkbox1" value="content_1"/>Content 1</label>
<label for="checkbox2"><input type="checkbox" name="checkbox2" value="content_2"/>Content 1</label>

Related

Try to using ajax form instead of form action (solve)

I would like to improve user experience at my website. So I try to change the form action ajax, and I has been try some tutorial but I still getting stuck.
I am using a php forum program/source code call !Discuz and it was from China. Below is my coding now.
In html.
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn">submit</button>
</form>
in PHP, file name plugin.php
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
showmessage('message here','redirectlink');//this is !Discuz program function and it is fine.
}
}
?>
The above script is working fine while using form action, and redirect to my output page. If I would like to change to ajax, how do I adjust the below source code?
<script type="text/javascript">
function login() {
$.ajax({
type: "POST",
dataType: "json",//? is it can use json? since my form data can get as array
url: "plugin.php?id=cc&do=shop" ,//url
data: $('#jnfarm_pop').serialize(),
success: function (result) {
console.log(result);
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("ERROR");
}
});
}
</script>
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login()">submit</button>
</form>
And is it have to adjust the plugin.php source code?
Updated, below is work for me, thanks fayis003.
html change the <script></script>
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
alert(result.final);//alert message here
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
PHP
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
$final = 'message here';
echo json_encode(['final' => $final]);
}
}
?>
You can not initiate a direct browser redirect using server-side code on ajax request like you do with synchronous requests. instead, you have to return a URL to which you want to get redirected to and then do something like location.href = result.link in the result callback.
for ajax request, the simplest option is using as follows
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
let final = result.final;
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
now in the server-side code instead of creating a redirect from PHP return something like
return json_encode(['link' => 'somlink']);
of just return success message as usual.

preventDefault() causing a submitted form to redirect to another page?

I have a product page with the following form:
<form id="ratingsForm" action='../resources/add_rating_to_product.php' method="POST">
<input type="hidden" name="productID" value="<?php echo $productID; ?>" />
<span class="rating">
<input type="radio" class="rating-input"
id="rating-input-1-5" name="rating" value="5">
<label for="rating-input-1-5" class="rating-star"></label>
...
<input type="radio" class="rating-input"
id="rating-input-1-1" name="rating" value="1">
<label for="rating-input-1-1" class="rating-star"></label>
</span>
</form>
This is just a simple star rating form which uses radio buttons.
I have a javascript file that will submit the form once a radio button is clicked
$(document).ready(function() {
$('input[name=rating]').change(function(){
$('form').submit();
});
});
I have another javascript file that will trigger when the form is submitted and use ajax to post it to the correct file.
$(document).ready( function() {
$("#ratingsForm").on("submit",function(e){
e.preventDefault();
$.ajax( {
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
alert('Thanks for rating');
}
});
})
});
Add_rating_to_product just takes the posted information and inserts it into the database.
The problem I'm having is that instead of preventing and redirection, e.preventDefault redirects me to my search page for apparently no reason. I have check all of my code in my product page and there's nothing that could redirect me there so what is the problem? Without the preventDefault(), it redirects to add_rating_to_product.php as expected.
Is there any chance you have another form on your page? If you do, the following code submits all the forms on the page:
$(document).ready(function() {
$('input[name=rating]').change(function(){
$('form').submit();
});
});
I think it would be safer to do the following:
$(document).ready(function() {
$('input[name=rating]').change(function(){
$(this).closest('form').submit();
});
});
After the success function call you can use
$(this).unbind('submit').submit()
, which will allow the execution to continue as if preventDefault was nt called
Try this:
$(document).ready(function() {
$('input[name=rating]').change(function(e){
e.preventDefault();
var prodID = $(this).find("input[name='productID']").val();
$.ajax( {
type: "POST",
url: $(form#ratingsForm).attr( 'action' ),
data: {$('form#ratingsForm').serialize(), prodID: prodID},
success: function( response ) {
alert('Thanks for rating');
}
});
});
});
Just do it in one function to initialize and send them in server side. I hope this works.

Using purely jQuery AJAX in cakePHP 1.3

I'm using cakePHP 1.3 and would like to use AJAX from my search view to the search action in my controller. I was using prototype and scriptaculous and it was working fine, but need to use purely jQuery.
The search action basically looks as follows:
public function search() {
if (empty($this->data)) {
} else {
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']));
}
}
The view currently looks like:
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = searchString;
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
<div id='container'>
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
What is the best way to make the 'data' variable available to $this->data in the controller? I checked the other threads with similar questions, but was unable to see how to do this.
Thanks!
Send it as POST ( refer to http://api.jquery.com/jQuery.post/ ) or url_encode (google "javascript url encode") the string and append it to the url. Not sure which was is better, both should work and be easy to implement.

Send multiple checkbox data to PHP via jQuery ajax()

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;

jQuery: form returned on "success" needs re-binding

a quick question. I am using the jQuery.forms.js plug-in.
I have a form that posts to a php page and returns data with jSon.
The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded.
So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?
// jQuery for submitting info to php doc and, on success, replacing the form
$(document).ready(function() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
});
<!-- /////////////////////// POST ONLINE /////////////////////// -->
<div id='onlineStatus<?php echo $b_id ?>' class='postOnline'>
<form name="postOnline" id="postOnline<?php echo $b_id ?>" action="postOnline.php" method="post">
<input type="hidden" value="<?php echo $b_id ?>" name="b" />
<input type="hidden" value="1" name="p" />
<input type="submit" class="button" value="Post Online" />
</form>
</div>
<!-- /////////////////////// POST ONLINE /////////////////////// -->
// ... code for entering data into database and then...
$result = mysql_query( $sql );
if($result) {
if($show == '1'){$val = 'remove from online'; $num='0';}
if($show == '0'){$val = 'show online'; $num='1';}
$return = "
<form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'>
<input type='hidden' value='$b_id' name='b' />
<input type='hidden' value='$num' name='p' />
<input type='submit' class='button' value='$val' />
</form>
";
print json_encode(array("rid" => $id, "formed" => $return));
}
?>
The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:
$(document).ready(function() {
jQuery('form[id*=postOnline]').live('submit', function() {
var formdata = $(this).serialize();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
dataType: 'json',
data: formdata,
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
return false;
});
});
Now since you are using jQuery's new (1.3) live functionality, any forms you add that match the form[id*=postOnline] selector will still be wired with this event.
Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it live. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:
function bindForm() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
bindForm();
}
});
}
$(document).ready(function() {
bindForm();
});
I don't think it is very neat, but it should work.
You need to rebind the event handlers after the ajax call. I heard about a new feature in the newer version of jquery called live events, that would make this unnecessary though.
If for whatever reason you're stuck with a pre-1.3 version of jQuery, use the "livequery" plugin.

Categories