Append Ajax Response Multiple Times Foreach Data Send - php

I have a list of users who waiting for pending payment. I Would like to created a mass payment to users who have pending.
I created ajax request for that
<script>
jQuery(document).ready(function(){
$("#boxesAll").click(function () {
$('input[name="boxes[]').prop('checked', this.checked);
$submit_act.toggle( $submit_box.is(":checked") );
$submit_act_paid.toggle( $submit_box.is(":checked") );
if($(this).is(':checked')){
var numberChecked = $('input[name="boxes[]"]:checked').length;
$('#count_item').html(numberChecked +' items');
$('tr>td:first-child').addClass('bg-warning');
} else {
$('tr>td:first-child').removeClass('bg-warning');
}
});
var id,resp,
$submit_act = $(".btn-act").hide(),
$count_item = $("#count_item").hide(),
$submit_box = $('input[name="boxes[]"]').click(function() {
$submit_act.toggle( $submit_box.is(":checked") );
$count_item.toggle( $submit_box.is(":checked") );
$('input[name="boxes[]"]').change(function() {
$(this).parents('tr>td').toggleClass('bg-warning', $(this).is(':checked'));
});
var numberChecked = $('input[name="boxes[]"]:checked').length;
$('#count_item').html(numberChecked +' items selected');
});
$('.btn-act').click(function(){
var btnid = jQuery(this).attr("id");
var page = '<?=$page;?>';
id = [];
$(':checkbox:checked').each(function(i){
id[i] = $(this).val();
});
if (confirm("Are you sure to "+btnid+" these items?")) {
if(id.length === 0){
alert("Please Select atleast one item(s).");
}else{
$.ajax({
type: 'POST',
url: '/<?=$settings['admin_dir'];?>?p=jquery&act='+btnid,
data: {page:page,id:id},
beforeSend: function() {
$(".btn-act").attr("disabled", true);
$(".btn-act").html('<span class="spinner-border spinner-border-sm align-middle" role="status" aria-hidden="true"><span class="sr-only">Loading...</span></span> Please wait...');
}
}).done(function(t) {
setTimeout(function() {
data = JSON.parse(t);
if(data['result']=='success'){
var pages = "<?=$settings['admin_dir'];?>?p="+page;
if(data['type']=='payments'){
$(".btn-act").html('All Payment Paid');
$(".btn-act").attr("disabled", true);
for(var i=id.length; i>0; i--){
$("#action_response").append('<div id="resp">'+data['msg']+'</div>');
}
}
}else{
$(".btn-act").attr("disabled", false);
$(".btn-act").html('Failed to action');
}
}, 3000);
});
}
}
});
});
</script>
And the php to process it
if($_GET['act']=="payments"){
if(isset($_POST["page"]) && isset($_POST["id"])){
foreach($_POST["id"] as $id){
$details = getDetails('user_payments','id',$id);
$user = getDetails('users','id',$details["user_id"]);
}
$msg = array(
"result" => 'success',
"type" => 'payments',
"msg" => 'Successfully paid to '.$user['username']
);
echo json_encode($msg);
}
}
All code is working, but I have a problem about the result. The result always return in same result.
For example I checked 4 items for payments, the result goes here
Successfully paid to user1
Successfully paid to user1
Successfully paid to user1
Successfully paid to user1
The result I want is append each user that I checked.
Successfully paid to user1
Successfully paid to user2
Successfully paid to user3
Successfully paid to user4
So we know which user have been paid successfully.
Let me know if someone can fix this

You only return one message in your ajax response.
To get the multiple results you have to build the message in a loop
if($_GET['act']=="payments"){
if(isset($_POST["page"]) && isset($_POST["id"])){
$msg = [];
foreach($_POST["id"] as $id){
$details = getDetails('user_payments','id',$id);
$user = getDetails('users','id',$details["user_id"]);
$msg[] = 'Successfully paid to '.$user['username'];
}
$response = array(
"result" => 'success',
"type" => 'payments',
"msg" => $msg
);
echo json_encode($response);
}
}
.
for(var i=id.length; i>0; i--){
$("#action_response").append('<div id="resp">'+data.msg[i]+'</div>');
}

Related

PHP code not executing when run thru AJAX

I am trying to execute data if the SMS OTP is equal to Session_oTp. So, that is working fine, I am able to verify the mobile OTP is verified or not. But when trying to execute some normal query it does not run.
case "verify_otp":
$otp = $_POST['otp'];
$orderId = $_POST['orderid'];
$params = array("status" => "completed");
$body = 'orders/'.$_POST['orderid'] ;
// $woocommerce->put('orders/'.$orderId, $params);
if ($otp == $_SESSION['session_otp'] && $orderId == $_SESSION['OrderID']) {
// if ($otp == $_SESSION['session_otp']) {
echo "$params";
// $params = array("status" => "completed");
// $woocommerce->put($body, $params);
// print_r($_SESSION['OrderID']);
unset($_SESSION['session_otp']);
unset($_SESSION['OrderID']);
echo json_encode(array("type"=>"success", "message"=>"Your mobile number is verified!"));
} else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
If I turn off the $params or $woocommerce query it works perfectly. Even if I try to echo a normal words, it's returning the error code.
My AJAX code is below:
$('form.otp-ver-form').on('submit', function(e){
// $(document.body).on("submit", 'form.otp-ver-form', function() {
e.preventDefault();
$(".error").html("").hide();
$(".success").html("").hide();
var $form = $( this ),
url = $form.attr( 'action' );
// var otpnumber = $form.find('input[name="otpnumber"]').val();
var otpnumber = $form.siblings('.mobileOtp').val();
var Order_ID = $form.siblings('.orderID').val();
console.log(otpnumber);
console.log(Order_ID);
var input = {
"otp" : otpnumber,
"orderid" : Order_ID,
"action" : "verify_otp"
};
if (otpnumber.length == 6 && otpnumber != null) {
$.ajax({
url : 'controller.php',
type : 'POST',
dataType: 'json',//specify data type
data : input,
success : function(response) {
console.log(response.message);
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
});
Please let me know where is my fault or if I missing something.

Why do the responses of my new plugin not save?

So below are some of the actions that my plugin is supposed to perform when submitting the survey. On my console I should get 'response saved', but I get absolutely nothing, not even 'Could not save response'. I have looked through the code, but I can't see why ajax is not performing the function of saving the response. Can anyone else see what is going on here?
// 5.3
// hint: ajax form handler for saving question responses expects: $_POST['survey_id'] and $_POST['response_id']
function ssp_ajax_save_response() {
$result = array(
'status'=>0,
'message'=>'Could not save response.',
'survey_complete'=>false
);
try {
$survey_id = (isset($_POST['survey_id'])) ? (int)$_POST['survey_id']: 0;
$response_id = (isset($_POST['response_id'])) ? (int)$_POST['response_id']: 0;
$saved = ssp_save_response($survey_id, $response_id);
if($saved) {
$survey = get_post($survey_id);
if(isset($survey->post_type) && $survey->post_type = 'ssp_survey') {
$complete = true;
$html = ssp_get_question_html($survey_id);
$result = array(
'status'=>1,
'message'=>'Response saved!',
'survey_complete'=>$complete,
'html'=>$html
);
} else {
$result['message'].='Invalid survey.';
}
}
} catch(Exception $e) {
// php error
}
ssp_return_json($result);
}
// 5.4
// hint: saves single question response
function ssp_save_response($survey_id, $response_id) {
global $wpdb;
$return_value = false;
try {
$ip_address = ssp_get_client_ip();
// get question post object
$survey = get_post($survey_id);
if($survey->post_type == 'ssp_survey'):
// get current timestamp
$now = new DateTime();
$its = $now->format('Y-m-d H:i:s');
// query sql
$sql = "INSERT INTO {$wpdb->prefix}ssp_survey_responses (ip_address, survey_id, response_id, created_at) VALUES (%s, %d, %d, %s) ON DUPLICATE KEY UPDATE survey_id = %d";
// prepare query
$sql = $wpdb->prepare($sql, $ip_address, $survey_id, $response_id, $ts, $survey_id);
// run query
$entry_id = $wpdb->query($sql);
// If response saved successfully...
if($entry_id):
// return true
$return_value = true;
endif;
endif;
} catch(Exception $e) {
// php error
ssp_debug('ssp_save_response php error', $e->getMessage());
}
return $return_value;
}
Someone made me aware that I need to add the jQuery code and so here it is and thank you in advance.
jQuery(document).ready(function($){
// do something after jQuery has loaded
ssp_debug('public js script loaded!');
// hint: displays a message and data in the console debugger
function ssp_debug(msg, data) {
try {
console.log(msg);
if(typeof data !== "undefined") {
console.log(data);
}
} catch(e) {
}
}
// setup our wp ajax URL
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
// bind custom function to survey form submit event
$(document).on('submit', 'ssp-survey-form', function(e){
// prevent form from submitting normally
e.preventDefault();
$form = $(this);
$survey = $form.closest('.ssp-survey');
// get selected radio button
$selected = $('input[name^="ssp_question_"]:checked', $form);
// split field name into array
var name_arr = $selected.attr('name').split('_');
// get the survey id from the last item in name array
var survey_id = name_arr[2];
// get the response id from the value of the selected item
var response_id = $selected.val();
var data = {
_wpnonce: $('[name="wp_nonce"]', $form).val(),
_wp_http_referer: $('[name="wp_http_referer"]', $form).val(),
survey_id: survey_id,
response_id: response_id
};
ssp_debug('data', data);
// get the closest dl.ssp-question element
$dl = $selected.closest('dl.ssp-question');
// submit the chosen item via ajax
$.ajax({
cache: false,
method: 'post',
url: wpajax_url + '?action=ssp_ajax_save_response',
dataType: 'json',
data: data,
success: function(response) {
// return response in console for debugging...
ssp_debug(response);
// If submission was successful...
if(response.status) {
// update the html of the current li
$dl.replaceWith(response.html);
// hide survey content message
$('.ssp-survey-footer', $survey).hide();
} else {
// If submission was unsuccessful...
// notify user
alert(response.message);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// output error information for debugging...
ssp_debug('error', jqXHR);
ssp_debug('textStatus', textStatus);
ssp_debug('errorThrown', errorThrown);
}
});
});
});

Ajax response return undefined

Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.

ajax check user logged in before running script

i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.

AJAX/PHP pop up for validation

Anyone can help me. Please. I don't how to have a pop up every validation exist.
I used alert(data.message); but validation says undefined.
here is my PHP code for the function:
<?php
include('connect.php');
$mydata = $_POST["results"];
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$plate_no_full = "$plate_char-$plate_no";
$result1 = mysql_query("SELECT * FROM cars where plate_no ='" . $plate_no_full . "'");
$result2 = mysql_query("SELECT * FROM cars where chass_no ='" . $chassis_no . "'");
$result3 = mysql_query("SELECT * FROM cars where eng_no ='" . $engine_no . "'");
$rows1 =mysql_num_rows($result1);
$rows2 =mysql_num_rows($result2);
$rows3 =mysql_num_rows($result3);
$errors = [];
if (mysql_num_rows($result1) > 0) {
$errors[] = array(
'error_code' => 1,
'message' => 'That plate number was already taken'
);
}
if (mysql_num_rows($result2) > 0) {
$errors[] = array(
'error_code' => 2,
'message' => 'That chassis number was already taken'
);
}
if (mysql_num_rows($result3) > 0) {
$errors[] = array(
'error_code' => 3,
'message' => 'That engine number was already taken'
);
}
if(empty($errors)) {
mysql_query("INSERT INTO cars VALUES ('', '$plate_char-$plate_no', '$engine_no', '$chassis_no', '$car_year', '$car_brand', '$car_model', '$horse_power', '$torque','$transmission $transmission_no', '$drivetrain', '$length/$width/$height', '$seating', '$condition','$air_bag' , '$front_wheel/$rear_wheel' , '$front_susp/$rear_susp' , '$brake_front/$brake_rear' , '$eng_type', '$fuel_type' , '$acquisition_cost' , '$marg_cost', '$selling_price' , '')");
if(isset($_POST["txt1"])){
for($i=0;$i<=count($_POST["txt1"])-1;$i++){
mysql_query("INSERT INTO expenses VALUES ('','$plate_char-$plate_no', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."', '". $_POST["txt3"][$i] ."')");
}
}
$response = array(
'message' => 'Successfully Added'
);
echo json_encode($response);
} else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
here is my ajax code:
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
e.preventDefault();
var mytxt1 = [];
var mytxt2 = [];
var mytxt3 = [];
$(".expense_name").each(function () {
mytxt1.push($(this).val());
});
$(".expense_desc").each(function () {
mytxt2.push($(this).val());
});
$(".expense_cost").each(function () {
mytxt3.push($(this).val());
});
var perfTimes = $(this).serialize();
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function(data) {
if(data.errors) { }
else {
alert(data.message);
window.localtion.href = data.redirect;
}
});
});
});
You need to add the datatype to your post request so jquery can parse the response, then you can handle the errors like you did:
$.post("addfunction.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2, txt3: mytxt3 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.localtion.href = data.redirect;
}
}, "json");//<--datatype here
Also the data.redirect value is missing in your response:
$response = array(
'message' => 'Successfully Added',
'redirect' => ''//add here
);
echo json_encode($response);
Fixing the redirect you wrote "localtion" wrong:
window.location.href = data.redirect;
I found that I needed to parse the returned JSON as well. This is because $.post is just a preconfigured $.ajax call, which does not (I think) specify which dataType is being fetched.
Hence, your Client-side code cannot immediately access the response as an object.
The simplest option is just to parse the response using jQuery:
data = $.parseJSON(data);
Otherwise you could change your code to use the $.ajax function:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
Good luck!

Categories