Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass form value to PHP variable with AJAX call?

Having issues anyone has any ideas? I have only posted was is necessary for the code. I basically have an HTML form I want to pull the value from a field on a form before it's submitted run an ajax call and populate another field. I think if I could get that Txt that is entered in the form over to a PHP variable on the modcreate.php it will work. because if I manually enter the details without the variable it works.

mainpage.php

Relevant parts from form

  <tr>
    <th>Service Tag:</th>
    <th><input type="text" id="inputTag" name="inputTag" value="" onblur="this.value=this.value.toUpperCase()"></td>
  </tr>

and

  <tr>
    <th>Model:</th>
    <th>
       <input type="text" id="inputModel" name="inputModel" value=""> 
       <a href="#" id="updateBtn">Populate</a>
       <div id="spinner">
          <img src="\images\ajax-load.gif" alt="Loading..."/>
       </div>
    </th>
  </tr>


 <script type="text/javascript" src="\js\jquery-latest.js"></script>
 <script type="text/javascript"> 
 $('#updateBtn').click( function(e) {
    //to disable the click from going to next page
    e.preventDefault();
    $.ajax({
       url: "modcreate.php",
       data: { 'txt1': $('#inputTag').val() },
       success: function(data) {
       }
    });
 });
 </script>

modcreate.php

<?php 

$field1value = $_GET['txt1'];
    $file_string = file_get_contents('blahblah.com/'.$field1value);
    preg_match("/<title>Product Support for (.+)\| Dell/i", $file_string, $matches);
    $print = "$matches[1]";
    echo $print;
?>

******Solution****** my ajax call was missing the part where it sent the data back to the form field

here is what the working ajax looks like now thanks guys for all the pointers

 <script type="text/javascript" src="\js\jquery-latest.js"></script>
 <script type="text/javascript"> 
 $('#updateBtn').click(function(e){
     //to disable the click from going to next page
     e.preventDefault();
     $.ajax({
         url: "modcreate.php",
         data: { 'txt1': $('#inputTag').val() },
         success: function(data) {
            $('#inputModel').val(data); //this was the missing part
         }
     });
 });
</script>
like image 201
user1548769 Avatar asked Oct 14 '13 20:10

user1548769


1 Answers

<script type="text/javascript"> 
 $('#updateBtn').click(function(e){
    //to disable the click from going to next page
    e.preventDefault();
    $.ajax({
            url: "modcreate.php",
            data: 'data="{ "txt1": '+$('#inputTag').val()+' }"',
            success: function(data){


          }
     }
);
});
</script>

On server side:

$income_data = json_decode($_GET['data'], true);
$field1value = $income_data['txt1'];
like image 62
dr.dimitru Avatar answered Oct 05 '22 22:10

dr.dimitru