How can I get my search bar work with Google? - javascript

I have this search bar and I can't connect it to Google as a search functionality, I tried with this guy's code but I couldn't:
<form id="frmSearch" action="index.html" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search"><span class="fa fa-search"></span></button>
</div>
</form>
Thanks in advance!

You could use an AJAX call to a php page where you are going to implement cURL to get data from google searching url!
Of course you will need to code your own cURL in PHP: PHP + curl, HTTP POST sample code?
here you can find how to implement it!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector("form#frmSearch");
form.onsubmit = function() {
let keyword = encodeURIComponent(this.querySelector("input#keyword").value);
$.ajax({
url: `./php_curl_file.php?q=${encodeURIComponent(keyword)}`,
type: 'GET',
error: (err) => {
throw new Error(err);
},
success: (searchData) => {
console.log( searchData );
}
});
return false;
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmSearch" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" id="keyword" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search">
<span class="fa fa-search"></span> Search
</button>
</div>
</form>

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

recaptcha v3 form not submiting

Im trying to avoid recaptcha v3 timeout by delaying execution until it is submited. Sadly the submit button does nothing when I press it. Here is my code.
JAVASCRIPT
<script>
grecaptcha.ready(function() {
document.getElementById('contactForm').addEventListener("submit", function(event) {
event.preventDefault();
grecaptcha.execute('xxxxxx', {
action: 'homepage'
}).then(function(token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
document.getElementById('contactForm').submit();
});
}, false);
});
</script>
HTML
<form method="POST" action="<? echo $url . '/nueva/'; ?>" id="contactForm">
<div class="form-group row">
<label class="col-3 col-form-label" for="palabra">address</label>
<div class="col-9">
<input id="address" name="address" type="text" class="form-control here">
</div>
</div>
<div class="form-group row">
<div class="offset-3 col-9">
<button name="submit" type="submit" class="btn btn-primary btn-block">Enviar</button>
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
</div>
</form>
I guess that it's php & javascript,
My code is ASP.NET MVC & JQuery, but you can try that
Javascript
grecaptcha.ready(function() {
document.getElementById('enviar').addEventListener("click", function(event) {
return new Promise((res, rej) => {
grecaptcha.ready(function () {
grecaptcha.execute('xxxxxx', { action: 'homepage' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
});
}, false);
});
HTML
<button id="enviar" name="submit" type="submit" class="btn btn-primary btn-block">Enviar</button>

Your session has expired. on ajax form post laravel

I have the following html snippit from my view and js code to handel the form request.
$('#quick-enquiry').on('submit', function(e) {
e.preventDefault();
$(".submit").prop("disabled", true);
data = $(this).serialize();
action = $(this).attr('action');
$.ajax({
type: 'POST',
url: action,
data: data,
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#quick-enquiry").trigger("reset");
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$("#response-msg").toggleClass('uk-alert-danger uk-alert-success');
$('.print-error-msg').find('ul').append("<li>" + data.success + "</li>");
setTimeout(function() {
$('.print-error-msg').fadeOut();
$(".submit").prop("disabled", false);
UIkit.modal("#modal-quick-enquiry").hide();
}, 3000);
} else {
printMessageErrors(data.error);
}
}
});
});
function printMessageErrors(msg) {
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$.each(msg, function(key, value) {
$('.print-error-msg').find('ul').append("<li>" + value + "</li>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/css/uikit.min.css" rel="stylesheet" />
<form action="{{ route('frontend-postEnquiry') }}" method="POST" id="quick-enquiry">
<input type="hidden" id="tour-id" value="1">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Full Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="text" placeholder="Full Name" id="fullName" name="fullName">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="email" placeholder="Email" id="email" name="email">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Message</label>
<div class="uk-form-controls">
<textarea class="uk-textarea uk-form-width-large" rows="4" placeholder="Some Message...." id="enquiryMessage" name="enquiryMessage"></textarea>
</div>
</div>
<p class="uk-text-right">
<button class="uk-modal-close-default" type="button" uk-close></button>
<button class="uk-button uk-button-primary submit uk-width-1-1" type="submit">Send</button>
</p>
</form>
With the above code I'm getting
419
Sorry, your session has expired. Please refresh and try again.
I've set CSRF-TOKEN in ajax and in head section also, but seems like my js code is not picking up csrf token.
I would be very thankful if anyone could highlight the mistake I've made above.
Try using this:
{{ csrf_field() }} instead of #csrf
419 error is mostly because of CSRF token issues.

Link in keyup function is not working

Here is screen shot of my problemI am using codeigniter and ajax.When keyup function is call on search bar then data is shown in suggestion box but when i click on link which is shown on suggestion box then this click is not working.No error of any script file.
Here is code of my view file:
<div class="container-fluid my_searchbar">
<div class="container my_searchbar_container">
<div class="nav nav-justified navbar-search navbar-nav">
<form class="search navbar-search" method="post" action="index.html" >
<div class="input-group">
<input type="text" name="search_area" id="search_area" placeholder="Search Area" class="form-control input-lg">
<div class="input-group-btn">
</div>
<input type="text" name="search_pro" id="search_pro" placeholder="Search Professional Category" class="form-control input-lg">
<ul id="show_search_pro" class="results" >
</ul>
<div class="input-group-btn">
Search
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Here is my ajax code in view file.
$('#search_pro').keyup(function(){
// alert($(this).val());
var location_field = $('#search_area');
var search_cal_field = $(this);
$.ajax({
type: 'POST',
url: 'http://localhost/JustClick/User/search_professional',
cache : false,
dataType : 'html',
data :{location_id:location_field.val(), category_id:search_cal_field.val()},
success:function(data)
{
$('#show_search_pro').html(data);
}
});
});
Here is code of my controller through using ajax i get data on view page:
public function search_professional()
{
if($this->input->is_ajax_request())
{
$professional = $this->UserModel->search_professional($this->input->post('location_id',true),$this->input->post('category_id',true));
foreach ($professional as $row)
{
echo '
<li>
<a class="s_pro" href="'.base_url('Professional/show_professional_detail/'.$row->pro_id).'">'.$row->firstname.' '.$row->lastname.'<br /><span>Description...</span></a></li>';
}
}
else
{
show_404();
}
}
Help me how i solve this problem.

Form doesn't submit on callback

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?
Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.
You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Categories