Run php file via jquery call in Wordpress - javascript

So I wish to replicate the following functionality in wordpress. Jquery calls a php file, which itself queries a mysql table, and returns the result encapsulated within an tag. How do I go about achieving this?:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
....
function initialize() {
....
feedData();
}
$(document).ready(function () { initialize(); });
function feedData() {
$(document).ready(function () {
$.ajax({
cache: false,
type: "POST",
async: false,
url: "page-gotw-search.php",
data:{"action=showcountries"},
success: function (data) {
$('#CountryList').append(data);
},
error: function (data, status, error) {
console.log(data);
console.log(status);
console.log(error);
}
});
});
}
</script>
<body>
<div style="width: 800px">
<div style="float: left">
<select id="CountryList" onchange="getRegion()" size="20"></select>
<select id="RegionList" size="20" onchange="getMap()"></select>
</div>
<div id="cityList" style="float: right"></div>
</div>
</body>
</html>
page-gotw-search.php
<?php
include_once("pdo_mysql.php");
pdo_connect("localhost","root","");
pdo_select_db("wpdb");
$action=$_POST["action"];
if($action=="showcountries"){
$showcountry = pdo_query("Select distinct meta_value from wp_usermeta where meta_key =?, pdo_real_escape_string('country_registration')");
if (!$showcountry) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $showcountry;
die($message);
}else{
foreach($showcountry as $row){
echo '<option value=".$row[country_code].">.$row[country_name].</option>';
}
}
}
else if($action=="showregions"){
$country_id= $_POST["country_id"];
$showregion = pdo_query("Select region_code, region_name from regiontbl
WHERE country_id=?", pdo_real_escape_string($country_id));
if (!$showregion) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $regionquery;
die($message);
}else{
foreach($showregion as $row){
echo '<option value=".$row[region_code].">.$row[region_name].</option>';
}
}
}
?>

Looks like you want to implement ajax into the wordpress.
I have a simple way to do this. Follow below given steps to use ajax calls in wordpress
add some code in footer.php
jQuery(‘#clickerid').change(function(){
var your_id = jQuery(‘#get_val').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
cache: false,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ‘id='+ id + '&action=get_id',
success: function(data)
{
jQuery(‘#id').html(data);
}
});
});
Then use this ajax call into the functions.php
add_action( 'wp_ajax_get_your_action', 'prefix_ajax_get_your_action' );
add_action( 'wp_ajax_nopriv_get_your_action', 'prefix_ajax_get_your_action' );
function prefix_ajax_get_costofcare() {
// Do your php code used in ajax call and return it.
}
Ajax calls works via admin-ajax.php which is build in functionality provided by wordpress

Related

Submit form with AJAX and PHP without page reload

I have "add to favorite" feature in my wordpress project, I am using <form> to submit the feature. Each time I click on add to fav button it works, but the page is always reloaded which is annoying so I decided to use AJAX, but I can not connect it with my PHP file.
This is PHP file, where I wrote function for the feature
if (! function_exists('favorite_button_icon')) {
function favorite_button_icon() {
echo apply_filters( 'favorite_button_icon', get_the_favorite_button_icon() );
}
}
if (! function_exists('get_the_favorite_button_icon')) {
function get_the_favorite_button_icon() {
$output = '';
$action = $currentPath; // window.location.href
$name = is_favorite() ? 'remove_favorite' : 'add_favorite';
$class = 'favorite-button-pro' . ( is_favorite() ? ' favorite' : '' );
$icon = is_favorite() ? 'Added' : 'Add';
$output .= '<form method="post" id="favorite_user_post"
class="favorite_user_post" action="'. $action .'">';
$output .= '<button id="submit-favorite" type="submit" name="'. $name .'"
value="'. get_the_ID() .'" class="'. $class .'">';
$output .= $icon;
$output .= '</button></form>';
return apply_filters( 'get_the_favorite_button_icon', $output );
}
}
And I am just calling that function in html
<div class="add-to-favorites-option" >
<?php favorite_button_icon() ?>
</div>
Everything above works, but as I said, page is being reloaded.
This is my attempt to use AJAX
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
var url = form.attr('action');
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});
I get absolutely no fire on submit, am I missing something?
You need to use the wp_ajax_ hook: https://developer.wordpress.org/reference/hooks/wp_ajax_action/
Simple example below:
You PHP code to process the ajax request:
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
// code that captures your ajax POST request
wp_die(); // this is required to terminate immediately and return a proper response
}
Your Ajax call:
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
// note the added "my_action" to tell the server what function to fire (my be a better way to append this to your form data)
var url = form.attr('action') + "&=my_action";
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});

jquery ajax return values into html form

I need help with returning values from jQuery/AJAX to html form inside index.php
index.php :
<script type="text/javascript">
$(document).ready(function () {
$('#display').ready(function () {
var pageid = '<?php echo $_GET[\'ID\'] ;?>';
var powiat = '<?php echo $row[\'powiat\'] ;?>'
$.ajax({ //create an ajax request to display.php
type: 'GET',
url: 'display.php?ID=' + pageid + '&powiat=' + powiat,
dataType: 'html', //expect html to be returned
success: function (response) {
$('#responsecontainer').html(response);
//alert(response);
}
});
});
});
(...)
echo "<form action=\"save.php\" method=\"GET\">";
echo "<tr><td>IP</td><td><div id=\"responsecontainer\"></td></tr>";
echo "<input type=\"submit\" value=\"Save\">" ;
echo "</table></form>
display.php file contains:
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
echo "<option value=\"".$disp_row_1['ip']."\">".$disp_row_1['ip']</option>";
}
In return I have filed html as expected but when I try submit form filed by jquery/ajax I have error
Notice: Undefined index: ip.
How can I handle with that?
Thanks.
Syntax error in your code when you are printing the option.
Updated code is as below.
$disp_result_2 = mysql_query("SELECT ip FROM swittche_ip WHERE powiat LIKE '%$disp_powiat%' AND ip NOT IN ( SELECT ip FROM switche )" )or die(mysql_error());
while($disp_row_1 = mysql_fetch_assoc($disp_result_2)){
?>
<option value="<?php echo $disp_row_1['ip'];?>" ><?php echo $disp_row_1['ip'];?></option>
<?php }

Sent value and show output when select tag change

I new in term of using jQuery.
I practice using native php ajax, but for this time I need to learn jQuery for the current technology and demand.
I sent "types" value method POST to other page (ajaxInfo.php) when the tag change.
After the select tag change, it should show the result at <div id="showList"> that come from database (MySQL). But nothing happen.
Below are the source code.
Body
<select id="form-types" class="col-xs-10 col-sm-5" name="types">
<option value="">PLEASE CHOSE</option>
<option value="STATE">STATE</option>
<option value="FACULTY">FACULTY</option>
<option value="PROGRAME">PROGRAME</option>
</select>
<div id="showList"></div>
jQuery AJAX
<script type = "text/javascript" >
$(document).ready(function () {
$("select#form-types").change(function () {
var types = $("select#form-types").val();
if (types != null) {
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function (response) {
$("#showList").html(response);
}
}
});
});
});
</script>
Post Page (ajaxInfo.php)
<?php
if (isset($_POST["types"]) === TRUE){
$types = $_POST["types"];
}
else{
$types = null;
}
include '../dbco.php';
$query = $dbc -> query ("SELECT child FROM infobase WHERE parent='$types'");
if ($query -> num_rows > 0){
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc()){
echo "$count" . $result['child'] . "<br />";
count++;
}
}else{
echo "NO " . $types . " REGISTERED";
}
?>
Thank You.
You are using id (form-types) for your select input field. but your are tying to targeting another id (form-jenis).
use same named id for select input field and in your jquery selector.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(e){
e.preventDefault();
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'show.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
You have a missing bracket
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}
});
});
}); // add this
</script>
I found out that my ajax jQuery function do not have close pair, so i decide to add it and it work.
<script type="text/javascript">
$(document).ready(function(){
$("select#form-types").change(function(){
var types= $("select#form-types").val();
if (types!= null)
{
$.ajax({
type: 'post',
url: 'ajaxInfo.php',
data: "types=" + types,
dataType: 'html',
success: function(response)
{
$("#showList").html(response);
}
}); // Add This
}
});
});
</script>
After the code running good, i also found out the error at ajaxInfo.php, the count inside the loop missing $ symbol
if ($query -> num_rows > 0)
{
echo "LIST OF : " . $types . "REGISTERED<br />";
$count = 1;
while ($result = $query -> fetch_assoc())
{
echo "$count" . $result['child'] . "<br />";
$count++; //HERE
}
}
Thanks for the people that help.

Wordpress Ajax returns '0'

There are quite a few similar problems I could find, but nothing helped, so have to post my own version of this question.
I have 2 php files:
playing.php (contains the web form and sends the ajax call)
plug_search.php (has the form processing code)
Before I started trying to use ajax, the form processing worked perfectly, the query worked as expected and the proper result was returned, based on the search parameters. Now, I want to use ajax, so the results are returned to the same page and it always returns '0'. I tried (seems like) everything I could, ruled out the most probable reasons (incorrect function/call name) - no luck. Feels like something very simple is missing, I suspect the problem is in the declaration of the function, but can't see what's wrong (it seems like the call never reaches processing function in plug_search.php). I stripped all the query code and just trying to return a simple string - still same '0'.
If you could help, I'd appreciate that a lot!
playing.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function search(){
var plug=$("#autocomplete-dynamic").val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
if(plug!==""){
$("#result").html();
$.ajax({
type: "GET",
url: ajaxurl,
data: {
action: 'ajax_return_search_results',
plug: 'country'
},
success:function(data){
alert(data);
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});
</script>
plug_search.php
<?php
add_action( 'wp_ajax_ajax_return_search_results', 'myajax_return_search_results' );
add_action( 'wp_ajax_nopriv_ajax_return_search_results', 'myajax_return_search_results' );
function myajax_return_search_results() {
echo "Success";
die();
}
?>
plug_search.php - Full version
function myajax_return_search_results() {
$value = $_GET['plug'];
$value2 = $_GET['country'];
$sql = "SELECT name, image_url, amazon_url, plug_type FROM adapters_list WHERE plug_type = '$value' AND country LIKE '%$value2%'" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($sql);
while($row = mysqli_fetch_array($result)) { ?>
<div id="output-product" style="border: 1px solid #333; font-family: Helvetica, sans-serif; font-size: 20px;"><?php echo $row["name"] . "<br />";?>
<?php echo "</div>";
die();
}
Add this code in your functions.php
add_action( 'wp_ajax_ajax_return_search_results', 'myajax_return_search_results' );
add_action( 'wp_ajax_nopriv_ajax_return_search_results', 'myajax_return_search_results' );
function myajax_return_search_results() {
echo "Success";
die();
}
data is returning an error code because you are using .success instead of .done
$.ajax({
type: "GET",
url: ajaxurl,
data: {
action: 'ajax_return_search_results',
plug: 'country'
}
}).done(function(data){
alert(data);
});
You are missing datatype in ajax
Try adding it
$(document).ready(function(){
function search(){
var plug=$("#autocomplete-dynamic").val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
if(plug!==""){
$("#result").html();
$.ajax({
type: "GET",
url: ajaxurl,
dataType: 'html',
data: {
action: 'ajax_return_search_results',
plug: 'country'
},
success:function(data){
alert(data);
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});

PHP Ajax not creating post variable

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});

Categories

Resources