How to Display message once we got response from Browser - php

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');

Related

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!

Load() not working to call a PHP template when submitting a form

I'm trying to load a php file into a div on submission of a form. At the moment everything fires bar this line $('#signupform').load('newsletter-signup-call.php');, I've just got a simple echo request in there and it doesn't fire. If I goto that template it works though.
Where am I going wrong? Could I possibly fire two Ajax calls (as that in itself works) but there seems to be issues with load.
<script>
$("#signupForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var email = $("#EmailAddress").val();
$.ajax({
type: "POST",
url: form.attr('action') + '?email=' + email,
data: form.serialize(),
beforeSend: function(){
$(".newsletter-loading").show().css({"display":"inline-block"});
},
success: function(data)
{
console.log(data); //data contain response from your php script
register_signup();
register_prefs();
(function() {
window.sib = {
equeue: [],
client_key: "xxx"
};
/* OPTIONAL: email for identify request*/
window.sib.email_id = email;
window.sendinblue = {};
for (var j = ['track', 'identify', 'trackLink', 'page'], i = 0; i < j.length; i++) {
(function(k) {
window.sendinblue[k] = function() {
var arg = Array.prototype.slice.call(arguments);
(window.sib[k] || function() {
var t = {};
t[k] = arg;
window.sib.equeue.push(t);
})(arg[0], arg[1], arg[2]);
};
})(j[i]);
}
var n = document.createElement("script"),
i = document.getElementsByTagName("script")[0];
n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();
})();
sendinblue.track('marketing');
$(".newsletter-loading").hide();
form.replaceWith("<br /><p>Thanks for signing up! You'll receive an email with your discount.</p>");
}
});
});
function register_prefs(){
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php');
}
function register_signup(){
ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
}
</script>
Try to console.log the response status to see what's going wrong
function register_prefs(){
//see if this function is triggered
console.log('register_prefs function triggered')
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php', function( response, status, xhr ){
console.log('Server response : ', response)//The serve response
console.log('Status Message : ', [xhr.status, xhr.statusText])//See the status of your request, if any error it should be displayed here
});
}
BUT, Why perform another server call with load, when your are already using ajax, you can return the html in the first call in a json object {Mydata: ..., MyHTML: ...} and just use $('#signupform').html(data.MyHTML) on success.
Also, not sure but I'm suspecting a malformed URL, try this instead '/newsletter-signup-call.php' or an absolute path just to be sure.

AJAX with WordPress HTTP API

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);

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Codeigniter and AJAX error

I am making an application for a bar.
The application populates #beer_output with "beer form buttons" by executing get_beers_from_customer(); when the document is ready.
Then the bartender serves drinks by clicking on a "beer form button".
Each time the bartender clicks on the "beer form button" an ajax call is made and send to the codeigniter controller where the beer is deleted and echos a response to ajax with the beers left to be served until there are no orders left to be serve.
Once there are no beers left the order gets processed through another function of my controller : process_order_when_all_drinks_served($user_id).
I am using authorize.net as the payment gateway.
The problem is when I order only 1 beer to be serve, but if I have an order of 2 beers everything works fine. process_order_when_all_drinks_served($user_id) outputs the error Trying to get property of non-object.
Here is specifically where the error is happening if($response->response_code=="1") apparently it is not giving a response back. The ajax is posting and it is not giving back any errors. I do not know what is happening. I can give you the link and order 1 drink if that helps.
Here are the ajax functions
$(document).ready(function(){
get_beers_from_customer();
function get_beers_from_customer()
{
//form variables
var user_id = "<?php echo $this->session->userdata('user_id'); ?>" ;
var formData = {user_id:user_id};
ajax_update_content_when_page_is_loaded_beers(formData);
}
function ajax_update_content_when_page_is_loaded_beers(formData)
{
$.ajax({
url : '<?php echo base_url()."index.php/bartender/bartender_serve_beers"; ?>',
async : false,
type : "POST",
cache : false,
data : formData,
dataType: "html",
success : function(data)
{
alert($.trim(data));
$('#beer_output').html($.trim(data));
$('#beer_output').trigger('create'); },
error: function (jqXHR, textStatus, errorThrown)
{
$('#server_message_error_jqXHR').html("here is the jqXHR"+jqXHR);
$('#server_message_error_textStatus').html("here is the textStatus "+textStatus);
$('#server_message_error_errorThrown').html("here is the errorThrown"+errorThrown);
}
});
}
});
once the form is submitted
$(".beer").on("submit",function(event)
{
//variables
var delete_beer = $(this).find(".delete_beer").val();
var beer_id = $(this).find(".beer_id").val();
var user_id ="<?php echo $this->session->userdata('user_id');?>";
// alert( "delete_beer="+delete_beer+"beer_name=" +beer_name +"beer_id="+beer_id );
//form variables
var formData = {delete_beer:delete_beer,beer_id:beer_id,user_id:user_id}; //Array
submit_ajax_form_beers(formData);
//get_beers_from_customer();
});
function submit_ajax_form_beers(formData)
{
$.ajax({
url : '<?php echo base_url()."index.php?/bartender/bartender_serve_beers"; ?>',
async : false,
type : "POST",
cache : false,
data : formData,
dataType: "html",
success : function(data){
$('#beer_output').trigger('create');
console.log($(this).data(formData));
},
error: function (jqXHR, textStatus, errorThrown){
$('#server_message_error_jqXHR').html("here is the jqXHR"+jqXHR);
$('#server_message_error_textStatus').html("here is the textStatus "+textStatus);
$('#server_message_error_errorThrown').html("here is the errorThrown"+errorThrown);
}
});
}
Codeigniter controller
public function process_order_when_all_drinks_served($user_id)
{
$bartender_id = $this->session->userdata('bartender_id');
//load model
$this->load->model('authorizenet_model');
//finalize order with authorizenet prior authorize and capture
$response = $this->authorizenet_model->priorauthcapture($user_id);
print_r($response);
if($response->response_code=="1")
{
//stores the order_line before it is deleted
$this->bartender_model->store_past_order_line($user_id);
//deletes customer from order line if all beers and mixed drinks have been served
$this->bartender_model->delete_customer_from_order_line($user_id);
//order was successful
$response_message= '<center><strong>'.$response->response_reason_text.'</strong></center>';
}
else
{
//store userdata in unprocess orders
$this->bartender_model->store_unprocessed_order($user_id,$bartender_id);
//then erases it from order_line
$this->bartender_model->delete_customer_from_order_line($user_id);
$response_message= '<center><strong style="color:red;">'."There was a problem with the order.<br/>"
.$response->response_reason_text.$response->error_message.'</strong></center>';
}
return $response_message;
}
public function bartender_serve_beers(){
//checks if there are any drinks left to process order
if(isset($_POST['delete_beer']) && isset($_POST['user_id'])
{
$user_id = $_POST['user_id'];
$beer_id = $_POST['beer_id'];
//then it is deleted from the paid beers
$this->bartender_model->delete_beers($user_id,$beer_id);
//checks if there are any drinks left to be processed
$checks_any_drinks_left= $this->bartender_model->checks_if_mixed_drinks_beers_left_to_process_order($user_id);
if($checks_any_drinks_left=="1")
{
$user_id = $this->session->userdata('user_id');
$proccess_drinks_message= $this->process_order_when_all_drinks_served($user_id);
//outputs the response message to bartender
echo $proccess_drinks_message;
}
else
{
$user_id = $this->session->userdata('user_id');
//continues outputting beers
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}
}
else
{
$user_id = $this->session->userdata('user_id');
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}
}
I don't see nesessity to have output of session variable to frontend.
You will have it in next controller too. Better would be to check in next controller if it still exists.
Add one check in inside else like:
//...
else if ($this->session->userdata('user_id') != false && !empty($this->session->userdata('user_id')) ) {
$user_id = $this->session->userdata('user_id');
//continues outputting beers
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}//...rest of the code
Also, you check for $_POST['delete_beer'] and than assign $_POST['beer_id'] to $beer_id variable. Although I can't see you passed any beer variable through AJAX. As far as I can see, you pass only session output.

Categories