Solved

Get values from custom form

Posted on 2014-11-28
10
229 Views
Last Modified: 2014-12-01
I am in a bit of a dilemma and not sure of the best way to proceed.  The code I am using queries php using ajax and returns the data successfully. However, I have a form that is triggered from a click event and what I need to do is capture the values from that form and append to the data that I already have so I can send to php for db processing.

Brief scenario:

If the data == 'New Intake' this triggers the form and when the action button is pressed, capture the form values to join with the existing data and send to php for processing.

I have looked at this for some time now and cannot see how to do this, hence the post. I would be grateful if someone help me find a solution to this. I am using jtable to display and process the data and I have only posted the relevant part of the code because it is quite long. Many thanks

jQuery/Ajax

sendbtn: {
  title: 'Action',
  width: '1%',
  sorting: false,
  edit: false,
  display: function(data) {
    var $image = $('<span><img src="css/themes/lightcolor/icon-action.png" style="display: block; margin: 0 auto; cursor:pointer;"/></span>');

    $image.click(function() {
      var $selectedRows = $('#setActionsScheduleShow').jtable('selectedRows');
      $selectedRows.each(function() {
        var record = $(this).data('record');
        var id = record.id;
        var service = record.service;
        var dept = record.department;
        var activity = record.activity;
        var company = record.company;
        var user = record.user;
        var item = record.item;
        var address = record.address;
        //alert(id + ' ' + service + ' ' + activity + ' '  + dept + ' ' + company); 

        var data = {
          id: id,
          service: service,
          company: company,
          dept: dept,
          activity: activity,
          user: user,
          item: item,
          address: address
        }
        $.ajax({
          type: "POST",
          url: "boxActionTemp.php",
          data: data,
          success: function(data) {
            //alert(data);
            if (data == 'error') {
              notif({
                msg: 'There was an error actioning your request.<br />' + 'Please inform the system administrator.' + 'Thank you.',
                type: "default",
                position: "center",
                width: 490,
                height: 75,
                multiline: true,
                timeout: 6000,
                autohide: true,
                opacity: 0.9,
                fade: 10,
              });
            } else if (data == 'New Intake') {
              //alert ('new Intake');
              $('#rackInput').show();
              var $dialog = $('#rackIntakeForm');
              $dialog.dialog({
                autoOpen: true,
                modal: true,
                title: 'Please input your rack details',
                width: 280,
                height: 280,
                draggable: true,
                resizable: false,
                close: function(event, ui) {
                    $("#rackIntakeForm").validate().resetForm();
                    //$( this ).dialog( "close" );
                    $("#rackIntakeForm").get(0).reset();
                    $("#rack, #column, #row, #bay").val(' ');
                  }
                  // buttons: {
                  //Close: function() {
                  //$( this ).dialog( "close" );
                  //$("#frmreport").get(0).reset();
                  // }
                  // }

              });

            } else {
              notif({
                msg: 'You have successfully actioned your request for ' + activity + '<br /><br /><b><font color="black">' + data + '</b></font>' + '<br /><br />This update was successfully added to the database.<br /><br />Thank you.',
                type: "defaultSuccess",
                position: "center",
                width: 490,
                height: 75,
                multiline: true,
                timeout: 6000,
                autohide: true,
                opacity: 0.9,
                fade: 10,
              });

              $('#setActionsScheduleShow').jtable('load');
            }
          }
        });
      });
    });
    return $image;
  }
}

Open in new window


boxActionTemp.php

<?php
session_start();

$connect = mysql_connect("localhost", "root", "") or die(mysql_error());
//If this Fails at least place it in a JSON so you can see IT
$db = mysql_select_db("sample");

// test vars from jquery form
$id          = mysql_real_escape_string($_POST['id']);
$company     = mysql_real_escape_string($_POST['company']);
$user        = mysql_real_escape_string($_POST['user']);
$activity    = mysql_real_escape_string($_POST['activity']);
$service     = mysql_real_escape_string($_POST['service']);
$item        = mysql_real_escape_string($_POST['item']);
$address     = mysql_real_escape_string($_POST['address']);
$newdate     = $date[2] . '-' . $date[1] . '-' . $date[0];
$Displaydate = $date[0] . '-' . $date[1] . '-' . $date[2];
$qty         = mysql_real_escape_string($_POST['rcyqty']); // never used */
$authorised  = mysql_real_escape_string($_SESSION['kt_name_usr']);
$dept        = mysql_real_escape_string($_POST['dept']);

if ($id == "")
{
    echo 'error';
}
else if ($activity == 'New Intake')
{
    echo 'New Intake';
}
else
{
    $output = 'Company: ' . ' ' . $company;
    $output .= '<br />';
    $output .= 'Address: ' . ' ' . $address;
    $output .= '<br />';
    $output .= 'User: ' . ' ' . $user;
    $output .= '<br />';
    $output .= 'Activity: ' . ' ' . $activity;
    $output .= '<br />';
    $output .= 'Service: ' . ' ' . $service;
    $output .= '<br />';
    $output .= 'Item: ' . ' ' . $item;
    echo ($output);
    
    /* $sql = "INSERT INTO `act` (service, activity, department, company, address, user,  date, quantity, type, new)";
    $sql .= "VALUES ('$service', '$activity', '$dept', '$company', '$address', '$requested', NOW(), '$qty', '$type', 1)";
    $result = mysql_query($sql) or die ('{"opp":"error","box":"' . mysql_error() . '"}'); */
}
?>

Open in new window


html

<form id="rackIntakeForm" method="post">
  <table id="rackTable" border="0">
    <tr>
      <td>Rack:</td>
      <td></td>
      <td><input id="rack" name="rack"></td>
    </tr>
    <tr>
      <td>Column:</td>
      <td></td>
      <td><input id="column" name="column"></td>
    </tr>
    <tr>
      <td>Row:</td>
      <td></td>
      <td><input id="row" name="row"></td>
    </tr>
    <tr>
      <td>Bay:</td>
      <td></td>
      <td><input id="bay" name="bay"></td>
    </tr>
    <tr>
      <td>Size:</td>
      <td></td>
      <td>
        <select id="boxSelect" name="size">
          <option value="" selected> Choose box size </option>
          <option value="S"> Standard </option>
          <option value="P"> Printout </option>
          <option value="O"> Other </option>
          <option value="T"> Transfer </option>
        </select>
      </td>
      <br />
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td><br /><input class="addprofilesubmit" type="submit" name="submit" value="Action"></td>
    </tr>
  </table>
</form>

Open in new window

0
Comment
Question by:peter-cooper
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 43

Expert Comment

by:Rob
ID: 40471173
Simple demo: http://jsbin.com/vowode/1/edit?js,console,output

The idea would be to serialize the forms data and add it to the data you pass via ajax:

$("#rackIntakeForm").serialize()
0
 

Author Comment

by:peter-cooper
ID: 40471457
I am aware of the serialize function but am having trouble adding the values to the data that is passed to ajax. Could you do example please. The link you supplied only deals with the basic coding but not how to merge with existing data. Thanks
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 40471535
Let me suggest a slightly different design concept.  Every AJAX call to the server will send some element of data (otherwise, why bother) so just accept these data elements on the server and keep them there, in the database, 100% of the time.  If you design your application with this idea in mind you will build up a knowledge base about your clients that will rival what Google knows about you.
0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 
LVL 34

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40471787
greetings peter-cooper, , I have read your question and looked at your code here, however I can not clearly see what you may mean by this part -
" capture the form values to join with the existing data and send to php for processing."
You do NOT have any  "existing data"  when you show the   $dialog.dialog  that has this  rackIntakeForm. Ajax processes are asynchronous, the return function IS not used in that Order. . the Ajax return as your success function -
      success: function(data) {
happens After all of the selected rows for -
     $selectedRows.each(function() {
and After the -
    $.ajax({
have completely finished, ,  AND After the PHP server has finished sending all of it's text to the JS return function.

This becomes somewhat complex, due to the Many Rows that could be selected and run with -
    $selectedRows.each(function() {
although you may not be able to select more than one row? ?

IF you can Only have One row selected, you may be able to use the data object that was created for the first ajax, However, you have confusing code (to me) because you use the var data in more than one place you have it as the variable name in the success function AND as the URL parameters in the Ajax send, you might change the Ajax send name to another to avoid a mix up -
 var sendPar = {
  id: record.id,
  service: record.service,
  company: record.company,
  dept: record.department,
  activity: record.activity,
  user: record.user,
  item: record.item,
  address: record.address
  }
$.ajax({
          type: "POST",
          url: "boxActionTemp.php",
          data: sendPar,

Open in new window

in your dialog close you will now need to use the old "sendPar" object and add the rackIntakeForm inputs to it, and THEN send Another Ajax.
else if (data == 'New Intake') {
  $('#rackInput').show();
   var $dialog = $('#rackIntakeForm');
  $dialog.dialog({
     autoOpen: true,
     modal: true,
     title: 'Please input your rack details',
      width: 280,
       height: 280,
       draggable: true,
        resizable: false,
        close: function(event, ui) {
             $("#rackIntakeForm").validate().resetForm();
              $("#rackIntakeForm").get(0).reset();
             sendPar.rack =  $("#rack").val;
             sendPar.column =  $("#column").val;
             sendPar.row =  $("#row").val;
             sendPar.bay =  $("#bay").val;
      $.ajax({
            type: "POST",
            url: "boxActionTemp.php",
            data: sendPar,
            success: function(receive) {
               alert(receive);
             } });
  }
   });

            }

Open in new window

the above code is just a guess from me, and will not work as is. BUT I hope that it shows you some of the areas to get and use data sets in ajax. Please remember that the jquery success function IS an asynchronous callback that can happen a millisecond AFTER the Ajax call , OR can happen a minute AFTER the Ajax call, depending on the SERVER time to finish. And you need to "Store" any original Ajax data that needs to be used in the success function, either in a JS variable (object) , , OR store it on the PHP server in a Session variable with a Unique ID number FOR that particular Ajax call, and return that ID to the success function to send in the next Ajax call.

I may not have fully understood your requirements, but this is my suggestion,
ask questions if you need more info.
0
 

Author Comment

by:peter-cooper
ID: 40471841
Cheers Slick. Got me started in the right direction and before I read your post I had in fact been dabbling with 2 ajax calls. Thank you.
0
 

Author Closing Comment

by:peter-cooper
ID: 40471842
Thanks once again
0
 
LVL 43

Expert Comment

by:Rob
ID: 40471981
Expanding on my initial post, you just concatenate the data together:

e.g.

$(function () {
    var myObject = {
        a: {
            one: 1,
            two: 2,
            three: 3
        },
        b: [1, 2, 3]
    };
    console.log($("#rackIntakeForm").serialize());
    $("#rackIntakeForm").on('submit', function (e) {
        alert(e);
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
            url: 'request.php',
            data: $("#rackIntakeForm").serialize() + '&' + decodeURIComponent($.param(myObject)),
            method: 'post',
            success: function (data) {
                $("#result").html('<pre>'+data+'</pre>');
            }
        });
        return false;
    });
});

Open in new window

0
 
LVL 43

Expert Comment

by:Rob
ID: 40471983
ah well... that's what you get for living in another timezone *laughing*.

You may get something out of what I've posted :)
0
 

Author Comment

by:peter-cooper
ID: 40473409
Thanks Rob. Ever considered moving? :-)
0
 
LVL 43

Expert Comment

by:Rob
ID: 40474345
*laughing* I have, just not that far...
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question