0

I have PHP function for URL shortening (like goo.gl or bit.ly) and it returns shortened link with echo. I want to put returned link into input without refreshing page (variable is in PHP).

I know it's a bit incomprehensible so:

  1. user pastes URL in input
  2. PHP function shortens it and returns shortened URL
  3. shortened URL is displayed under input (I want to display this in input without refreshing)

My code:

<?php

function shortUrl($url)
{

    $id = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
    $ip = $_SERVER['REMOTE_ADDR'];
    $date = date("Y-m-d");
    $hour = date("H:i:s");
    $user = $_SESSION["user"];


    require_once 'db.php';

    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
    {
        die("Database error. (1)");
        exit();
        //die($conn->connect_error);
    } 

    $sql = "INSERT INTO links (id, ip, user, link, date, hour) VALUES ('".$id."', '".$ip."', '".$user."', '".$url."', '".$date."', '".$hour."')";

    if ($conn->query($sql) === TRUE) 
    {
        echo 'http://blabla.ru/'.$id;
    }
    else 
    {
        echo 'Connection error. (2)';   
        //echo $conn->error;    
    }

    $conn->close();
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
cal1fornia
  • 87
  • 7
  • 2
    What if `$id` value is exists in the database for different url ? That is not related to the question though. Read about [Ajax](http://www.w3.org/2006/Talks/0524-www-AjaxWAI.pdf) – Rayon Oct 05 '15 at 17:34

2 Answers2

3

Ajax is perfect for this. Say you have your input, the user pastes into it - you are listening for a value change on that input. Once that happens you take the value of that input and post it to http://example.com/your-shortern.php or something with the link as a param.

Once it runs it will return via that echo, your ajax success function will take that data and set that as the value in the input.

https://jsfiddle.net/rzan9hdr/3/ is an example ( SUPER SIMPLE )

For those who have come later here is the final solution that uses a button click to trigger the ajax https://jsfiddle.net/rzan9hdr/5/

Drew Dahlman
  • 4,952
  • 1
  • 22
  • 34
  • 1
    @RayonDabre you could do it with 'GET' as well. – Drew Dahlman Oct 05 '15 at 17:48
  • 1
    Not only "could" you do it with `GET`, you "should" do it with `GET`. – user1032531 Oct 05 '15 at 18:01
  • "should" is questionable... depends on your situation. Since this is CREATING a url you would `POST`but you could also do it with `GET` but you're really only getting the return value from a create action... http://stackoverflow.com/a/18511298/1171470 – Drew Dahlman Oct 05 '15 at 18:04
  • 1
    @DrewDahlman Sorry, I really didn't look at what his server code is doing. As it is updating the database, he should use POST and not GET. – user1032531 Oct 05 '15 at 18:07
  • thanks, its working perfectly, but how can I change to not update value on paste but on submit click? – cal1fornia Oct 05 '15 at 18:29
  • thanks for help but now its updating when i go mouseover, not on the button click (input type submit), how to do this? (first time working with ajax, sorry) – cal1fornia Oct 05 '15 at 18:38
  • 1
    Ahh so you could just have a button https://jsfiddle.net/rzan9hdr/5/ and watch for the click on that. you don't need a full form submission. – Drew Dahlman Oct 05 '15 at 18:59
1

If you want to echo the new URL on the page, then you need to refresh the page.

Alternatively, you could allow the user to input the URL into an input field or whatever, then use an ajax call to send the URL to your server, have your server determine the new URL and send it back to the client. Since you are changing the state of the server, use a POST request instead of a GET request (see https://en.wikipedia.org/wiki/Idempotence). Maybe something like the following...

$('#input1).change(function(){
   $.POST( "yourserver.php", {oldURL:$( "'#input1t" ).val()}, function( newURL ) {
      $( "'#input1t" ).val(newURL);  //Might need to do something to prevent another change event
   });
});

yourserver.php

<?php
shortUrl($_POST['oldURL'])

function shortUrl($url)
{
  //Your posted code
}
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • 1
    jQuery is not tagged in the question! php script can echo error as well, do you want error to be set as value of input field ? – Rayon Oct 05 '15 at 17:48
  • 1
    @RayonDabre Ajax is not tagged in the question as well, however, it will be needed if the original poster doesn't wish to refresh the page. jQuery is just JavaScript and I am not saying the jQuery library or any library needs to be used, however, I do believe it better describes intent if the user is just staring off. For a production server, you shouldn't be displaying any system generated errors. – user1032531 Oct 05 '15 at 18:00
  • If you are mentioning jQuery in the answer and the question is not tagged for jQuery then you must provide satisfactory reason for using it. As far as Ajax in cencerned, OP was not aware of the concept called as Ajax hence the question of tagging it in the question is out of context. In this situation, a simple javascript block of code will do the job so jQuery is unnecessary. – Rayon Oct 05 '15 at 18:58
  • 1
    @RayonDabre With all due respect, bla bla bla. I selected a language to reply to the question, and the selected answer consciously used the same language. – user1032531 Oct 06 '15 at 00:22