Trying to get PHP responce on ajax - php

Here I am trying to update the MSQL table using jQuery, both PHP code and jQuery script is written on the same page, the code working fine to update my tables but the response msg is not getting by the AJAX so it always shows me the default message "Some problem occurred, please try again.".
HTML
<!-- HTML code to display msg -->
<p class="statusMsg_post"></p>
jQuery
<script>
$(document).ready(function(){
$('#btn_publish').click( function() {
var obj_post_postID="<?php echo $post_id; ?>";
var publish_post="publish";
$.ajax({
type:'POST',
// url:'post_view.php',
data:{
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success:function(res) {
if (res=='ok') {
$('.statusMsg_post').html('<span style="color:green;">Post has been '+publish_post+' sucessfully</span>');
}
else {
$('.statusMsg_post').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
});
});
</script>
PHP
// my PHP code to update my table
<?php
// require_once('../../inc/db-connect.php');
if (isset($_POST['post_status_update'])) {
$temp_publish_post = $_POST['post_status_update'];
echo $bj_post_postID = $_POST['obj_post_status'];
$obj_post_status_query = "UPDATE `objection_report` SET `obj_status` = '$temp_publish_post' WHERE `objection_report`.`obj_post_id` = $bj_post_postID;";
$obj_post_status_query .= "UPDATE `post` SET `status` = '$temp_publish_post' WHERE `post`.`post_id` = $bj_post_postID ;";
if (mysqli_multi_query($con, $obj_post_status_query)) {
echo "ok";
die;
}
}
?>
all the above codes are on the same page

The script is returning the HTML and JS on the ajax call. If you put checks around the HTML it will not:
<?php if ( ! isset( $_POST['post_status_update'] ) ): ?>
<p class="statusMsg_post"></p>
<script>
$( document ).ready( function () {
$( '#btn_publish' ).click( function () {
var obj_post_postID = "<?php echo $post_id; ?>";
var publish_post = "publish";
$.ajax( {
type: 'POST',
// url:'post_view.php',
data: {
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success: function ( res ) {
if ( res === 'ok' ) {
$( '.statusMsg_post' ).html( '<span style="color:green;">Post has been ' + publish_post + ' sucessfully</span>' );
} else {
$( '.statusMsg_post' ).html( '<span style="color:red;">Some problem occurred, please try again.</span>' );
}
}
} );
} );
} );
</script>
<?php endif; ?>

Related

WP ajax response is empty for $_POST value

I am trying to echo the posted value of an input field via WP ajax, but it keeps returning empty (i.e. no $_POST content), why? If I try to echo 'test', it works.
functions.php:
add_action('wp_footer', 'ajx_action_subscriber');
function ajx_action_subscriber() {
?>
<script type="text/javascript">
jQuery( document ).on( 'click', '#subscribe-submit', function() {
var subscribe_email = $('#footer-email').val();
$('#subscribe-confirmation').html('Registering');
jQuery.ajax({
url : '<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php',
type : 'post',
data : {action:'subscribe_user', subscribe_email:subscribe_email},
success : function( response ) {
$('#subscribe-confirmation').html(response);
}
});
});
</script>
<?php
}
add_action('wp_ajax_subscribe_user', 'subscribe_user');
function subscribe_user() {
echo $_POST['subscribe_email'];
// echo 'test'; // works successfully ?!!?
die();
}

Why my ajax login form doesn't work correctly?

I create a login form using AJAX .
And this is my JQUERY code:
$("#logbtn").on("click" , function() {
if (!$("div").hasClass("error"))
{
$.ajax
({
type:'post',
url:'http://localhost/mysite/wp-content/themes/facecar/admin/inc/proccesslogin.php',
data:{
username: $("#loguser").val(),
password: $("#logpass").val()
},
success:function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
}
});
}
});
This is my PHP code:
<?php
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
?>
I put the response in the console and it show my php codes and alert "answer is no !" . what is problem ?
I believe, you are using wordpress and the way you are trying ajax in wordpress is not the right way. In wordpress ajax url is admin_url( 'admin-ajax.php' ).
You'll get an idea from this link: Ajax call from front in wordpress. I hope you can do the rest following that link.
Let's make it easy for you to understand...
write in your functions.php
/* include your js script */
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
function my_enqueue_scripts() {
//Change the key and url with yours
wp_register_script('my-js', get_stylesheet_directory_uri(). '/js/my-js.js', array( 'jquery' ) );
wp_enqueue_script('my-js');
//Localize script data to be used in my-js.js
$scriptData = array();
$scriptData['ajaxurl'] = admin_url( 'admin-ajax.php' );
$scriptData['action'] = 'answerAction';
wp_localize_script( 'my-js', 'my_js_data', $scriptData );
}
/* Add your server code */
add_action("wp_ajax_answerAction", "answerAction");
add_action("wp_ajax_nopriv_answerAction", "answerAction");
function answerAction(){
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
die();
}
Now, add you js script in my-js.js
(function($){
$(document).ready(function(){
$('#logbtn').on('click',function(e){
e.preventDefault();
var data = {
'action': my_js_data.action,
'username': jQuery("#loguser").val(),
'password': jQuery("#logpass").val()
};
if (!$("div").hasClass("error"))
{
jQuery.post( my_js_data.ajaxurl, data, function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
});
}
});
});
})(jQuery);
Best of luck.

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

php echo link without a href in file add target blank

<?php echo auto_link(site_url('guest/view/quote/' . $quote->quote_url_key)); ?>
This is creating for instance the following link:
http://domainname.com/guest/view/quote/d163df9c4d426b3ab5ef6247bc380745
How can I add an target="_blank" to this php code. Or is there another way to achieve the same.
EDIT 1: Added all scripts from the php page.
<script type="text/javascript">
$(function() {
$('#btn_add_item_from_lookup').click(function() {
$('#modal-placeholder').load("<?php echo site_url('item_lookups/ajax/modal_item_lookups'); ?>/" + Math.floor(Math.random()*1000));
});
$('#btn_add_item').click(function() {
$('#new_item').clone().appendTo('#item_table').removeAttr('id').addClass('item').show();
});
<?php if (!$items) { ?>
$('#new_item').clone().appendTo('#item_table').removeAttr('id').addClass('item').show();
<?php } ?>
$('#btn_save_quote').click(function() {
var items = [];
var item_order = 1;
$('table tr.item').each(function() {
var row = {};
$(this).find('input,select,textarea').each(function() {
if ($(this).is(':checkbox')) {
row[$(this).attr('name')] = $(this).is(':checked');
} else {
row[$(this).attr('name')] = $(this).val();
}
});
row['item_order'] = item_order;
item_order++;
items.push(row);
});
$.post("<?php echo site_url('quotes/ajax/save'); ?>", {
quote_id: <?php echo $quote_id; ?>,
quote_number: $('#quote_number').val(),
quote_date_created: $('#quote_date_created').val(),
quote_date_expires: $('#quote_date_expires').val(),
quote_status_id: $('#quote_status_id').val(),
items: JSON.stringify(items),
custom: $('input[name^=custom]').serializeArray()
},
function(data) {
var response = JSON.parse(data);
if (response.success == '1') {
window.location = "<?php echo site_url('quotes/view'); ?>/" + <?php echo $quote_id; ?>;
}
else {
$('.control-group').removeClass('error');
for (var key in response.validation_errors) {
$('#' + key).parent().parent().addClass('error');
}
}
});
});
$('#btn_generate_pdf').click(function() {
window.location = '<?php echo site_url('quotes/generate_pdf/' . $quote_id); ?>';
});
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$("#item_table tbody").sortable({
helper: fixHelper
});
});
</script>
I have resolved it. Not by using any code but by simple explaining to the users to use ctrl + click. It is probably not the best thing. There should be a way to achieve the same with code. But after the long discussion with Royal Bg I thought it would be wise to stop putting oil on the fire.
I hope that in the future someone else takes up the original question and posts an solution for others to benefit from. In the meantime I will accept this as an answer. I hope others do too.

jQuery Autocomplete: Uncaught TypeError: Cannot read property 'length' of null

My first time using JQuery. Trying to use Autocomplete, and keep getting the error above.
I've tested the MySQL queries and they all work.
If I use the same code below but called from a webpage without the Autocomplete code,
the JSON looks well-formed.
Thanks for any guidance you can provide.
<?php
$docname=$_POST['docselect'];
$surname=$_POST['lastname1'];
if (isset($_POST['lastname1'])){
$return_arr = array();
try {
$dbc=mysqli_connect('localhost','gotlibc_testuser','**passwordgoeshere**','gotlibc_robo2') or die("Error connecting to MySQL server.");
$query="SELECT PT_ID, surname, firstname, jnum FROM patients WHERE surname LIKE '$surname%' ORDER BY surname";
$result=mysqli_query($dbc,$query) or die('Error querying database.');
$row=array();
while($Xrow = mysqli_fetch_array($result)) {
$row['label']="{$Xrow['surname']},{$Xrow['firstname']},{$Xrow['jnum']}";
$row['value']=$Xrow['PT_ID'];
$return_arr[]=$row;
}
}
// end try
catch(Exception $e ) {
echo "<script type='text/javascript'> alert('Hi'); </script>";
printf("catch activated");
echo $e->errorMessage();
}
echo json_encode($return_arr);
mysqli_close($dbc);
}
?>
Here's the relevant snippets of the calling web page
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$( "#lastname1" ).autocomplete({
source: "pt_autoshow1.php", minLength: 1
});
});
</script>
<h2>Patient Information:</h2>
<br>
<form id="surnamepicker" action="#" method="post"> or Last name: <input name="lastname1" id="lastname1" type="text">
<div class="rage_button_781076"> New Patient </div>
with Dr.
<select name="docname">
<option value="2">Doctor A</option>
<option value="1">Doctor B</option>
<option value="3">Doctor C</option>
</select></form>
its working fine for me
php function will return the rows/No Results as response
public function shamsearchJSON ()
{
$search = $this->input->post('search');
$query = $this->user_model->getmessages($search);
if(!empty($query)){
echo json_encode(array('responses'=> $query));
}
else{
echo json_encode(array('responses'=> 'No Results'));
}
}
javascript code
$( "#search-inbox" ).autocomplete({
minLength: 2,
source: function( request, response ) {
// $.getJSON( "<?php echo base_url(); ?>index.php/user/shamsearchJSON?search="+request.term,response );
$.ajax({
url: "<?php echo base_url(); ?>index.php/user/shamsearchJSON",
data: {"search": request.term},
type:"POST",
success: function( data ) {
var parsed = JSON.parse(data);
if(parsed.responses == "No Results")
{
alert("no results::");
var newArray = new Array(1);
var newObject = {
sub: "No Results",
id: 0
};
}
else{
var newArray = new Array(parsed.length);
var i = 0;
parsed.responses.forEach(function (entry) {
var newObject = {
sub: entry.subject,
id: entry.mID
};
newArray[i] = newObject;
i++;
});
}
response(newArray);
},
error:function(){
alert("Please try again later");
}
});
},
focus: function( event, ui ) {
//$( "#search-inbox" ).val( ui.item.sub );
return false;
},
select: function( event, ui ) {
if(ui.item.id != 0){
$( "#search-inbox" ).val( ui.item.sub );
openInboxMessage(ui.item.id);
}
else
{
}
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ){
return $( "<li>" ).append("<a>" + item.sub +"</a>" ).appendTo(ul);
};

Categories