Hello,

I'm really new to HTML/jquery so having some issues with submitting a form to jQuery and showing the results in a div.
What I want ->
Text box: Fill in text
Button: Submit text as POST data with longurl=<text>, and display the result in a div (#shorturl)
I have the following now but it simply refreshes the page and doesn't update the div at all:

HTML:

<body>
 17     <div class="container" id="middle">
 18       <div class="row">
 19         <div class="span10 offset1">
 20           <form class="form-horizontal" method="POST" action="shortify.php" id="longurl">
 21             <input class="input-block-level text-center" type="text" name="longurl" id="longurl" autocomplete="off" placeholder="Paste your long URL here...">
 22             <button class="btn btn-large btn-block btn-primary">Submit URL</button>
 23           </form>
 24           <div class="well well-large" id="shorturl">
 25 
 26           </div>
 27         </div>
 28       </div>
 29     </div>
 30 
 31   </body>

jQuery:

$(document).ready(function(){
 12 $('#longurl').submit(function() {
 13     $.ajax({
 14       data: $(this).serialize(),
 15       type: $(this).attr('method'),
 16       url: $(this).attr('action'),
 17       success: function(response) {
 18         $('#shorturl').html(response);
 19       } 
 20     }); 
 21     return false;
 22 }); 
 23 });

Some help would be awesome. Thanks :)

Dani AI

Generated

Two things are tripping you up here, : (1) the form and the text input share the same id of longurl, which makes $('#longurl') ambiguous, and (2) the browser is doing a normal form submit before your Ajax runs. Give the form its own id and intercept the submit event; this way pressing Enter in the textbox works, and you do not need to bind to a button click (which suggested, but submit keeps keyboard behavior and works even if the trigger changes later).

Example:

<form id="urlForm" method="post" action="shortify.php">
  <input type="text" id="urlInput" name="longurl" placeholder="Paste your long URL here...">
  <button type="submit">Submit URL</button>
</form>

<div id="shorturl"></div>
$(function () {
  var $form = $('#urlForm');
  var $out  = $('#shorturl');
  var $btn  = $form.find('button[type=submit]');

  $form.on('submit', function (e) {
    e.preventDefault();

    $btn.prop('disabled', true);
    $out.text('Working...');

    $.ajax({
      url: this.action,
      method: 'POST',
      data: $form.serialize(),
      dataType: 'html',
      cache: false
    })
    .done(function (html) {
      $out.html(html);
    })
    .fail(function (xhr) {
      $out.text('Request failed: ' + xhr.status + ' ' + xhr.statusText);
    })
    .always(function () {
      $btn.prop('disabled', false);
    });
  });
});

Notes:

  • Duplicated ids are invalid HTML and lead to exactly this kind of event-binding confusion.
  • cache: false mainly matters for GET; for POST it is harmless but not required. Your $.ajaxSetup({ cache:false }) fix worked because your earlier code was effectively issuing a GET.
  • If shortify.php returns JSON instead of HTML later, set dataType: 'json' and render from the parsed object.

Recommended Answers

All 4 Replies

Member Avatar for Member #46692

posting your php file would help dont you think?

The php file doesn't do much, I just wanted to see if I could get the result in the div for now:

<?php
echo "Expected echo output";
?>

Thanks in advance,

hai KamiNuvini,

you have to modify your script code as follows so that you will get your answer

$(document).ready(function(){

    $("button").click(function(){
        var long_url_txt = $("#longurl").val();  // reading value from your text field here
        $.ajax({
            url:"shortify.php",                  // where you want to pass your request
            data:"long_url_value="+long_url_txt,   // passing textfield values to desired php page
            success:function(result){
              $("#shorturl").html(result);  // fetching and placing your result
            }
        });
    }); 

});

please go through the bellow url you will find more information regarding this requirement

http://www.w3schools.com/jquery/ajax_ajax.asp

let me know the stauts

happy coding

Got it working - as a sidenote I also had to add the following to prevent caching:

$.ajaxSetup ({                                                                                                                
    cache: false                                                                                                                
});      

Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.