AJAX with WordPress HTTP API - php

I'm new to php and stuck in my tracks here, so any help is appreciated. I've written a few functions in a JS file to render and update a gallery view for a WordPress template I made. From the updateGallery() function, I make an AJAX call after pressing a submit button on the page, but am receiving a "parsererror."
Arguments(3) [{…}, "parsererror", SyntaxError: Unexpected token A in JSON at position 0 at parse (<anonymous>)
at Ut (https://…, callee: ƒ, Symbol(Symbol.iterator): ƒ]
I tried the code for the API request directly in my WP template to render a response and it worked as expected, but when I try to incorporate my script I get the error and I can't figure out what's causing it.
JS
function updateGallery() {
var county = $("#county").val();
jQuery(".galleryGrid").fadeOut("fast", function() {
console.log("ajax request");
jQuery(".galleryGrid").html("").hide();
$.ajax({
type : "GET",
dataType : "JSON",
url : ajax.url,
data : {
action: "get_gallery_data",
county_id : county
},
error: function(response, error) {
console.log(arguments);
alert("Failed because: " + error);
},
success : function(response) {
if(response.type === "success") {
console.log("Success")
renderGrid(response.data);
}
}
});
});
}
PHP
add_action("wp_ajax_nopriv_get_gallery_data", "get_gallery_data");
add_action("wp_ajax_get_gallery_data", "get_gallery_data");
function get_gallery_data() {
$county_id = $_REQUEST[county_id];
$base_api_url = "https://some.api.com/";
$filters = array(
"field" => "field_153",
"operator" =>"is",
"value" => $county_id
);
$filters_url = rawurlencode(json_encode($filters));
$api_url = $base_api_url."?filters=".$filters_url;
$request = wp_remote_get($api_url, array(
"headers" => array(
"Application-Id" => "5xxxxxx",
"REST-API-KEY" => "0xxxxxx",
),
));
$body = wp_remote_retrieve_body($request);
$output = json_decode($body, true);
echo $output;
die();
};

$output = json_decode($body, true);
//Change
$output = json_encode($body, true);

Related

jQuery.ajax int is being sent but $_POST returns NULL

When sending data to an ajax post call I get "NULL" returned.
I am sending a lot more data (which all works), but left it out of the snippet to make it more clear.
When I log the var in my console, it shows up. When I check the network tab if the data is properly sent, it shows up. When I var_dump the $_POST in PHP it returns NULL.
Jquery
function get_cars_ajax() {
var filterAdvertentienummer = 119005595; // is number
$.ajax({
type: 'POST',
url: '/wp/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
'action' : 'get_cars_filter',
'filterAdvertentienummer ' : filterAdvertentienummer,
},
success: function(data) {
if(data != '') {
// DO SOMETHING
} else {
// DO NOTHING
}
},
error: function(data) {
console.log(data);
}
}
PHP
function get_cars_filter() {
global $post;
$context = Timber::get_context();
var_dump($_POST['filterAdvertentienummer']); // = NULL
echo $_POST['filterAdvertentienummer']; // = empty string
if (isset($_POST['filterAdvertentienummer'])) {
$advertentienummer = $_POST['filterAdvertentienummer'];
} else {
$advertentienummer = "";
}
$queryList = '?skip='.$current_page.'&limit='.$limit.'&sort='.$sort.'&order='.$order;
if ($advertentienummer != "") {
$queryList = $queryList . "&advertentienummer=" . $advertentienummer;
} else {
var_dump($advertentienummer);
}
$args = array(
'headers' => array(
'accept' => 'application/json'
)
);
$results = wp_remote_retrieve_body(wp_remote_get('http://IP/cars'.$queryList, $args));
return $results;
}
I noticed a mistake in your ajax code.
Your code line:
'filterAdvertentienummer ' : filterAdvertentienummer,
you have added one space in the variable name so it's not gonna be readable by PHP.
Modified code :
'filterAdvertentienummer' : filterAdvertentienummer
Now PHP will read this variable as a string. You can convert strings in int with PHP.

Autocomplete does not work in CodeIgniter

When doing an ajax-request for an autocomplete I get an undefined error:
View:
<input type="text" name="" id="search">
<ul>
<div id="result"></div>
</ul>
Javascript:
$("#search").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>index.php/admin/ajaxPro",
dataType: 'json',
type: 'POST',
data: req,
success: function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select: function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
Controller:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
header('Content-Type: application/json');
echo json_encode($data);
}
Database:
this is the table
There is no error in the console, Data is showing the network preview but it is not showing on the view page I do not know what the problem is Can you help
The Problem:
Return value: undefined
Change your Controller code to something like this:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
$ajaxData = array();
foreach($data as $row) {
$ajaxData[] = array( // Set "label"+"value" for autocomplete for each result
'label' => $row['name'], // <- change this to your column name
'value' => $row['id'] // <- this should be the ID-Value
);
}
header('Content-Type: application/json');
echo json_encode(
'status' => 'success',
'data' => $ajaxData
);
}
And your ajax success callback:
success: function(r){
if(typeof r.status != "undefined" && r.status == "success"){
response(r.data); // lets autocomplete build response list
} else {
console.log(r); // error occured
}
},
(I changed your response variable from data to r to clearify this is not just the actual data, but a response in a variable that can contain much more than just the data from your sql-find result. It usually holds data exactly in the format you give in json_encode() )
Explanation:
In this line:
if(data.response =="true"){
You are asking for a value/key response that does not exist.
Tips on Debugging and Troubleshooting:
To see what your ajax-response look like, you can open the Dev-Tools in your Browser (ususally F12 and go to the Tab that shows your network requests. There you can find your ajax-request and see the headers you sent and the final response.
Furthermore if you add debugger; in this line, you can debug your javascript and see all variables available in the current scope:
success: function(r){
debugger; // this is a breakpoint equivalent and will halt your code execution when dev tools are open!

AJAX get call always returning empty string

I am trying to make a simple AJAX GET call to my php backend, it hit and runs the method defined however no matter what the response data in the success function is always an empty string with a 200 response.
My ajax request is:
$("#coverage-table").on("click", "td", function() {
$(this).attr('id');
//Create Ajax call
//Get bill data/notes
//Present modal
$.ajax({
url: 'http://tms-v2.test/tms/getBillNotes',
type: 'GET',
data: {
bills: $(this).attr('id')
},
success: function(response) {
console.log(response);
debugger;
modal.style.display = "block";
}
});
});
My php method is:
public function getBillNotes() {
$bills = array_filter(explode("," ,$_GET['bills']));
$billingGateway = new BillingGateway;
$data = $billingGateway->getBillNotes($bills);
//Convert mysql object to array
while($row = mysqli_fetch_array($data)){
$items[] = $row;
}
foreach ($items as $key => $bill) {
$return[$bill['bill_id']] = [
'invoice_number' => $bill['invoice_number'],
'supplier' => $bill['supplier_name'],
'creation_date' => $bill['creation_date'],
'uploaded_by' => $bill['first_name'].' '.$bill['last_name'],
'is_credit_note' => !!$bill['type'],
'validation_status' => !!$bill['is_validating'],
'paid_date' => $bill['paid_date'],
'critical_notes' => $bill['note']
];
}
return 'TEST';
}
However this is always returning "", is this something to do with my request headers?

How to Display message once we got response from Browser

we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
Requirement :
I want to show the message "completed" once if we got response from browser :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function(){
var selected = [];
$('.assigneeid-order:checked').each(function() {
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response){
response = $.parseJSON(response);
$.each(response, function(index, val) {
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
In an ajax call, the member success is being used when the request succedeeds. You can use this method to inform the user the server gave a success response.
success: function(response){
//Your code here to inform the user
response = $.parseJSON(response);
$.each(response, function(index, val) {
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
You can use the member error the same way to tell the user that the server indicated that the request failed.
error: function(response)
{
//not good, tell it to the user
}
Hello,
You can add a div in display none in your HTML and put it in display block when you have an answer from the broswer.
In your success function in your ajax code, you put the code to do it.
Example:
$('#completed-message').text('Completed');
$('#completed-message').css('display', 'block');

reCAPTCHA on second form submit not working

When users submit form, in php fields are validated. If there is some error php return echo message that there is an error (it doesn't return an ERROR to ajax). So the ajax is still "success".
If I comment grecaptcha.reset(); in the ajax success, and when user submits the form for the second time then $response != null && $response->success returns false in php.
How to fix this, so that there is no grecaptcha.reset() after ajax successs, and that it is enough for user to pass the captcha for only once.
Here is the reCAPTCHA in the html form:
<div class="g-recaptcha" style="display:inline-block;" data-sitekey="6LdDlHIUAAAAAD3hgpRSSsNpS7SaRILGNTNiyak_"></div>
Here is the jQuery:
jQuery('#some_form').submit(function(e){
e.preventDefault();
var FormData = jQuery(this).serialize();
jQuery('.buttonHolder').css('display', 'none');
jQuery('#spinner-1').css('display', 'block');
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
dataType : 'json',
data : {
action : 'some_form',
security : rml_obj.check_nonce,
data1 : FormData
},
success : function( response ) {
PUM.open(7939);
//alert(checkbox_chk);
jQuery('.pum-content').html(response.message1);
jQuery('.copy-url').html(response.message2);
jQuery('.buttonHolder').css('display', 'block');
jQuery('#spinner-1').css('display', 'none');
//grecaptcha.reset();
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
},
});
});
And here is the php code for testing reCAPTCHA:
require_once "recaptchalib.php";
$secret = "6LdDlHIUAAAAALFlTOx-9T63cODtjs7eno******";
$response = null;
$reCaptcha = new ReCaptcha($secret);
$data = $_POST[ 'data1' ];
parse_str($data, $output);
$var1 = $output['var1'];
$var2= $output['var2'];
if ($output["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$output["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//insert data into db ...
header("Content-type: application/json; charset=utf-8");
echo json_encode(
array("message1" => 'message1',
"message2" => 'message2')
)
} else {
header("Content-type: application/json; charset=utf-8");
echo json_encode(
array("message1" => 'error reCAPTCHA')
}
Thaks ArtisticPhoenix for the good advise. After further investigating the same reCAPTCHA response cannot be validated twice. Changes in php fields validation have fixed my issue.

Categories