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();
}
});
});
Related
<script>
function addprescription() {
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
}
</script>
I have a function to submit the form. But ajax function alerts its as failure. But data base seems to be updated. when I click the button. I couldn't find the reason for the cause in the console.
this is the php file
<?php
echo "I'm in";
include "../../Adaptor/mysql_crud.php";
include ("Prescription.php");
$prescription=new Prescription();
if(isset($_POST)){
$Note=htmlspecialchars($_POST['Note']);
$Case_Histroy=htmlspecialchars($_POST['Case_Histroy']);
$medication = htmlspecialchars($_POST['Medication']);
$pname=$_POST['pname'];
$danme=$_POST['dname'];
$id=$_POST['id'];
$prescription->insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
<div class="alert alert-success" id="alert"><strong><?php echo "Submitted succesfully"; ?></strong></div>
<?php
}
?>
Try adding an else statement to your if:
insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
}
?>
Also, it's not necessary to stick the php in the middle of the <div> you can just use echo at the beginning since you're not introducing any variables to it:
echo '<div class="alert alert-success" id="alert"><strong>Submitted successfully</strong></div>';
Finally I got the answer for the Problem! Actual problem is button that fired up the AJAX request also reloaded the page interrupting AJAX inner workings. So the error message will be alerted.
I tried this code.
<script>
$(function() {
$("#button_Add_p").click(function(e){
e.preventDefault();
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
dataType: 'html',
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
});
});
</script>
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
I am trying to get data from one php page and pass it to another page using Ajax.
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id=data"
}
});
action.php :
<?php
$test= 1;
?>
data.php :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
<?php
$id = $_GET['id'];
echo $id;
?>
First of all, you need to echo your data in action.php, and second, use data parameter of AJAX request to send data to data.php.
Here's the reference:
jQuery.ajax()
So the organization of pages should be like this:
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php",
data: {id: data},
success: function(data){
// your code
// alert(data);
}
});
}
});
action.php :
<?php
$test = 1;
echo $test;
?>
data.php :
<?php
$id = $_GET['id'];
echo $id;
?>
Try to use $.get() method to get/send data :
$.get("action.php",{}, function(data){
//data here contain 1
$.get("data.php", {id: data}, function(id){
alert(id);
}
});
Just echo $test since just the data printed in page will return as responce to the query request.
action.php :
<?php
$test=1;
echo $test;
?>
Hope this helps.
For example,
Test
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
action.js
$('.dataClass').click(function(){
var value=$(this).attr('data-value');
$.ajax({url:"Ajax_SomePage.php?value="+value,cache:false,success:function(result){
alert("success");
}});
});
Ajax_SomePage.php
<?php
$value = $_GET['value'];
echo $value;
?>
To get data as response in ajax call, you need to echo the result from your php page; action.php page.
echo $test = 1;
In your provided code
$.ajax({
url: "data.php?id=data"
} // closing bracket is missing
you are sending the string data as id to data.php page. Instead you have to append the result with the url using + symbol like shown in the below code.
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id="+data
})
}
});
I have an javascript array variable in my view file , how can i send the array to different controller ?
this is html code:
<button id=<?php echo $key ?> onclick="movebutton(this)" class='li'><?php echo $officers['Officer']['name'] ?> </button>
and this is my javascript code:
function movebutton(elem){
var teamMember=new Array();
if( $(elem).parent().attr("class") == "officers_list" ){
$(elem).detach().appendTo('.add_member');
teamMember.push($(elem));
}
else{
$(elem).detach().appendTo('.officers_list');
teamMember.pop($(elem));
}
You can pass any data to controller using ajax -:
Get values you want to a javascript variable and check a sample ajax
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array(
'controller'=>'controller','action'=>'action'));?>',
data: ({type:variable-value }),
success: function (data){
return true;
// $("#div").html(data);
}
});
To pass data from view to controller:
You can use form but in form your data won't be sent as an array
Using ajax
.
var data = {
val1 = '<?php echo $string ?>';
val2 = '<?php echo $number ?>';
}
$.post( 'controller/action', data , function(response) {
if (response == true) {
// Do this
} else {
// Do that
}
});
i am trying to get a row of data from database using ajax in codeigniter.
Here is the javascript function-
$(function(){
$("button[name='program_view_details']").click(function(e){
e.preventDefault();
var program_id=$(this).attr('id');
$.ajax({
url: "<?php echo base_url();?>program_management/get_program_data",
type: "POST",
dataType: "html",
data: "program_id="+program_id,
success: function(row)
{
alert(row.program_name);
}
});
});
I am not sure if the datatype and post is correct or not.
Here is my controller function-
public function get_program_data( ){
$program_id = $this->input->post('program_id');
$this->load->model('program_management_model');
$data['programs']= $this->program_management_model->get_program_specific($program_id);
echo $data;
}
Here is the model-
function get_program_specific($program_id){
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
return $query->result();
}
I am searching the way of returning the row from controller to javascript. But the alert() is showing "undefined" in the success. Please anyone tell me the whole way through. Thanks in advance.
$data['programs']= $this->program_management_model->get_program_specific($program_id);
The $data which you are echoing in the controller is basically an array[] and programs is an array which is present in $data. Either echo the $data in controller using the
foreach(){}
or echo the $query array in your model. That will do the trick.And in ajax success call just append the data to the element in which you want to show the result.
Change names as per your page.
in your script:
$.ajax({
url: '<?php echo base_url();?>managealerts_edit/editalerts',
type: "POST",
data: {'id': edit_id},
cache: false,
dataType: "json",
success: function(row){
//alert(row.sub);
$('#edit').show();
$('#sub').val(row.sub);
$('#mess').val(row.mess);
}
});
in your model:
$query = $this->db->query("SELECT fld_id, fld_course_id,fld_sub,fld_mess from tbl_alerts where fld_id='".$det."' ");
if ($query->num_rows() > 0)
{
$row = $query->row_array();
$data=array("sub" => $row['fld_sub'], "mess" => $row['fld_mess']);
echo json_encode($data);
}
in your controller:
$det = $this->input->post('id');
//$alertsres['tbl_alerts'] = $this->managealerts_m->select_editalerts($det);
$this->managealerts_m->select_editalerts($det);`
in model
function get_program_specific($program_id){
$temp=array();
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
$temp= $query->row_array();
echo $temp['program_name'];
}
in controller change the line
$data['programs']= $this->program_management_model->get_program_specific($program_id);
with
$this->program_management_model->get_program_specific($program_id);
and finally in javascript
alert(row);
please let me know if you face any problem.