Forums

Chronoforms - project log and queries!

Mizpah 12 Aug, 2009
Ok folks,

Am in the midst of looking at a rather complex chronoforms/chronodata requirement, and as usual am working through it bit by bit. This thread is intended to server a couple of purposes, to track my progress as I go, to keep all of the info in one place, to make asking for help as simple as possible ^^, and to hopefully help anyone else out who is trying to do anything similar!

Background:

J! 1.5.14 site, running latest Chronoforms, Chronodata, AEC, Jomsocial and JUGA as major components. This will be based on a customised RT template, but am using the standard template in the dev environment for now.

The premise of the site is to allow people to upload data as a form submission if they have a valid subscription (handled by AEC). The data uploaded needs to be viewable, filterable and searchable. The results of a query will be a chronodata view. The registration process may also be handled by chrono, however this is being left till last due to issues between AEC wanting to handle the registration (and having AEC integration) and the additional functions I have in chrono.

Where we are today:

A joomla site with JUGA (access control) fully working and tested, with custom content and menu links based on having an active subscription (from AEC). Now to do something with the custom menus and content!

On the chrono side we have three identical test upload forms (upload_gold, upload_silver and upload_bronze), each reached via a menu link controlled by JUGA and AEC. Thus if you are logged in as a gold user the link takes you to the gold form etc etc.
All Three forms are linked to the same table, and contain the same fields. As of now only the title of the forms are different.
There is a chronodata view to show all data in the table in question.

Challenge One:

To give each user (by plan type) a number of active uploaded data sets they are allowed. i.e. silver can have up to 10 active items, Gold 15, and Bronze will be pay-as-u-go with a pay pal submission per form submission.

I have the ability to fire an SQL statement on joining a plan, so am considering building a table with

userid - subs (submissions) allowed - current subs.

and populating the columns for the user when they obtain the subscription.

Then we need to adjust the silver and gold forms to do the following - *on form load* (we don't want this on form submit) look up the user ID, compare current subs with allowed subs, and then either proceed, or throw an error message. Then on form submit increment the value for current subs by +1.

Any thoughts before I dig myself a nice deep hole ?
GreyHead 12 Aug, 2009
Hi Mizpah,

The only bit I ahve any question over is
userid - subs (submissions) allowed - current subs.

My general feeling is that it's safer to keep a table of Subscriptions and run the count each time than to try to keep a running total updated and accurate.

Bob
Mizpah 12 Aug, 2009
Thats a nice idea actually Greyhead, it may make life easier when it comes to sold listings vs live listing (each listing has a hidden status field, it controls how they are displayed and in this instance if we should be includng the item in a count or not!) *goes off to grab an sql book*
Mizpah 18 Aug, 2009
ok - after digging out an online mysql resource we have the following simple query!


SELECT COUNT(1)as "Live Cars Listed"
FROM `jos_chronoforms_cars`
WHERE `status` = 'forsale'


So we now need to extend the where clause to only return the results of the currently logged in user!

We have 'cf_user_id', and in jos_users an autoincrementing id. I don't suppose there is a relationship between the two ? It would be easy to add AND 'cf_user_id' = 'result of another query' I suppose!

Off to look for some more documentation unless anyone answers and beats me to it!

I note two things - currently cf_user_id seems to always have a value of '0' that might just be as all of my test form sunmissions are from the link in the backend, I need to check!

I wonder if I should just lookup 'jos_user_id' each time a form is submitted and add that to the table and just query on that ?


PS: I amy be missing somthing but a search on '+cf_user_id' in the forums hasnt turned up a definition of the field and where its populated from!
Mizpah 18 Aug, 2009
ok, halfway there. I have decided to get the ID of the user logged in at the time, and add it to a jos_user_id table (or whatever the joomla one shoudl be called!)

The following (simple!) code prints it in my form:


<?php
$user =& JFactory::getUser();
echo $user->get('id') ;
?>


Now to work out how to stick it into the database automagically!
Mizpah 18 Aug, 2009
Well, Its seems that cf_user_id IS jos_users_id 😶 - I was trying to do somthign already accomplished, I just happened to keep filling in my test form from the backend link! (hence the value was always 0)

It does leave me a question on the code I should use on submit to introduce a value however!


$sql = "INSERT INTO `uglybety_csedev`.`jos_chronoforms_cars` ( `jos_user_id` ) VALUES ('$user->get('id')')"; 
$sql = @mysql_query($sql); 


Is the code I was trying (in the forms managment on submit box), and neither a hardcoded value i.e. '101' OR a variable '$user->get('id')' would introduce anything to the column in question - can anyone point out what I am missing ?
Mizpah 19 Aug, 2009
ok some progress! But as always more to do 🤣

We have now managed to get the currently logged in user id, and the number of `forsale` uploads by that user.

it looks like this, and is placed in the php form code:


<?php

//A built in joomla function with an argument to get 'id' over say 'name'
$user =& JFactory::getUser(); 
echo "This value should be the logged in joomla user id: "; 
echo $user->get('id'); 
?>
<br />
<br />
<?php
//This query below was a nightmare! I got confused between (`) and (') and had to debug including the above $user var for ages, 
//however it works and gives me the number of rows uploaded  by the logged in user, that are ALSO 'forsale'.
echo "This value should be number of existing records found created by the user id above: "; 
$query = "SELECT COUNT('cf_id') FROM `jos_chronoforms_cars` WHERE `status` = 'forsale' AND `cf_user_id` = "." ".$user->get('id')." " ; 
//stick the query into the $result array 
$result = mysql_query($query);  
// Just runing echo $array now only gives the resource pointer! resource #115 is not a helpfull piece of info!!
// Stick the $result into another sql function to get the actuall data referenced by the pointer
$row = mysql_fetch_array($result); 
//Now output the data I wanted in the first palce!
echo $row[0];
?>


The (more)complicated part!

I need to build on what I have already done, to effectively check number of uploads to date, vs the (active) subscription type, based on the logged in user, to decide if to allow the form to load (or not).

I think it therefore needs to look like the following:

I have the following tables:

jos_cse_plans - it has a fields called plan, name and uploads (amongst others). (table manually created by me)
jos_acctecp_plans - it has a field called id, status and plan (amongst others. The ID is the joomla user ID of the person the subscription plan belongs to.

I need to run this query php code at the very top of a form.

What I now need to do is get the value returned by "$user->get('id')" (example: 68), and use it to select a row in jos_acctexp_plans that matches 'id' (there should only be one), then check that status = 'active' on that row and get the value of the field called 'plan' in that row.
If the value of `status` in that row is NOT active, I need to run code from a given part of an elseif loop rather than show the form!
I then need to look up jos_cse_plans and find the (again should only be one) row that matches the value of 'plan' that I just grabbed, and get the value of 'uploads'.

I am guessing I need to populate a bunch of $vars with the results of the above query, to use in logic that would be somthing like this:

if (no user id returned in $user)
{load code for a page inviting the user to log in}
elseif (if `status` = 'expired')
{load code for a page, reinviting to subscribe}
elseif (if `status` = 'banned')
{load code for a page inviting the user to 'go away' !}
elseif (compare $row[0] (from before) to 'uploads' - if $uploads => $row[0])
{ load code for a page saying 'Sorry $username you have the $planname subscription and have used $uploads and have none left! please click here to purchase more')
else
{include the code for the form!} //finally!

I will then need to include on the form a count showing how many uploads the user has left!

So where does this leave us ? I think I have a fair idea of the elseif loop - what I really dont know how to do is to elaborate on the sort of query I produced earlier to give me the logic I now need as described above!!

So, as usuall I hope that the example at the top of the post helps sombody searching the forums, and I hope that some other knowlagable person can give me a kickstart as to how a query and values from 3 tables might work!

Thanks in advance,

Mizpah
GreyHead 19 Aug, 2009
Hi Mizpah,

This query below was a nightmare! I got confused between (`) and (') and had to debug including the above $user var for ages,

I know that you solved this but here's the guide to MySQL quoting for other users:

In MySQL query statements MySQL will do it's best to resolve clausess iwthout quotes but any ambiguity will lead to problems!! It's best to add quotes your self to start with.

a) backtucks `` are used to distinguish table and column names like `#__users` or `user_id`.

b) Single quotes are used to identify strings like 'John Smith' or 'Islas Baleares'

c) No quotes are needed for integers or numbers but single quotes will do no harm.

d) Because single quotes are used by MySQL it's best to build the query string inside PHP double quotes like
$query = ". . .";

e) Simple PHP variable names can be used as they are
$query = ". . . `user_id` = $user_id . . .";


f) Compound PHP variables or expressionsmust be wrapped in ".." to demarcate the variable - AND in single quotes if they are a string
$query = ". . . `country` = '".$country['name']."' . . .";


g) It makes code easier to read if you use UPPERCASE LETTERS for MySQL terms
$query = "SELECT `name`, `email` FROM `#__users` WHERE `id` = '".$user->id." ;" ;


h) To maximise flexibility you should use the Joomla table prefix placeholder '#_' instead of 'jos'. 99% of Jooomlinstallations use jos as a prefix - but not 100%.

Bob
GreyHead 19 Aug, 2009
Hi Mizpah,

What I now need to do is get the value returned by "$user->get('id')" (example: 68), and use it to select a row in jos_acctexp_plans that matches 'id' (there should only be one), then check that status = 'active' on that row and get the value of the field called 'plan' in that row.
If the value of `status` in that row is NOT active, I need to run code from a given part of an elseif loop rather than show the form!
I then need to look up jos_cse_plans and find the (again should only be one) row that matches the value of 'plan' that I just grabbed, and get the value of 'uploads'.


This should work I think:
$query = "
  SELECT a.`status`, c.`uploads`
    FROM `#__acctexp_plans` AS a
      JOIN `#__cse_plans` AS c ON a.`plan` = c.`plan`
    WHERE `id` = ".$user->id." ;
";

This will return status and uploads so you'll need to check status to decide what to do next.

Bob
Mizpah 26 Aug, 2009
Thanks Bob!

After a very frustrating week with no internet (/sigh don't we just love British Telecom!) we have been able to move this on again!

The basis of the soulution was exactly that query - here we now have it working in anger with all of the parts 'joined up'! Note the simplistic error conditions, and I plan to reurn to this to add case statements to handle the various subscription status that might exist! (I just check for != 'active' at the moment, and thats not quite clever enough!).


<?php
//Get the currently logged in Joomla User, set to $userid
$user =& JFactory::getUser();
$userid = $user->get('id');

// Get number of uploads by logged in user, set to $uploaded
$query = "SELECT COUNT('cf_id') FROM `jos_chronoforms_cars` WHERE `status` = 'forsale' AND `cf_user_id` = "." ".$userid." " ; 
$result = mysql_query($query); 
$row = mysql_fetch_array($result);
$uploaded = $row[0];

// Get the status of the logged in users subscription, set to $status
// Get the number of allowed uploads based on the subscription above, set to $upallow 
$query = "
  SELECT a.`status`, c.`uploads`
    FROM `jos_acctexp_subscr` AS a
      JOIN `jos_carsaving_uploads` AS c ON a.`plan` = c.`plan`
    WHERE a.`userid` = ".$userid." ;
";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
$status = $row[0] ;
$upallow = $row[1] ;
?> 
<!-- The below is a debug block to show the values obtained -->
<div>
<span class="alert">
<p>
Here are the current $vars and the values:<br />
The logged in user: <?php echo $userid ; ?><br />
The number of live uploads: <?php echo $uploaded ; ?><br />
The status of the subscription: <?php echo $status ; ?><br />
The number of uploads allowed by the subscription: <?php echo $upallow ; ?> 
</p>
</span>
</div>
<!-- This if/else block checks the $vars to determine if the form can be used.  The form is contained within the final else statement. -->
<?php 
if ( $userid == '0') {
?>
<div>
<!-- This is the condition for userid 0 (admin or test link)) -->
<span class="note"><p>Hmm, have you clicked the test link again ? Logged in user is userid 0 !!</p></span>
</div>
<?php
} elseif ( $status != 'Active') {
?>
<div>
<!-- This condition states that the sub is not active  To Do: Need to add  case statement here for each possibility! -->
<p> I am sorry there is a problem with your subscription! </p>
</div>
<?php
} elseif ( $uploaded >= $upallow) {
?>
<div>
<!-- This condition states that uploads are exceeded for the subscription -->
<p> It looks like you have exceeded your upload allowance for this subscription! </p>
</div>
<?php
} else {
?>
<!-- No other conditions apply, all is well with the world (allegedly) so load the form! -->
** CHRONOFORMS FORM GOES HERE **
<?php
}
?>


There is only one small deviation from the solution you provided in the query: 'WHERE `userid` = ".$userid." ;' had to become ' WHERE a.`userid` = ".$userid." ;'

Now onto my next challange - and new terratory once more. How to (optionally) use an existing web service that I have a schema for - and to use that to pre-populate the fields in the form, based on the user submitting a registration number - before submitting the form itself to the server. The theory is that 80% of the time, a reg would be typed in, and submitted, the page would refresh with the form fields prepopulated, and the user would then submit the form in the usual way. 20% of the time they would just fill the form in, without getting any data first.

Am currently trying to find some examples using PHP not ASP to get the job done!!

As always many thanks for your help and advice in helping get to where I needed to be, hopefullyt somebody somewhere will find this writeup usefull, if anyone does have any questions fire away I will do my best 🤣

/Miz
Mizpah 27 Aug, 2009
ok, time to change tangents!

I am now trying to add more intellegence to the basic form, now that we have ascertained the subscriptions and access aspects.

I am trying to consume the webservice found here:

https://www.carwebuk.com/CarweBVRRB2Bproxy/carwebvrrwebservice.asmx?op=strB2BGetVehicleByVRM - this is a commercial product that I am testing!

The aim is to provide a vehicle registration (vrm) lookup via post or get (I assume post as it effects the form?), to populate certain parameters in the form.

Options:

1) A single page form with a 'Lookup VRM' button, all of the fields we want the lookup to populate, and the form submit button. If I want to populate some of the fields of the form by using the lookup, I would assume ajax has to be involved. The rest of the fields would then be filled in and only on submit would I want the form committed to the database.

2) A multipage form, with the first page containing the vrm lookup or skip options, and the second page containing the fields - either prefilled or empty. The user would then add images and a description, and submit.

My assumption in both cases is that I need to somehow run the results through an xml parser, to serialise things so I can build an array, and output parts of the array with $vars, then populate the fields with the $vars ?

http://onlamp.com/pub/a/php/2004/01/15/simplexml.html
and
http://paulstamatiou.com/how-to-parse-xml-with-php5

Look like good bets for further info!

My preference is for option one if that is possible!


Initial testing:

I have this simple form code: (with some obscured values)

<input type="hidden" name="strUserName" value="*****">
<input type="hidden" name="strPassword" value="*****">
<input type="hidden" name="strClientRef" value="Mizpah">
<input type="hidden" name="strClientDescription" value="Initial Testing">
<input type="hidden" name="strKey1" value="*****">
<input type="hidden" name="strVersion" value="0.26.1">
<table>
<tr>
<td class="frmText">strVRM:</td>
<td><input class="frmInput" type="text" size="50" name="strVRM"></td>
</tr>
<tr>
<td></td>
<td align="right"> <input type="submit" value="Invoke" class="button"></td>
</tr>
</table>


The actionurl is set to 'https://www.carwebuk.com/CarweBVRRB2Bproxy/carwebvrrwebservice.asmx/strB2BGetVehicleByVRM'

When I use this in IE8, the following is returned:


  <?xml version="1.0" encoding="utf-8" ?> 
- <GetVehicles release="8.1" environment="Production" lang="en-US" xmlns="">
- <ApplicationArea>
- <Sender>
  <LogicalId>0</LogicalId> 
  <Component>CarweBVRRWebService</Component> 
  <Task>strB2BGetVehicleByVRM</Task> 
  <ReferenceId>0</ReferenceId> 
  <AuthorizationId>0</AuthorizationId> 
  <CreatorNameCode>0</CreatorNameCode> 
  <SenderNameCode>0</SenderNameCode> 
  <SenderURI>http://www.carwebuk.uk.com</SenderURI> 
  <DealerNumber /> 
  <StoreNumber /> 
  <AreaNumber /> 
  <DealerCountry /> 
  <Language>en-GB</Language> 
  <DeliverPendingMailInd>0</DeliverPendingMailInd> 
  <Password /> 
  <SystemVersion /> 
  </Sender>
  <CreationDateTime>2009-08-27T16.25.00Z</CreationDateTime> 
  <BODId /> 
- <Destination>
  <DestinationNameCode>1</DestinationNameCode> 
  <DestinationURI>84.45.60.102</DestinationURI> 
  <DestinationSoftwareCode>1</DestinationSoftwareCode> 
  <DestinationSoftware>VRRB2B</DestinationSoftware> 
  <DealerNumber /> 
  <StoreNumber /> 
  <AreaNumber /> 
  <DealerCountry>UK</DealerCountry> 
  </Destination>
  </ApplicationArea>
- <DataArea>
- <Error>
- <Header>
  <DocumentDateTime>2009-08-27T16.25.00Z</DocumentDateTime> 
  </Header>
  </Error>
- <Vehicles>
- <Vehicle>
  <BodyStyle>MOTOR CARAVAN</BodyStyle> 
  <CherishedTransferDate /> 
  <CherishedTransferMarker>false</CherishedTransferMarker> 
  <ColourCurrent>WHITE</ColourCurrent> 
  <ColourCurrentCode>N</ColourCurrentCode> 
  <ColourOriginal /> 
  <ColourOriginalCode /> 
  <ColourLast /> 
  <ColourLastCode /> 
  <ColourLastDateOfChange /> 
  <ColourPrevCount>0</ColourPrevCount> 
  <CO2>0</CO2> 
  <DateFirstRegistered>2006-10-04</DateFirstRegistered> 
  <DateOfFirstRegistrationUK /> 
  <DVLAYearOfManufacture>2006</DVLAYearOfManufacture> 
  <DateOfPreviousKeeperAcquisition /> 
  <DateOfPreviousKeeperDisposal /> 
  <DVLA_Code>N1600</DVLA_Code> 
  <DVLA_MakeCode>N1</DVLA_MakeCode> 
  <DVLA_ModelCode>600</DVLA_ModelCode> 
  <DVLA_Make>FIAT</DVLA_Make> 
  <DVLA_Model>DUCATO 15 JTD SWB</DVLA_Model> 
  <DVLA_Vehicle_Description /> 
  <DVLA_WheelPlanDesc>2-AXLE-RIGID BODY</DVLA_WheelPlanDesc> 
  <EngineNumber>4236212</EngineNumber> 
  <EngineCapacity>2800</EngineCapacity> 
  <ExportDate /> 
  <ExportMarker>0</ExportMarker> 
  <FuelDescription>DERV, DIESEL, GAS OIL, HEAVY OIL, KEROSENE, PARAFFIN, TVO (tractor vaporising oil)</FuelDescription> 
  <FuelType>DIESEL</FuelType> 
  <GrossWeightKG>3500</GrossWeightKG> 
  <ImportDate /> 
  <ImportMarker>false</ImportMarker> 
  <ImportMarkerFromNorthernIreland>false</ImportMarkerFromNorthernIreland> 
  <IssueDateOfLatestV5>2006-10-04</IssueDateOfLatestV5> 
  <NumberOfPreviousKeepers>0</NumberOfPreviousKeepers> 
  <ScrappingDate /> 
  <ScrappingMarker>0</ScrappingMarker> 
  <ScrappedRemovedMarker>false</ScrappedRemovedMarker> 
  <ScrapStatus>Not marked as scrapped</ScrapStatus> 
  <StartDateOfCurrentKeeper /> 
  <UsedBeforeFirstRegistrationMarker>false</UsedBeforeFirstRegistrationMarker> 
  <VIC_TestDate /> 
  <VIC_TestResult /> 
  <VIN_Original_DVLA>ZFA24400007814176</VIN_Original_DVLA> 
  <VRM_Curr>RX56EZZ</VRM_Curr> 
  <VRM_NorthernIreland /> 
  <WheelPlan>C</WheelPlan> 
  <AbbreviatedTransmission>M</AbbreviatedTransmission> 
  <AccelerationTo100KPHSecs /> 
  <ArrangementOfCylinders>IN LINE</ArrangementOfCylinders> 
  <Aspiration>TURBO CHARGED</Aspiration> 
  <BodyStyleDescription>CHASSIS CAB</BodyStyleDescription> 
  <Bore /> 
  <BusSeatingCapacity>1</BusSeatingCapacity> 
  <CO_GtoKm /> 
  <Combined_EngineCapacity>2800</Combined_EngineCapacity> 
  <Combined_ForwardGears>5</Combined_ForwardGears> 
  <Combined_FuelType>DIESEL</Combined_FuelType> 
  <Combined_Make>FIAT</Combined_Make> 
  <Combined_Model>DUCATO 15 SWB JTD C/C</Combined_Model> 
  <Combined_Transmission>MANUAL</Combined_Transmission> 
  <Combined_VIN>ZFA24400007814176</Combined_VIN> 
  <Combined_VINLast8>07814176</Combined_VINLast8> 
  <CountryOfOrigin>ITALY</CountryOfOrigin> 
  <DateOfThirdPrevKeeperAcquisition /> 
  <DateOfThirdPrevKeeperDisposal /> 
  <DateOfFourthPrevKeeperAcquisition /> 
  <DateOfFourthPrevKeeperDisposal /> 
  <DateOfFifthPrevKeeperAcquisition /> 
  <DateOfFifthPrevKeeperDisposal /> 
  <Delivery>FUEL INJECTION</Delivery> 
  <DriveAxle>FRONT</DriveAxle> 
  <DriveType>4X2</DriveType> 
  <DVLAForwardGears /> 
  <DVLATransmission /> 
  <EngineLocation>FRONT</EngineLocation> 
  <EngineManufacturer>FIAT</EngineManufacturer> 
  <EngineModelCode>8140.43S</EngineModelCode> 
  <EuroStatus /> 
  <FrontSteerHGV>0</FrontSteerHGV> 
  <FuelConsumptionCombined_Ltr100km /> 
  <FuelConsumptionExtraUrban_Ltr100km /> 
  <FuelConsumptionUrbanCold_Ltr100km /> 
  <FuelConsumptionCombinedMPG /> 
  <FuelConsumptionExtraUrbanMPG /> 
  <FuelConsumptionUrbanColdMPG /> 
  <FuelTypeAbbreviated>D</FuelTypeAbbreviated> 
  <ForwardGears>5</ForwardGears> 
  <HC>0</HC> 
  <HeightMM /> 
  <IntroductionDateToUK>2002-09-01</IntroductionDateToUK> 
  <KerbWeightMin /> 
  <KerbWeightMax /> 
  <LengthMM /> 
  <LoadLengthForVans>0</LoadLengthForVans> 
  <lrHandDrive /> 
  <ManufacturerBuildDate /> 
  <MarketSegment>LCVs (Heavy Vans 2601-3500 Kgs)</MarketSegment> 
  <MarqueDescription>FIAT</MarqueDescription> 
  <MassInService>0</MassInService> 
  <MaximumNettPower>45</MaximumNettPower> 
  <MaximumPowerAtRPM /> 
  <MaximumPowerBHP /> 
  <MaximumPowerInKW /> 
  <MaximumSpeedKPH /> 
  <MaximumSpeedMPH /> 
  <MaximumTechnicallyPermissableMass>990</MaximumTechnicallyPermissableMass> 
  <MaximumTorqueAtRPM /> 
  <MaximumTorqueLbFt /> 
  <MaximumTorqueNM /> 
  <ModelRangeDescription>DUCATO</ModelRangeDescription> 
  <ModelSeries>244</ModelSeries> 
  <ModelVariantDescription>15 SWB JTD C/C</ModelVariantDescription> 
  <ModelYear /> 
  <NOX>0</NOX> 
  <NumberOfCylinders>4</NumberOfCylinders> 
  <NumberOfDoors /> 
  <NumberOfValvesPerCylinder /> 
  <OriginalSalesType>P</OriginalSalesType> 
  <ParticulatesGtoKm>0</ParticulatesGtoKm> 
  <PayloadForVans>1605</PayloadForVans> 
  <PowerWeightRatio_MotorcyclesOnly>0</PowerWeightRatio_MotorcyclesOnly> 
  <RoofHeightForVans>0</RoofHeightForVans> 
  <SeatingCapacityInclDriver>2</SeatingCapacityInclDriver> 
  <Seats /> 
  <SoundLevelEngineSpeed>3940</SoundLevelEngineSpeed> 
  <SoundLevelDriveBy>74</SoundLevelDriveBy> 
  <SoundLevelStationary>86</SoundLevelStationary> 
  <CW_EngineCapacity>2800</CW_EngineCapacity> 
  <Stroke /> 
  <TechPermMaxTowableMassOfTrailer_Braked>0</TechPermMaxTowableMassOfTrailer_Braked> 
  <TechPermMaxTowableMassOfTrailer_Unbraked>0</TechPermMaxTowableMassOfTrailer_Unbraked> 
  <Transmission>MANUAL</Transmission> 
  <UnladenWeightForVans>1695</UnladenWeightForVans> 
  <ValveGear /> 
  <VehicleCategoryCode>DC</VehicleCategoryCode> 
  <VehicleCategoryDescription>LCVs (Heavy Vans 2601-3500 Kgs)</VehicleCategoryDescription> 
  <VIN_MVRIS>ZFA24400007814176</VIN_MVRIS> 
  <VIN_Verified /> 
  <VRM_MVRIS>RX56EZZ</VRM_MVRIS> 
  <WheelbaseForVans /> 
  <WidthMM>2024</WidthMM> 
  <VRM_Change1 /> 
  <VRM_Change2 /> 
  <VRM_Change3 /> 
  <datPNCRecordDate /> 
  <strForceCode /> 
  <strMessageType /> 
  </Vehicle>
  </Vehicles>
  </DataArea>
  </GetVehicles>


However in Chrome and it returns an otherwise blank page something akin to this:

'0 CarweBVRRWebService strB2BGetVehicleByVRM 0 0 0 0 http://www.carwebuk.uk.com en-GB 0 2009-08-27T15.50.17Z 1 84.45.60.102 1 VRRB2B UK 2009-08-27T15.50.17Z MOTOR CARAVAN false WHITE N 0 0 2006-10-04 2006 N1600 N1 600 FIAT DUCATO 15 JTD SWB 2-AXLE-RIGID BODY 4236212 2800 0 DERV, DIESEL, GAS OIL, HEAVY OIL, KEROSENE, PARAFFIN, TVO (tractor vaporising oil) DIESEL 3500 false false 2006-10-04 0 0 false Not marked as scrapped false ZFA24400007814176 RX56EZZ C M IN LINE TURBO CHARGED CHASSIS CAB 1 2800 5 DIESEL FIAT DUCATO 15 SWB JTD C/C MANUAL ZFA24400007814176 07814176 ITALY FUEL INJECTION FRONT 4X2 FRONT FIAT 8140.43S 0 D 5 0 2002-09-01 0 LCVs (Heavy Vans 2601-3500 Kgs) FIAT 0 45 990 DUCATO 244 15 SWB JTD C/C 0 4 P 0 1605 0 0 2 3940 74 86 2800 0 0 MANUAL 1695 DC LCVs (Heavy Vans 2601-3500 Kgs) ZFA24400007814176 RX56EZZ 2024'

when I select view source it does not seem to be aware of the xml structure!






So - Questions!

1) Trying to find any code examples of anything akin to option 1 or 2 above.
2) Am still a little in the dark as to how I should be obtaining the XML to interrogate for each submission - all examples that I can find either obtain the XML via http post (as I have done above), and then output raw XML to a new page, or read it directly from a file (in the example of XML parsers i.e. php 5's simplexml). As per my simple test above, I guess I need to load the results into a $var somehow, and not generate a new page with output - then load that $var into an XML parser - take the output (an array) and set the default value of the fields in the form to those $vars ??
3) Am I correct in thinking that my largest aim atm, is to get the result of a query into an array - work out how to update it - then I can start to do things with it!
4) Do we have any examples in the chronoforms community of populating form fields with $vars that are dynamically looked up ?


Anybody care to correct my thinking or give me a poke in the correct direction ? First time ive tried to use a web service - I thought I had already managed the hardest part with the subscriptions side of things 🤣

For reference, the suppliers of the webservice, can only help with .net code examples of how to use it!

Cheers in advance!

/Miz
Mizpah 27 Aug, 2009
Progress!

The following code gives me the basics of consuming a web service, and getting the results into an array I can do something with!

Note that I have obfusicated some elements of the URL with ******

(Bob, Max, if you want these details if you happen to be looking into any of this please just yell!)


<?php
// Grab the XML file content via a cURL transfer and store as a variable ($data)
$request_url = "http://www.carwebuk.com/CarweBVRRB2Bproxy/carwebvrrwebservice.asmx/strB2BGetVehicleByVRM?strUserName=********&strPassword=*******&strClientRef=Mizpah&strClientDescription=Test&strKey1=*******&strVRM=RX56EZZ&strVersion=0.26.1";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch)
//Pass the content of $data to the SimpleXML Function, output simpleXML to $xml
$xml = new SimpleXMLElement($data);
// Show the simpleXMLObject structure currently loaded from the XML file into the $xml var
echo "<pre>";
var_dump($xml);
echo "</pre>";
?>


God Bless PHP5's simpleXML function!!

So what do we have now ?

Well we can within a form page, max a webservices query, and generate an array of data.

Now to do somthing with it!

It seems that understanding xpath, and ajax is next on my list.

I am going to build a test form, with a Vehicle reg field, a Make field, a Model field
and a submit button. The aim will be to have a user type into the VRM field, and autopopulate the defaults for the other two fields without a page refresh. The user can then edit the fields (if needed) and if happy, hit submit to commit the data to the database.

I guess I need to have a java function called in the vehicle registration fields 'onchange()' element.
I also assume I will need in the url string for the web service request to replace the hard coded registration used for testing with a $variable.

I am a little concerned with passing all of the data in a url string - will that expose anything (such as our account password with the service provider) via view page source ?

I am hoping to glean what I need to know from http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html - however if anyone else has any chronoforms ajax examples please let me know!

And of course all help gratefully appreciated!
Mizpah 27 Aug, 2009
The beginnings of the JavaScript (I hope!)

/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
  try {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e2) {
    xmlHttp = false;
  }
}
@end @*/

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  xmlHttp = new XMLHttpRequest();
}

                
function callServer() {
  // Get the VRM from the web form
  var vrm = document.getElementById("vrm").value;
  var state = document.getElementById("state").value;
  // Only go on if we have a value for VRM!
  if ((city == null) || (city == "")) return;
   // Build the URL to connect to
   // Again, lots of details are hardcoded here - want to review and change
  var url = "http://www.carwebuk.com/CarweBVRRB2Bproxy/carwebvrrwebservice.asmx/strB2BGetVehicleByVRM?strUserName=***********&strPassword=*********&strClientRef=Mizpah&strClientDescription=Test&strKey1=******&strVRM="+ escape(vrm)"&strVersion=0.26.1";
  // Open a connection to the server
  xmlHttp.open("GET", url, true);
  // Setup a function for the server to run when it's done
  xmlHttp.onreadystatechange = updatePage;
  // Send the request
  xmlHttp.send(null);
}


function updatePage() {
  if (xmlHttp.readyState == 4) {
    var response = xmlHttp.responseText;
  //need a line here that runs the previous php code!
  //need multiple lines here that get values via xpath, and set them to a php $var
  //need lines here to update fields in the chronoform, with the new $vars
  }
}


Ok, this is not tried in anger yet, am going to need to work out what to put into function updatepage() !!

Hopefully this is moving along the right lines however!
Mizpah 03 Sep, 2009
Roundup and new help request:

We now have a form that:
[list]
  • Only loads if the user has a valid subscription (determined by sql queries), otherwise a relevant error is displayed.

  • Can consume a webservice via php, return the xml into a parser (simplexml) and build an array - using a value from the form!

  • Can retrieve the simpleXML data from the array, using ajax, and output results as text into the form
  • [/list]

    What I am am now stuck on (again 🙄 ) is that final step!

    Heres (another) test form used to illustrate the current issue:

    I have the following javascript:
    
    var xmlhttp
    
    function showCar(str)
    {
    if (str.length==0)
      {
      document.getElementById("test").innerHTML="";
      return;
      }
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
      {
      alert ("Your browser does not support XMLHTTP!");
      return;
      }
    // The file containing my php function!
    var url="vrm.php";
    // Building the url string with a variable to be called by the function
    url=url+"?q="+str;
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
    }
    
    function stateChanged()
    {
    if (xmlhttp.readyState==4)
      {
      document.getElementById("test").innerHTML=xmlhttp.responseText;
      }
    }
    
    function GetXmlHttpObject()
    {
    if (window.XMLHttpRequest)
      {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      return new XMLHttpRequest();
      }
    if (window.ActiveXObject)
      {
      // code for IE6, IE5
      return new ActiveXObject("Microsoft.XMLHTTP");
      }
    return null;
    }
    


    The following form (used to test):
    
    VRM: <input type=text name="vrm" onblur="showCar(this.value);" />
    Marque: <input type="text" id="marque"  />
    Model: <input type="text" id="model" />
    <p>Test Output:<span id="test"></span></p>
    


    And here is the function vrm.php (with values in the url masked)

    <?php
    //Set a value to 'q' (part of the url used to call this)
    $q=$_GET["q"];

    // Grab the XML file content via a cURL transfer and store as a variable ($data)

    $request_url = "http://www.carwebuk.com/CarweBVRRB2Bproxy/carwebvrrwebservice.asmx/strB2BGetVehicleByVRM?strUserName=********&strPassword=********&strClientRef=Mizpah&strClientDescription=Test&strKey1=********strVRM=$q&strVersion=0.26.1";
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);

    //Pass the content of $data to the SimpleXML Function, output simpleXML to $xml

    $xml = new SimpleXMLElement($data);

    // Assign some values from the simpleXMLObject structure currently loaded into the $xml var

    $marque = $xml->DataArea->Vehicles->Vehicle->Combined_Make;
    $model = $xml->DataArea->Vehicles->Vehicle->Combined_Model;

    //test output - confirms the the lookup is using the vrm correctly, and functioning!
    print_r($xml);
    echo $model;
    echo $marque;
    echo $q;
    ?>



    So - I have a form using ajax, using the webservice, passing variables from the form ($q - the registration) - and returning results dynamically as text at the bottom.

    And the part I am now stuck on ?

    How the blazes can I return $marque and $model as default vales in the fields dynamically ?

    As I have discovered you can't pass variable between javascript and php, I have (after much overuse of google - in fact thats how I coded everything here ^^) tried variations on:

    document.getElementById("marque").setAttribute('value', <?php print $marque ?>);

    in function statechanged() = but no cigar!

    So, I'm pleased with what I have but not quite there yet, any 'proper' programmers care to give me a leg up ?
    This topic is locked and no more replies can be posted.