Shorten URL with Javascript using JSON - javascript

I am trying to short a Link over API and get the result with JSON
Some information about the API
Sample Response
{"error":0,"short":"http:\/\/doma.in\/sf0x6"}
Sample Usage in PHP
$content=#file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array
if(!$url["error"]){ // If there is no error
echo $url["short"]; //Outputs the short url
}
else{
echo $url["msg"]; //Outputs the error message
}
Request to Shorten a Long URL
GET http://doma.in/api/?url=http://www.google.com&api=APIKEY
*json_short.php*
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$url = curPageURL();
$json_short = #file_get_contents("http://doma.in/api/?url=$url&api=APIKEY");
echo $json_short;
*json_short.js*
$.getJSON('json_short.php', function(data) {
if(!data.error){ // If there is no error
alert(data.short) //Outputs the short url
}
else{
alert(data.msg)
}
});

Use JavaScript to simplify the process:
var foo = window.location.href;
var bar = foo.replace(/[a-z0-9.]+\//g, shortener);
function shortener(match, pos, fullstring)
{
if (shortener.count === foo.match(/[a-z0-9.]+\//g).length)
{
shortener.count = 0;
}
else
{
shortener.count = shortener.count + 1 || 0;
}
if (shortener.count === 1)
{
return "";
}
else
{
return match;
}
}

Related

How do I submit this wordpress form without page reload?

So basically I need to submit this quick-interest-slider form without page reload - https://loancalc.000webhostapp.com , this isn't my code, i'm not too experienced with wordpress or php.
After adding this $('.qis-form').on('submit'... code the slider continues to reload the page once i've clicked "apply now".
I don't know exactly what in the code I should be working with but i'm told the functions are...
qis-loop (validates and processes the form), qis_process_form also processes the form and sends email.
function qis_loop($atts) {
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
qis_process_form
function qis_process_form($values) {
global $post;
$content='';
$register = qis_get_stored_register($values['formname']);
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$qis_messages = get_option('qis_messages');
$application = qis_get_stored_application_messages();
if(!is_array($qis_messages)) $qis_messages = array();
$ip=$_SERVER['REMOTE_ADDR'];
$url = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$page = get_the_title();
if (empty($page)) $page = 'Unknown Page';
$period = $values['loan-period'] == 1 ? $settings['singleperiodlabel'] : $settings['periodlabel'];
if (!$period) $period = $settings['period'];
$values['loan-amount'] = $settings['currency'].$values['loan-amount'];
$values['loan-period'] = $values['loan-period'].' '.$period;
$radio = explode(',',$register['radiolist']);
$values['yourradio'] = $radio[$values['radiooption']];
for ($i=1;$i<=3;$i++) {
if ($values['check'.$i]) $checks .= $register['check'.$i] . '<br>';
}
if ($checks) $values['yourchecks'] .= substr($checks, 0, -4);
$values['sentdate'] = date_i18n('d M Y');
$values['timestamp'] = time();
if ($register['storedata']) {
$newmessage = array();
$arr = array(
'reference',
'yourname',
'youremail',
'yourtelephone',
'yourmessage',
'yourchecks',
'yourradio',
'yourdropdown',
'yourconsent',
'loan-amount',
'loan-period',
'confirmation',
'formname',
'sentdate',
'timestamp'
);
foreach ($arr as $item) {
if ($values[$item] != $register[$item]) $newmessage[$item] = $values[$item];
}
$qis_messages[] = $newmessage;
update_option('qis_messages',$qis_messages);
}
if (!$auto['notification']) {
qis_send_notification ($values);
}
if (($auto['enable'] || $values['qis-copy']) && !$application['enable']) {
qis_send_confirmation ($auto,$values,$content,$register);
}
if ($register['qis_redirect_url']) {
$location = $register['qis_redirect_url'];
echo "<meta http-equiv='refresh' content='0;url=$location' />";
exit;
}}
The data is validated in qis_verify_application
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
If it passes validation the form is then processed in qis_process_application.
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
I have made an ajax call here
jQuery('.qis-form').on('submit', function(event){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
After hunting down your html, you will want to call it on the APPLY click NOT form submit.
jQuery(document).on('click','.toggle-qis a', function(event){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
return false;
});

Ajax call result not working properly

I have this function where on onkeyup it verifies the mobile number whether it exists in the database already or not now the issue is even if the response is "true" it will always show as false
PHP
elseif ($action == 'check_mobile_phone')
{
$mobile = trim($_GET['mobile']);
$mobile = json_str_iconv($mobile);
if (mobile_register($mobile))
{
echo 'false';
}
else
{
echo 'true';
}
}
Ajax Call
function checkMobilePhone(mobile)
{
if (mobile == '')
{
error.find('#mobile_notice_text').html('Mobile number cant be empty.');
submit_disabled = true;
}
else if (!Utils.isMobile(mobile))
{
error.find('#mobile_notice_text').html('Please enter mobile number in local format.');
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_mobile_phone', 'mobile=' + mobile, check_mobile_callback , 'GET', 'TEXT', true, true );
}
Response
function check_mobile_callback(result)
{
var logform = $('form[name="formUser"]');
var error = logform.find('#mobile_notice');
if ( result === "true" )
{
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
error.find('#mobile_notice_text').html('Phone number already exists.');
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function mobile_register($mobile)
{
$res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['db']->table('users') .
" WHERE mobile_phone = '$mobile'");
return $res;
}

2 ajax on the same event "onchange" cause conflict

I have a form with a dropdown list. On change, it calls 2 ajax functions :
<select onchange="getLimite(this.value); getPrice(this.value);">
Thoses functions call a PHP script which send a SQL query.
Problem : one function works, the other not.
In this way :
<select onchange="getLimite(this.value); getPrice(this.value);">
Only getPrice(this.value) works.
In this way :
<select onchange="getPrice(this.value); getLimite(this.value);">
Only getLimite(this.value) works.
Source of one of those functions (for example) :
function getPrice(billet) {
if(billet == 'vide') {
document.getElementById("blocPrixP").innerHTML = '';
}
else {
var prixBlocP = document.getElementById("blocPrixP");
prixBlocP.innerHTML = '<img src="images/loading.gif" alt="loading" title="loading" />';
creerRequete(); // new XMLHttpRequest();
var urlPrix = 'prix.php?billet='+billet;
requete.open('GET', urlPrix, true);
requete.onreadystatechange = function() {
if(requete.readyState == 4) {
if(requete.status == 200) {
affichePrix();
}
}
};
requete.send(null);
}
}
prix.php looks like this :
if(isset($_GET['billet'])) {
$billet = $_GET['billet'];
}
else {
$billet = false;
}
if(false !== $billet) {
$requete_prix = $bdd->prepare('SELECT nom_billet, prix_billet FROM ce_billet WHERE nom_billet = :nom_billet');
$requete_prix->execute(array(
':nom_billet' => $billet
));
$data = $requete_prix->fetch();
echo $data['prix_billet'];
}
else {
echo 'Error';
}
Edit : the other function
function getLimite(billet_bis) {
if(billet_bis == 'vide') {
document.getElementById('blocQuantite').innerHTML = '';
}
else {
var blocQuantite = document.getElementById('blocQuantite');
blocQuantite.innerHTML = '<img src="images/loading.gif" alt="loading" title="loading" />';
creerRequete();
var url_limite = 'limite.php?billet='+ billet_bis;
requete.open('GET', url_limite, true);
requete.onreadystatechange = function()
{
if(requete.readyState == 4)
{
if(requete.status == 200)
{
afficheLimite();
}
}
};
requete.send(null);
}
}
limite.php :
if(isset($_GET['billet'])) {
$billet2 = $_GET['billet'];
}
else {
$billet2 = false;
}
if(false !== $billet2) {
$requete_limite = $bdd->prepare("SELECT id_billet, nom_billet, limitation_chiffre_billet FROM ce_billet WHERE nom_billet = :nom_du_billet");
$requete_limite->execute(array(
':nom_du_billet' => $billet2
));
$data = $requete_limite->fetch();
$limite = intval($data['limitation_chiffre_billet']);
if($limite == '') {
$liste = NULL;
}
else {
$liste = '<select id="quantite-billet" name="quantite-billet-name" onchange="getQte(document.getElementsByClassName(\'selecttwo\')[0].value);">'; //
$liste .= '<option value="vide" id="vide">- - - Choisissez la quantité - - -</option>';
for($i = 1; $i <= $limite; $i++) {
$liste .= '<option value="'.$i.'" id="'.$i.'billet">'.$i.'</option>';
}
$liste .= '</select>';
}
echo $liste;
}
else {
echo "Erreur";
}
Edit 2 : function creerRequete(), function affichePrix(), function afficheLimite()
/* creerRequete() */
var requete = null;
function creerRequete() {
try {
requete = new XMLHttpRequest();
}
catch (microsoft) {
try {
requete = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(autremicrosoft){
try {
requete = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(echec) {
requete = null;
}
}
}
if(requete == null) {
alert('Ajax does not work');
}
}
/* afficheLimite() */
function afficheLimite() {
var limite = requete.responseText;
var blocQuantiteb = document.getElementById('blocQuantite');
blocQuantiteb.innerHTML = limite;
}
/* affichePrix() */
function affichePrix() {
var prixDuBillet = requete.responseText;
var prixBloc = $("#blocPrix");
var totalprice = $("#prixtotal");
prixBloc.val(parseFloat(prixDuBillet));
totalprice.val(prixBloc.val() + ' €');
$('#quantite-billet').on('change', function() {
var quantite = $("#quantite-billet option:selected").val();
totalprice.val((Math.round((prixBloc.val() * parseInt(quantite)) * 100) / 100 ) + ' €');
});
document.getElementById("blocPrixP").innerHTML = '';
}
I don't know how to call the 2 functions separately.
Have you tried calling the two from within a wrapper function, and sending a call to that as your onchange event handler? Like this:
<select onchange="getLimiteAndPrice(this.value)">
function getLimiteAndPrice(billet) {
getLimite(billet);
getPrice(billet);
}
requete is a global variable in your code. You use it in both getLimite() and getPrix() functions. One function overrides the other's value.
Here is what I'd do:
function creerRequete() {
var requete = null;
try {
requete = new XMLHttpRequest();
}
//etc.
// And at the end:
if(requete == null) {
alert('Ajax does not work');
} else {
return requete;
}
Then in getPrix():
function getPrix() {
[... do your stuff ...]
var maRequete = creerRequete(); // This is another variable (it exists only inside the function - you can give it another name if you find it easier to understand)
[... do other stuff ...]
affichePrix(maRequete);
}
Finally:
function affichePrix(toujoursMaRequete) {
// Here you can use requete (you still can give it another name: it exists only inside this function)
var prixDuBillet = toujoursMaRequete;
}
Same with your "Limite" functions.
You could have had a global variable (as you did before) if both function weren't executing at the same time, and changing the variable's value at the same time (or if this specific behavior was wanted).

what is happening in this update of php code for Ext js

Actually new in Ext js I m trying to find a solution for this code. I mean i want to see success is true and first "if" block is working but unfortunatelly else block is working and getting false
Why?
public function update() {
$res = new Response();
if (!get_class($this->params)) {
$res->data = array();
foreach ($this->params as $data) {
if ($rec = Event::update($data->id, $data)) {
array_push($res->data, $rec->to_hash());
}
}
$res->success = true;
$res->message = "Updated " . count($res->data) . " records";
} else {
if ($rec = Event::update($this->params->id, $this->params)) {
$res->data = $rec->to_hash();
$res->success = true;
$res->message = "Updated record";
} else {
$res->message = "Failed to updated record " . $this->params->id;
$res->success = false;
}
}
return $res->to_json();
}

returning json data from php as response in javascript ajax

I'm building simple store website with codeigniter. and if user wanna buy product he must login as member 1st. the tasks i want to create when user click "buy" on product:
if user not login alert "please login 1st"
if stock product if empty alert "stock is empty"
if ok, then alert "product added to cart"
I have code like this:
cart.js:
$(document).ready(function() {
//var url = window.location.pathname;
var base = 'http://thita.dev/index.php/'
//alert(url);
$('.prod_box form').submit(function() {
var id = $(this).find('input[name=id_produk').val();
var qty = $(this).find('input[name=qty]').val();
//alert('ID:' + id + '\n\rQTY:' + qty);
$.post(base + 'order/tambah_belanja', {id_produk: id, quantity: qty, ajax: '1'}, function(data) {
if (data.status === true) {
alert(data.message);
} else {
if (data.errtype === 'login') {
alert('please login 1st');
} else if (data.errtype === 'stok') {
alert('Stock is empty');
}
}
});
return false;
});
});
controller order.php:
public function tambah_belanja() {
$this->load->library('auth');
$data = array();
if (!$this->auth->cek_login()) {
$data['status'] = false;
$data['errtype'] = 'login';
}
if ($this->mo_order->tambahBelanja() === TRUE) {
if ($this->input->post('ajax') <> '1') {
redirect('order');
} else {
$data['status'] = true;
$data['message'] = 'product is added to cart';
}
} else {
$data['status'] = false;
$data['errtype'] = 'stok';
}
return json_encode($data);
}
module mo_order.php:
function tambahBelanja() {
$id_produk = $this->input->post('id_produk');
$qty = $this->input->post('quantity');
$this->db->where('id_produk', $id_produk)
->where('stok >', 0);
$Q = $this->db->get('produk', 1);
if ($Q->num_rows() > 0) {
foreach ($Q->result() as $row) {
$data = array(
'id' => $row->id_produk, //id_produk
'qty' => $qty, //qty
'price' => $row->harga, //harga
'name' => $row->nama_produk //nama_produk
);
}
$this->cart->insert($data);
file_put_contents('/tmp/data.txt', var_export(array('id_produk' => $id_produk, 'qty' => $qty, 'item' => $data), true));
return TRUE;
} else {
return FALSE;
}
}
when I try to run that codes, I still can add item to cart although I'm not login as member, and the alert not show up.
how is the right way?
Try
if (!$this->auth->cek_login()) {
$data['status'] = false;
$data['errtype'] = 'login';
}else{ //Add this else here i.e if valid login
if ($this->mo_order->tambahBelanja() === TRUE) {
if ($this->input->post('ajax') <> '1') {
redirect('order');
} else {
$data['status'] = true;
$data['message'] = 'product is added to cart';
}
} else {
$data['status'] = false;
$data['errtype'] = 'stok';
}
}

Categories