form Submit AJAX + PHP - javascript

On Sunday, I made a working script to send form data into my database and email with Mandrill.
Since Wednesday, my script doesn't work anymore. I'm trying to find the error but nothing fixed it.
I think I have an error in my PHP script but I don't know where and what.
Console log of my AJAX returns correct data but PHP doesn't do anything. It doesn't receive data.
There is my HTML
<form method="POST" id="formContact" action"#">
<input type="text" placeholder="Prénom" name="name" id="formName">
<input type="email" placeholder="Email" name="email" id="formEmail">
<input type="text" placeholder="Sujet" name="subject" id="formSubject">
<textarea cols="30" rows="10" placeholder="Ton message" name="message" id="formMessage"></textarea>
<button type="submit" id="formSubmit">Envoyer</button>
</form>
JavaScript
$(document).ready(function() {
$('#formContact').submit(function(event) {
var formData = {
'name' : $('#formName').val(),
'email' : $("#formEmail").val(),
'subject' : $("#formSubject").val(),
'message' : $("#formMessage").val()
};
$.ajax({
url: "commons/test.php",
type: "POST",
data: formData,
dataType: 'json',
encode: true
})
.done(function(data){
console.log(formData);
console.log(data);
if( ! data.success){
alert('Error');
}else{
alert('Success');
}
});
event.preventDefault();
});
});
PHP
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('../adm/dbconnect.php'); <- this work well
$data = array();
if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['subject']) && !empty($_POST['message']))
{
// var_dump($_POST['name']);
// var_dump($_POST['email']);
// var_dump($_POST['subject']);
// var_dump($_POST['message']);
$to = 'contact#sheguey.land';
$content = ''.$_POST['message'].'';
$subject = 'Nouveau message de '.$_POST['email'].' - Sheguey Land';
$from = ''.$_POST['email'].'';
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$api_key = 'my mandrill api key';
$content_text = strip_tags($content);
$postString = '{
"key": "' . $api_key . '",
"message": {
"html": "' . $content . '",
"text": "' . $content_text . '",
"subject": "' . $subject . '",
"from_email": "' . $from . '",
"from_name": "' . $from . '",
"to": [
{
"email": "' . $to . '",
"name": "' . $to . '"
}
],
"track_opens": true,
"track_clicks": true,
"auto_text": true,
"url_strip_qs": true,
"preserve_recipients": true
},
"async": false
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);
$req = $bdd->prepare('INSERT INTO contactform (name, email, subject, message) VALUES( :name, :email, :subject, :message)');
$req->execute(array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'subject' => $_POST['subject'],
'message' => $_POST['message']
));
$data['success'] = true;
}else{
$data['success'] = false;
}
echo json_encode($data);
After two days of research (changing PHP script, AJAX script, etc), I don't understand why this don't work anymore.

you might need quotes in formData '"' + $('#formName').val() + '"'

What is the reasoning for the double single quotes?
$content = ''.$_POST['message'].'';
$subject = 'Nouveau message de '.$_POST['email'].' - Sheguey Land';
$from = ''.$_POST['email'].'';
I would just have done it as follows:
$content = (string)$_POST['message'];
$subject = "Nouveau message de ".$_POST['email']." - Sheguey Land";
$from = (string)$_POST['email'];
Does it var_dump the $_POST values after the if statement if you uncomment one?
var_dump($_POST); //as a whole
You may want to set error_reporting(E_ALL); to error_reporting(E_ALL & E_STRICT); which sometimes provides you with more information.

I have find the problem and fixed it.
A .htaccess file was in the same folder as the PHP file, i don't know why it was there. The script work.
Anyway thanks for you help ;)

Related

How can i fetch usermeta in custom php page?

Hellow.
I'm not only a php beginner and but a wordpress beginner.
I try to integrate 3rd-party PHP file and Javascript (For Age Verification using Phone. i.e: SMS Certification) into my wordpress site.
this 3rd-party reference
Using 'add_shortcode', i managed to add 'request function' to my wordpress site. (Reference Url's STEP 1)
if (! function_exists ( 'register_mycustom_agecert_page' ) ) {
function register_mycustom_agecert_page () {
$mid ='**********'; // Given MID(Merchant ID)
$apiKey ='********************************'; // apikey to MID
$mTxId ='***********';
$reqSvcCd ='01';
// Check if registered merchant or not.
$plainText1 = hash("sha256",(string)$mid.(string)$mTxId.(string)$apiKey);
$authHash = $plainText1;
$userName = 'Anonymous'; // User name
$userPhone = '01011112222'; // user Phone
$userBirth ='19830000'; // user Birth
$flgFixedUser = 'N'; // When fixing specific user, use below 'Y' setting.
if($flgFixedUser=="Y")
{
$plainText2 = hash("sha256",(string)$userName.(string)$mid.(string)$userPhone.(string)$mTxId.(string)$userBirth.(string)$reqSvcCd);
$userHash = $plainText2;
}
$foo = '';
$foo .= '<div align="center" class="age-gate-wrapper">';
$foo .= '<form name="saForm">';
$foo .= '<input type="hidden" name="mid" value="' . $mid . '">';
$foo .= '<input type="hidden" name="reqSvcCd" value="' . $reqSvcCd . '">';
$foo .= '<input type="hidden" name="mTxId" value="' . $mTxId . '">';
$foo .= '<input type="hidden" name="authHash" value="' . $authHash .'">';
$foo .= '<input type="hidden" name="flgFixedUser" value="' . $flgFixedUser . '">';
$foo .= 'input type="hidden" id="userName" name="userName"';
$foo .= '<input type="hidden" id="userPhone" name="userPhone">';
$foo .= '<input type="hidden" id="userBirth" name="userBirth">';
$foo .= '<input type="hidden" name="userHash" value="' . $userHash . '">';
$foo .= '<input type="hidden" name="directAgency" value="">';
$foo .= '<input type="hidden" name="successUrl" value="' . esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '<input type="hidden" name="failUrl" value="'. esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '</form>';
$foo .= '<button onclick="callSa()">Proceed to "Age Verification"</button>';
$foo .= '</div>';
echo $foo;
}
add_shortcode( 'register_mycustom_agecert_page', 'register_mycustom_agecert_page');
}
callSa() script.
function callSa()
{
let window = popupCenter();
if(window != undefined && window != null)
{
document.saForm.setAttribute("target", "sa_popup");
document.saForm.setAttribute("post", "post");
document.saForm.setAttribute("action", "https://sa.inicis.com/auth");
document.saForm.submit();
}
}
function popupCenter() {
let _width = 400;
let _height = 620;
var xPos = (document.body.offsetWidth/2) - (_width/2); // Align center
xPos += window.screenLeft; // For dual monitor
return window.open("", "sa_popup", "width="+_width+", height="+_height+", left="+xPos+", menubar=yes, status=yes, titlebar=yes, resizable=yes");
}
And then, i put success.php file in "childtheme-folder/kg/".
(Reference's Step 2, 3)
success.php file.
<?php
// -------------------- recieving --------------------------------------
extract($_POST);
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
echo 'authRequestUrl : '.$_REQUEST["authRequestUrl"]."<br/>";
echo 'txId : '.$_REQUEST["txId"]."<br/><br/><br/>";
$mid ='********'; // Test MID. You need to replace Test MID with Merchant MID.
if ($_REQUEST["resultCode"] === "0000") {
$data = array(
'mid' => $mid,
'txId' => $txId
);
$post_data = json_encode($data);
// Start 'curl'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_REQUEST["authRequestUrl"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
// -------------------- Recieve result -------------------------------------------
echo $response;
// Check If user age is under 20 years old or not.
$pre_age_cert_result = json_decode( $response, true );
if ( isset ($pre_age_cert_result) && ! empty ( $pre_age_cert_result['userBirthday'] ) ) {
$pre_user_input_date = date ( 'Ymd', strtotime ($pre_age_cert_result['userBirthday']) );
$user_input_date = new DateTime( $pre_user_input_date );
$current_date = new DateTime();
$user_input_date->add( new DateInterval( 'P20Y' ) );
if ( $current_date > $user_input_date ) {
$age_cert_check = true;
$age_checking_msg = 'Age Verification: Success';
} else {
$age_cert_check = false;
$age_checking_msg = 'Age Verification: Failed';
}
} else {
$age_cert_check = false;
$age_checking_msg = 'Some Problem.';
}
echo $age_checking_msg;
// Add result of age cert into usermeta.
if ( $age_cert_check === true ) {
echo 'Success - Process 01';
echo '<br>';
if ( is_user_logged_in() ) {
echo 'Success - Process 02';
echo '<br>';
$temp_current_user_id = get_current_user_id();
echo $temp_current_user_id;
if ( $temp_current_user_id !== 0 && $temp_current_user_id !== NULL ) {
echo 'Success - Process 03';
echo '<br>';
$result_cur_time = date( 'Ymd', strtotime("now") );
echo $result_cur_time;
update_user_meta( $temp_current_user_id, 'ageCert', true );
update_user_meta( $temp_current_user_id, 'ageCertDate', $result_cur_time );
} else {
echo 'Failure - Process 03';
echo '<br>';
return;
}
} else {
echo 'Failure - Process 02';
echo '<br>';
$button_link_03 = esc_url( wp_login_url() );
$button_text_03 = esc_html( __( 'You Need to Login.', 'woocommerce' ) );
echo ''.$button_text_03.'';
return;
}
} else {
echo 'Failure - Process 01';
echo '<br>';
return;
}
}else { // if resultCode===0000 is not, display below code.
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
}
?>
Finally i could get "echo 'Success - Process 01". But i can't display neither 'success -Process 02' nor 'Failure -Process 02'.
I think the cause of this is that success.php is not wordpress page. So success.php doesn't have access to wordpress function.
How can i achive my goal?
If it's not possible to fetch usermeta in custom page (like success.php), below can be option ?
Using wordpress Rest-API, send value of $user_input_date. And hook somewhere, like wp_remote_get() ?
Using alternative function which can get usermeta from wordpress.
Grating access to wordpress to success.php page
I would appreciate any reference page or example Code.
Thank you for reading this long article.
Finally i achive my goal - thanks to IT goldman and Json.
i added below 2 lines into success.php
$custom_path = '/wp-load.php file path';
require_once( $custom_path . '/wp-load.php' );
It works !
You can just include "wp-config.php"; as the first line of your php script then you get all wordpress functions, including get_user_meta.
you use use wp_load.php on success.php file
if your folder structure is like this (/wp-content/themes/child-theme/kg/success.php)
in the success.php file add this line
<?php
include_once("../../../../wp-load.php");
echo "test:: " . get_site_url();
wp-load.php which loads all the functions and code for wordpress(bootstraps).

I keep getting a 400 (Bad Request) when submitting a WordPress form using the Fetch API

I am working on a WordPress site and I am trying to convert my jQuery code to vanilla JavaScript (mostly as a learning experience, but also so I don't have to rely on jQuery). The goal is once the form is submitted, instead of going to a thank you page or something else, simply display an overlay over the form saying "Thank you for your message". Again, everything works fine with jQuery/AJAX, but I want to try and get it working with plain JavaScript as well.
Here is the working jQuery code:
jQuery('#myContactForm').on('submit', function () {
var formData = jQuery(this).serializeArray();
formData.push({
name: 'security',
value: ajaxNonce
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: formData
});
jQuery('.form-overlay').addClass('visible');
return false;
});
And here is the working code from functions.php:
<?php
function javascript_variables() { ?>
<script type="text/javascript">
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
var ajaxNonce = '<?php echo wp_create_nonce('secure_nonce_name'); ?>';
</script>
<?php
}
add_action('wp_head', 'javascript_variables');
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$body = 'From: ' . $_POST['full_name'] . '<br />';
$body .= 'Email: ' . $_POST['email'] . '<br />';
$body .= 'Phone: ' . $_POST['phone'] . '<br />';
$body .= 'Message: ' . $_POST['message'] . '<br />';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
And finally, here is the relevant input inside the form:
<input class="form-inputs" type="hidden" name="action" value="send_form" />
Here is what I came up with when trying to use the Fetch API instead of jQuery:
// handle form submission
const formSubmissionHandler = () => {
const form = document.getElementById('myContactForm');
const formOverlay = document.querySelector('.form-overlay');
const formInputs = Array.from(document.querySelectorAll('.form-inputs'));
const formData = [];
form.addEventListener('submit', (e) => {
e.preventDefault();
formInputs.forEach((input) => {
if (!input.name || !input.value) {
return;
}
formData.push({
name: input.name,
value: input.value,
});
});
formData.push({
name: 'security',
value: ajaxNonce,
});
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
// send post request
fetch(ajaxUrl, fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
formOverlay.classList.add('visible');
});
};
document.addEventListener('DOMContentLoaded', formSubmissionHandler);
I've come across the FormData() constructor from searching, not sure where/if I would use that here?
And here is what I wrote in my functions.php file:
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$json_input = json_decode(file_get_contents('php://input'), true);
$body = '';
foreach ($json_input as $key => $value) {
$body = 'From: ' . $value['full_name'] . '<br />';
$body .= 'Email: ' . $value['email'] . '<br />';
$body .= 'Phone: ' . $value['phone'] . '<br />';
$body .= 'Message: ' . $value['message'] . '<br />';
}
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
I am new to all this so if someone could help me out it would be much appreciated. I think my issue is how I am parsing the JSON data in functions.php. Or could I simply not format the data the same in vanilla JS as it's done in jQuery? Thank you!
I know it is probably a bit late for me to post this but incase somebody in future runs into this, here is the deal:
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
here, you are making a json string to pass to the destination URL but you have to remember, Wordpress's ajax parser can't understand data being sent to it as raw json.
$json_input = json_decode(file_get_contents('php://input'), true);
here, you're turning the raw input that you received into an array, but before this, all Wordpress got was a piece of data which is a simple string. So, it doesn't know how to deal with it and what user-defined hook and actions should be fired to validate this.
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
here, you are telling wordpress to expect some request with the 'action' name of 'send_form' and if you got it, pass it to a function named 'send_form'. Wordpress however is not recieving that request with the name 'action'. Hence the error.
The fix, however, is quite simple, just add this request name as a GET to the url you're sending the raw data to and clear it up for wordpress:
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>?action=send_for';
or, the version I prefer:
// send post request
fetch(ajaxUrl + '?action=send_form', fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
and done!
I think once you star to work with fetch() and WP, at least for now (untill Wordpress figures out a way), this could come handy.

For each php loop get results added via AJAX

I have a working AJAX request call, that calls to a PHP file(which has some looping) and depending on some parameters in can take several minutes for the request to be ready. But waiting several minutes is not really user friendly.
How should i modify my code in order to have results outputed in HTML after after each for loop is over?
I understand this streaming effect could be accomplished with API's like web-sockets or socket.io, but I hope I can manage to accomplish this without needing to implement the use of these API's .
Live example witch the effect i am going for:
http://www.brokenlinkcheck.com/
I have made a demo of my code with the core of my logic in it:
PHP File :
<?php
$html = file_get_html($url);
function check_url($a)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $a);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
$good_array = array();
$number = 1;
foreach ($html->find('a') as $element) { // this one should return results first
$a = $element->href;
$check_url_status = check_url($a);
if (!preg_match('/404/', $check_url_status)) {
echo "<p style='color:green'>" . $number . '. ' . $a . " - Works (Response: $check_url_status) </p>";
$good_array[] = $a;
} else {
echo "<p style='color:red'>" . $number . '. ' . $a . " - Broken (Response : $check_url_status) </p>";
}
$number++;
}
array_unique($good_array);
for ($x = 0; count($good_array) > $x; $x++) { // from then on for every ending of this loop - it should add new html output via ajax.
$html = file_get_html($good_array[$x]);
foreach ($html->find('a') as $element) {
$a = $element->href;
$check_url_status = check_url($a);
if (!preg_match('/404/', $check_url_status)) {
echo "<p>" . $number . '. ' . $a . " - Works (Response : $check_url_status) | src: $good_array[$x] </p>";
} else {
echo "<p>" . $number . '. ' . $a . " - Broken (Response : $check_url_status) | src: $good_array[$x] </p>";
}
$number++;
}
}
?>
jQuery AJAX:
$(document).ready(function () {
$("#ajax-btn").click(function () {
$.ajax({
url: "../broken_links",
type: "get",
success: function (result) {
$("#div1").load('http://website.dev/php');
// alert('works');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
(Would be perfect if the solution involved jQuery AJAX, but vanilla JS would also do)
HTML:
<div class="panel panel-default">
<div class="panel-body">
<h2 id='div1'>test</h2>
<button id='ajax-btn'> Change Content</button>
</div>
</div>
Between I'm using Laravel 5.3 Framework so any solutions that involves built in framework features are also welcome!
You won't be able to send partial AJAX updates using PHP. Why don't you get all of the URLs from JavaScript and test them one by one.
$('a').each(function(){
var $anchor = $(this);
// Do Ajax call to check for this URL, directly to that page or your own PHP
$.ajax({
url: "../broken_links",
type: "get",
data: { url: $anchor.attr('href') },
success: function (result) {
$("#div1").load('http://website.dev/php');
// alert('works');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
PHP
<?php
$url = $_GET['url'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
if (!preg_match('/404/', headers['http_code'])) {
echo "<p style='color:green'>" . $number . '. ' . $url . " - Works (Response: $check_url_status) </p>";
$good_array[] = $a;
} else {
echo "<p style='color:red'>" . $number . '. ' . $url . " - Broken (Response : $check_url_status) </p>";
}
?>

fetch JSON data through php code

Method Name: GetAvaiillabiilliity
$mySOAP = <<<EOD
{
"Authentication": {
"LoginId": "username",
"Password": "password"
},
"AvailabilityInput":{
"BookingType":"O",
"JourneyDetails":[{
"Origin":"BOM",
"Destination":"PNQ",
"TravelDate":"10/30/2016"
}],
"ClassType":"Economy",
"AirlineCode":"",
"AdultCount":1,
"ChildCount":0,
"InfantCount":0,
"ResidentofIndia":1,
"Optional1":"0",
"Optional2":"0",
"Optional3":"0"
}
}
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: application/json',
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: ' . curl_error($ch) . "<br />\n");
} else {
echo $result;
}
curl_close($ch);
$data = json_decode($result,true);
$devices = $data['AvailabilityOutput']['AvailableFlights'];
?>
Output: GetAvailabilityResponse
This is the response which we have got from the server side and I want to show this through my php and html code.
{
"ResponseStatus":1,"UserTrackId":"RMYLN97099869978897983977484056886242191","AvailabilityOutput":{"AvailableFlights":{"OngoingFlights":[{"AvailSegments":[{"FlightId":"41","AirlineCode":"9W","FlightNumber":"618","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 10:00:00","ArrivalDateTime":"30\/10\/2016 10:50:00","Duration":"00Hrs 50Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":6940,"YQ":200,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":8254,"Commission":"208.2"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"42","AirlineCode":"9W","FlightNumber":"453","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"HYD","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 03:00:00","ArrivalDateTime":"30\/10\/2016 04:15:00","Duration":"01Hrs 15Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"L","ClassCodeDesc":"L","BaggageAllowed":null,"Adult":{"FareBasis":"L2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"43","AirlineCode":"9W","FlightNumber":"2822","AirCraftType":"73W","Origin":"HYD","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 05:50:00","ArrivalDateTime":"30\/10\/2016 07:05:00","Duration":"01Hrs 15Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"L","ClassCodeDesc":"L","BaggageAllowed":null,"Adult":{"FareBasis":"L2IPO","FareType":"\u000aRefundable","BasicAmount":16540,"YQ":400,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":18965,"Commission":"496.2"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"44","AirlineCode":"9W","FlightNumber":"465","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"MAA","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 07:05:00","ArrivalDateTime":"30\/10\/2016 09:05:00","Duration":"02Hrs 0Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"45","AirlineCode":"9W","FlightNumber":"2491","AirCraftType":"738","Origin":"MAA","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 09:45:00","ArrivalDateTime":"30\/10\/2016 11:25:00","Duration":"01Hrs 40Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":14050,"YQ":600,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":16244,"Commission":"421.5"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"46","AirlineCode":"9W","FlightNumber":"339","AirCraftType":"73W","Origin":"BOM","OriginAirportTerminal":"","Destination":"DEL","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 03:00:00","ArrivalDateTime":"30\/10\/2016 05:05:00","Duration":"02Hrs 5Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"47","AirlineCode":"9W","FlightNumber":"365","AirCraftType":"73H","Origin":"DEL","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 08:30:00","ArrivalDateTime":"30\/10\/2016 10:40:00","Duration":"02Hrs 10Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":13600,"YQ":800,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":16031,"Commission":"408"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"48","AirlineCode":"9W","FlightNumber":"463","AirCraftType":"73H","Origin":"BOM","OriginAirportTerminal":"","Destination":"MAA","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 02:55:00","ArrivalDateTime":"30\/10\/2016 04:50:00","Duration":"01Hrs 55Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPOA","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"49","AirlineCode":"9W","FlightNumber":"2491","AirCraftType":"738","Origin":"MAA","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 09:45:00","ArrivalDateTime":"30\/10\/2016 11:25:00","Duration":"01Hrs 40Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":13800,"YQ":600,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":15979,"Commission":"414"},"Child":null,"Infant":null}],"SupplierId":"1"}]}],"ReturnFlights":null}}}
my php code
<?php
echo 'Flifht checking';
echo '<br><hr>';
foreach ($devices as $device){
echo '<h4>';
echo $device['FlightNumber'];
echo '</h4>';
}
?>
How to get all flight information in json code ?
So how to get this json data AvailabilityOutput":{"AvailableFlights":{"OngoingFlights":[{"AvailSegments". I can't understand depth tree structure.
Here you have a possible implementation to go through all the flights.
I changed $devices name to $availableFlights to make the example easier to understand.
$data = json_decode($result, true);
$availableFlights = $data['AvailabilityOutput']['AvailableFlights'];
echo 'Flifht checking';
echo '<br><hr>';
foreach ($availableFlights['OngoingFlights'] as $availableFlight) {
foreach ($availableFlight['AvailSegments'] as $availSegment) {
echo '<h4>';
echo 'Flight Number: ' . $availSegment['FlightNumber'];
echo '</h4>';
echo '<p>Origin: ' . $availSegment['Origin'] . ' - Destination: ' . $availSegment['Destination'] . '</p>';
}
}
The output here is:
Flifht checkingFlight Number: 618Origin: BOM - Destination: PNQFlight Number: 453Origin: BOM - Destination: HYDFlight Number: 2822Origin: HYD - Destination: PNQFlight Number: 465Origin: BOM - Destination: MAAFlight Number: 2491Origin: MAA - Destination: PNQFlight Number: 339Origin: BOM - Destination: DELFlight Number: 365Origin: DEL - Destination: PNQFlight Number: 463Origin: BOM - Destination: MAAFlight Number: 2491Origin: MAA - Destination: PNQ
Also, a little trick: if you want to see the whole json tree easily, you can use this:
echo "<pre>";
print_r($availableFlights);
echo "</pre>";
(I thought it could be helpful to understand the data structure)

Parse selected form value into jQuery.ajax call

I have this drop down form - doing a sorting call.
What I can't manage to do is to parse the current selected value from the form in the ajax. URL.
The Form:
<form name="sortby">
<select name="order_by" onchange="myFunction()">
<option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'choose') echo ' selected="selected"'; ?> value="choose">Sort By</option>
<option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'OVERALL_VALUE') echo ' selected="selected"'; ?> value="OVERALL_VALUE">Most Popular</option>
<option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'PRICE') echo ' selected="selected"'; ?> value="PRICE">Price (low to high)</option>
<option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'PRICE_REVERSE') echo ' selected="selected"'; ?> value="PRICE_REVERSE">Price (high to low)</option>
<option<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'QUALITY') echo ' selected="selected"'; ?> value="QUALITY">Rating</option>
</select>
</form>
The ajax.
<script>
function myFunction() {
$('.searchtable').addClass('hide');
$('.spinner').removeClass('hide');
$.ajax({
type: 'GET',
data: {'name':'<?php echo $name;?>','arrival':'<?php echo $arrival;?>','departure':'<?php echo $departure;?>','guests':'<?php echo $numberOfGuests;?>','order_by':$('#order_by').value},
url: 'hotels/hotelSortBy.php',
success: function (data) {
//alert('data loaded succesfully');
alert(this.url);
$('.searchtable').replaceWith(data);
},
error: function (xhr) {
alert('data not loaded');
// do what ever you want to do when error happens
}
})
.done(function() {
$('.spinner').addClass('hide');
$('.searchtable').removeClass('hide');
});
}
</script>
hotelSortBy.php
<?php
$url = 'xxx';
$url .= '&cid=55505';
$url .= 'xxxx';
//$url .= '&customerUserAgent='[xxx]
//$url .= '&customerIpAddress='[xxx]
$url .= '&locale=da_DK';
$url .= '&currencyCode=DKK';
$url .= '&destinationString=' . strval($_GET['name']);
$url .= '&supplierCacheTolerance=MED_ENHANCED';
$url .= '&searchRadius=50';
$url .= '&arrivalDate=' . strval($_GET['arrival']);
$url .= '&departureDate=' . strval($_GET['departure']);
$url .= '&room' . strval($_GET['rooms']) . '=' . strval($_GET['numberOfGuests']) . ',,';
$url .= '&sort='. strval($_GET['order_by']);
$url .= '&numberOfResults=20';
$header[] = "Accept: application/json";
$header[] = "Accept-Encoding: gzip";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = json_decode(curl_exec($ch), true);
include '/hotelTables.php';
?>
Order_by value from the form is not pasted into ajax data to apply to the url.
First you need an id not just a name attribute:
<select id="order_by" name="order_by" onchange="myFunction()">
^^^^ id
Then put the value of order_by in the data section, not the url. Mixing data section and putting query params explicitly in the url is a bad idea as some params could get lost in some browsers when doing that. Choose one or the other:
$.ajax({
type: 'GET',
data:
{
'order_by':$('#order_by').val(),
'name': '<?php echo $name;?>',
'arrival': '<?php echo $arrival;?>',
'departure': '<?php echo $departure;?>',
'guests': '<?php echo $numberOfGuests;?>'
},
url: 'hotels/hotelSortBy.php',
.....
I question the wisdom of printing all that PHP in there. I think probably those should be fields in the form, even if hidden fields (i.e. <input type='hidden' />).
$.ajax({
type: 'GET',
data: {'name':'<?php echo $name;?>','arrival':'<?php echo $arrival;?>','departure':'<?php echo $departure;?>','guests':'<?php echo $numberOfGuests;?>'},
url: 'hotels/hotelSortBy.php?&order_by='+$('form').find('select').val(),

Categories

Resources