Parse selected form value into jQuery.ajax call - javascript

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(),

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).

echo javascript in php not interpreted

I had to redirect the visitor to another page if something went wrong. Header location couldn't work because there is already some things displayed so I only have the choice to use javascript. Here is a piece of my PHP code :
add_action('frm_field_input_html', 'getDoctypes');
function getDoctypes($field, $echo = true){
$url = 'http://ff/interface/iface.php';
$html = '';
if ($field['id'] == get_id_from_key_frm('doctype')){
$data = array('action' => 'getDoctypes');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'timeout' => 30,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$doctypes = json_decode($return);
if ($return === FALSE || isset($doctypes -> code)){
$wpBaseUrl = site_url();
echo "<script>window.location = '$wpBaseUrl/error-connection-interface/' </script>";
}else{
$html = ">";
foreach ($doctypes as $code => $name){
$html .= "<option value=\"$code\">$name</option>";
}
}
}
if ($echo)
echo $html;
return $html;
}
The problem is when $return === FALSE, instead of executing the script, it just display "window.location = 'http://my_ip/error-connection-interface/'" into the HTML
Any ideas ?
Thanks in advance

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>";
}
?>

form Submit AJAX + PHP

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 ;)

How do I post a radio button and menu selection with ajax and json

I've found several articles on this but nothing that fits my circumstance. I have these radio buttons and drop down menu from which I need to post a selection using ajax in json dataType. Simply put, what do I put in the "WHAT GOES HERE" spot?
Thanks in advance!
<script>
$(function() {
$('#driver').click(function(){
$.ajax({
url:'_resources/_helpers/grader-test.php',
type: "POST",
data:{ /*WHAT GOES HERE?????*/ },//<---WHAT GOES HERE??
dataType: "json",
success: function(result){
$('#jsonstuff').html(result);
console.log(result[0].AVG);
$('#grade').html(result[0].AVG);
}
});
});
});
</script>
<td>
Select:
<select id="extension">
<option value="empty"></option>
<? foreach ($sql as $row){
echo '<option value = "' . $row['extension'] . '">' . $row["tech_fname"] . ' ' . $row["tech_lname"] . ' - ' . $row['extension'] . '</option>';
?>
</select>
</td>
<td>
As Reviewer<input type="radio" class="as_type" name="as_type" value="reviewer"/><br />
As Reviewed<input type="radio" class="as_type" name="as_type" value="reviewed"/>
<input type="button" id="driver" value="Submit" />
</td>
<td id="grade"></td>
And here is grader-test.php:
$ext = $_POST['extension'];// 2752;//
$type = $_POST['as_type'];// "reviewer";//
switch($type){
case "reviewer":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewer_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
case "reviewed":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewed_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
default:
echo "select something";
}

Categories

Resources