retrieving data from php - javascript

I tried to retrieve data from php but when I run the code it not passing in javascript. It gives an error. Can anyone help?
Javascript
function updateCountryFeatures() {
$.ajax({
url: "libs/php/getCountryBounds.php",
type: 'POST',
dataType: 'json',
data: {
iso3: countryAlpha2Code
},
success: function(result) {
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("updateCountryFeatures: " + errorThrown + " " + jqXHR + " " + textStatus);
}
});
}
PHP:
$executionStartTime = microtime(true);
$countryBorders = json_decode(file_get_contents("libs/php/countries/countries_large.geo.json"), true);
$border = null;
foreach ($countryBorders['features'] as $feature) {
if ($feature["properties"]["ISO_A3"] == $_REQUEST['iso3']) {
$border = $feature;
break;
}
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['executedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $border;
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);

Related

WordPress ajax load more not working properly?

I'm trying to load more posts via load more button when it will be clicked but its not working properly my first three posts repeat again and again, anyone can help me?
Here is my query which I placed in template file.
$paged=get_query_var('paged') ? get_query_var('paged') : 1;
$the_queryx = new WP_Query(array(
'post_type' => 'exhibitions',
'posts_per_page' => 3,
'post_status' => 'publish',
'order' => 'DESC',
'paged'=>$paged,
'post__not_in'=> array($sticky_post_id),
)
);
$the_max_num_pagesx = $the_queryx->max_num_pages;
if ($the_queryx->have_posts()) {
echo '<div id="post_cat_home" class="row">';
while ($the_queryx->have_posts()) {
$the_queryx->the_post();
get_template_part('loop-templates/content', get_post_format());
}
echo '</div>';
if ($the_max_num_pagesx > 1) {
echo '<div class="load-more-posts" style="width:100%; text-align:center;">
<button id="more_posts_home_exb" data-sticky="' . $sticky_post_id . '" data-pages="' . $the_max_num_pagesx . '" data-pn="'.$paged.'" class="btn more_posts"> </button>
</div>';
}
/* Restore original Post Data */
wp_reset_postdata();
}
And here is my ajax script:
$("#more_posts_home_exb").on("click", function (e) {
e.preventDefault();// When btn is pressed.
$(this).attr("disabled", true); // Disable the button, temp.
var total = $(this).data('pages');
var sticky = $(this).data('sticky');
load_posts_home_exb(total, sticky);
});
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 1;
var ppp = 3; // Post per page
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
pageNumber++;
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
This is my final function file code which function call through via ajax script.
function more_post_home_exb_ajax()
{
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
// $paged = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$sticky_ignore = (isset($_POST['sticky_ignore'])) ? array($_POST['sticky_ignore']) : '';
$paged = $_POST['pageNumber'] +1;
header("Content-Type: text/html");
$loop_template = 'loop-templates/content';
$args = array(
// 'suppress_filters' => true,
'post_type' => 'exhibitions',
'posts_per_page' => $ppp,
'post__not_in' => $sticky_ignore,
'order' => 'DESC',
'post_status' => 'publish',
'paged' => $paged,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
get_template_part($loop_template, get_post_format());
endwhile;
endif;
exit;
}
add_action('wp_ajax_nopriv_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
add_action('wp_ajax_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
This code works but first three posts repeat when button clicked. Thank you!
I've tried some condition in ajax script and it is working now. ;)
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 0;
var ppp = 3; // Post per page
pc_x++;
pageNumber = pc_x;
if (total > pageNumber - 1) {
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
else{
$("#more_posts_home_exb").hide();
}
return false;
}

PHP not getting first post value

Experts, my php is not showing the first value of the input field but console.log showing correctly
console.log
PHP Output
function summary() {
$(document).ready(function (e) {
var date = $("#dddeliverydate").val();
var soid = $("#sssoid option:selected").val();
var form = $("#formsum").serialize();
console.log(form);
$.ajax({
url: "test.php",
method: "POST",
data: "&date=" + date + "&soid=" + soid + "&form=" + form,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}
below is my PHP code
<?php
for ($count = 0; $count < count($_POST['invoiceno']); $count++) {
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO " . $invoiceno . " Amount " . $amount . '<br>';
}
?>
what I am doing wrong need your help thanks in advance
You can change the code as below
function summary() {
$(document).ready(function (e) {
var send_data= $("#formsum").serialize();
send_data += '&date='+$("#dddeliverydate").val();
send_data += '&soid ='+$("#sssoid option:selected").val();
$.ajax({
url: "test.php",
method: "POST",
data: send_data,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});

Confirm scan barcode result

I have a project with barcodescanner library for phonegap. i have success scan QR Code image with this. And i want to authenticate the code inside QR Code with my database. How to do it?
i have barcodescanner.js:
document.addEventListener("deviceready", init, false);
function init() {
}
function scan() {
log("scanning");
cordova.plugins.barcodeScanner.scan(scanSuccessCallback, scanErrorCallback);
}
function scanSuccessCallback(result) {
log(JSON.stringify(result));
konfirmasi();
/*
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
*/
}
function scanErrorCallback(error) {
alert("Scanning failed: " + JSON.stringify(error));
}
function encode() {
log("encoding");
if (device.platform == "Android") { //Not supported on iOS
var stringToEncode = "http://www.sap.com";
cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, stringToEncode, encodeSuccessCallback, encodeErrorCallback);
}
else {
log("Encoding is not supported on iOS. See https://github.com/wildabeast/BarcodeScanner/issues/106");
}
}
function encodeSuccessCallback(result) {
log(JSON.stringify(result));
}
function encodeErrorCallback(error) {
alert("Encoding failed: " + JSON.stringify(error));
}
function log(line) {
var results = document.getElementById("scan_results");
//results.innerHTML+= "<br>" + line;
}
And this is my authentition php:
<?php
header("access-control-allow-origin: *") ;
include "connect.php";
$kode_konfirmasi = $_POST['konfirmasi'];
$kurir = $_POST['kurir'];
$miss = 'miss';
$delivered = 'delivered';
$query_kode = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Belum Terkirim'";
$res_kode_ok = mysqli_query($dbc, $query_kode);
$query_exp = "SELECT * FROM pengiriman WHERE kode_transaksi = '$kode_konfirmasi' AND status = 'Terkirim'";
$res_kode_expired = mysqli_query($dbc, $query_exp);
$query_ok = "SELECT pengiriman.kode_transaksi, pengiriman.status FROM pengiriman, kurir WHERE pengiriman.id_kurir = kurir.id_kurir AND kurir.username = '$kurir' AND pengiriman.kode_transaksi = '$kode_konfirmasi'";
$res_kurir = mysqli_query($dbc, $query_ok);
if(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)>0){
$res_upd = mysqli_query($dbc, $query_upd);
$output = array('status' => true);
echo json_encode($output);
$query_upd = "UPDATE pengiriman SET status = 'Terkirim' WHERE kode_transaksi = '$kode_konfirmasi'";
}elseif(mysqli_num_rows($res_kode_ok)>0 && mysqli_num_rows($res_kurir)==0){
$output = array('status' => $miss);
echo json_encode($output);
}elseif (mysqli_num_rows($res_kode_expired)>0){
$output = array('status' => $delivered);
echo json_encode($output);
}else{
$output = array('status' => false);
echo json_encode($output);
}
?>
I have a script for authenticate the code inside QR Code manually by insert it in form html like this
$(document).on('pageinit','#manual',function(){
$(document).on('click','#submit',function(){
if($('#kode').val().length>0){
var un = window.localStorage.getItem('uname');
var kode = $('#kode').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/konfirmasi.php',
data:{ kurir : un,
konfirmasi : kode
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(hasil){
console.log(hasil);
if(hasil.status==true){
alert('Berhasil! Konfirmasi kode ' + kode + ' berhasil.')
$.mobile.changePage("#konfirmasi");
console.log('Konfirmasi Berhasil');
}else if(hasil.status=='delivered') {
alert('Error! Kode '+ kode + ' telah dikonfirmasi.');
}else if(hasil.status=='miss'){
alert('Error! Data kurir tidak sesuai.');
}else{
alert('Gagal, Kode konfirmasi tidak sesuai.');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
So, how i can authenticate the code from scanning result immediately when scan success?

CURL Delete request to Instagram API fails

I'm trying to unlike a photo that I just liked on Instagram with a call to the API. My url is exactly as the URL in instagrams API tool. Im using Curl. I get an empty response, no error or status code.
Here is my "like/unlike" method written in javascript.
likeImage: function(type, id)
{
var params = "url=https://api.instagram.com/v1/media/" + id + "/likes";
if(type === 'DELETE')
{
params += "?access_token=" + localStorage.getItem('id') + "." + localStorage.getItem('token');
}
else
{
params += "&access_token=" + localStorage.getItem('id') + "." + localStorage.getItem('token');
}
$.ajax({
url: "crossDomain.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
type: type,
data: params,
beforeSend: function ()
{
console.log('Start' + type);
},
complete: function(data)
{
console.log('Finished ' + type);
},
success: function(data)
{
console.log('Success ' + type);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('JQXHR:' + jqXHR);
console.log('TEXTSTATUS: ' + textStatus);
console.log('ERROR THROWN:' + errorThrown);
console.log('error');
}
});
And here is my Server Code written in PHP
$method = $_SERVER['REQUEST_METHOD'];
if($method == "POST")
{
$url = $_POST['url'];
$token = $_POST['access_token'];
$fields = array(
"access_token" => urlencode($token)
);
$fields_string = "";
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
else if($method == 'DELETE')
{
$url = file_get_contents('php://input');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
My Like code works Perfectly... any thoughts?
According to the documentation a DELETE request should look like this:
curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=MYACCESSTOKEN
Problem solved. In my PHP delete method, $url started with url=... I just had to remove that.

Categories