cal1fornia
cal1fornia

Reputation: 87

set input value dynamically with php

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

Upvotes: 0

Views: 213

Answers (2)

Drew Dahlman
Drew Dahlman

Reputation: 4972

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/

Upvotes: 3

user1032531
user1032531

Reputation: 26281

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
}

Upvotes: 1

Related Questions