wp_mail not working in my ajax function - functions.php file - ajax

WP_MAIL functionality is not working in my ajax function in functions.php file.
Please have an look on the code and help me out !!
Do i need to load any files for the working of wp_mail function ??
function et_contact_form() { ?>
<script type="text/javascript" >
jQuery('#contact_modal').on('submit', function (e) {
e.preventDefault();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var name = jQuery("#name").val();
var data = {
'action':'et_contact_modal',
'name' : name
};
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
});
</script> <?php
}
add_action( 'wp_footer', 'et_contact_form' );
function et_contact_modal() {
global $wpdb;
$headers .= "Reply-To: test#gmail.com \r\n";
//$headers .= "CC: test#gmail.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$subject = 'New Enquiry From ';
$message .= '<p>' . $_POST['name'] . '</p>';
$message .= '<p></p>';
$mailResult = false;
$mailResult = wp_mail( 'test#gmail.com',$subject,$message, $headers );
echo $mailResult;
}
add_action( 'wp_ajax_et_contact_modal', 'et_contact_modal' );

Sorry people's!!
The code was correct , it was just server issue !!
Thank you.

Related

use route in controller

i'm trying to fetch data(jobs) and display each single job i have route for jobs and route for single job but when i use route in controller i get route not defined even all is good please check my question
ajax call
<script>
$(document).on('click','.submit', function(e) {
var category = $("input[name=category_id]").val();
var location= $(".js-example-basic-single option:selected" ).val();
console.log(location);
$.ajax({
type:'get',
data: {location : location,category : category},
url:'/job_listing',
success:function(data) {
$('.job-list').html(data);
console.log(category);
console.log(location);
}
})
});
function in cotroller
public function show_offers(Request $request){
$category = $request->category;
$location= $request->location;
if($request->ajax()) {
$data = Job_offer::where([
'category_id' => $category,
'location_id' => $location,
])->orwhere('location_id','=',$location)->orwhere('category_id','=',$category)->get();
// ->orWhere('location_id','LIKE','%'.$input.'%')->with('location')->get();
$output = '';
if (count($data)>0) {
$output = '';
foreach ($data as $row){
$output .= '<div class="job-info"> <div class="job_offer-img"><img class="offer-img" src='.'img/'.$row->offer_image.'></div>';
$output .= '<div class="job-title"> <span class="job"> '.$row->offer_title.'</span>';
$output .= '<span class="location">'.$row->location->Name.'</span></div>';
$output .= '<div class="job-contrat"> <span class="contract"> '.$row->type_emploi.'</span></div></div>';
}
$output .= '';
}
else {
$output .= '<li class="list-group-item">'.'No results'.'</li>';
}
return $output;
}
route
Route::get('single_offer/{offer_id}','job_seeker\Job_offers#single_offer')->name('single/offer');
Route::get('job_listing','job_seeker\home_job_seeker#show_offers');
Your routes need to be in routes/api.php file instead of routes/web.php file.
Use like this
href='."{{route('single/offer',['offer_id'=>$row->id])}}".'

Laravel Ajax does not get the value from the form to Controller

In Ajax code I have action = 'contact';, contact is used in route file:
Route::post('contact', array('uses' => 'FormsController#send', 'as' => 'post_form'));
In route file I have FormsController#send it is file php to send email:
$name = Input::get('name');
$getSubject = "Subject of my email";
$myEmail = 'myEmail#gmail.com';
$uid = md5(uniqid(time()));
$eol = "\r\n";
// header
$header = "From: " . $name . " <" . $email . ">\r\n";
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"" . $eol;
$header .= "Content-Transfer-Encoding: 7bit" . $eol;
$header .= "This is a MIME encoded message." . $eol;
// message & attachment
$nmessage = "--" . $uid . "\r\n";
$nmessage .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$nmessage .= "Content-Transfer-Encoding: 8bit" . $eol;
if($name != ''){$nmessage .= "Name: " . $name . "\r\n\r\n";}
// $nmessage .= "Wiadomość:\r\n" . $getMessage . "\r\n\r\n";
$nmessage .= "--" . $uid . "\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "--" . $uid . "--";
$send = mail($myEmail, $getSubject, $nmessage, $header);
Ajax directs to the controller file and bypasses the form, so the controller file does not download any data from the form, and the mail can not be sent. I have no idea how to pass data from the form to the controller file.
My Ajax:
const sendForm = function () {
action = 'contact';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('post', action, true);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
const getMessageSend = document.querySelector("#messageSend");
getMessageSend.innerText = "Thank you for sending an email. You will receive an answer shortly.";
} else {
const getMessageSendError = document.querySelector("#messageSendError");
getMessageSendError.innerText = "An error occurred and the email was not sent.";
}
};
// xmlhttp.open("post", action, true);
// xmlhttp.send();
const token = document.querySelector('meta[name="csrf-token"]').content;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xmlhttp.setRequestHeader('X-CSRF-TOKEN', token);
xmlhttp.send();
};
const sendMail = function() {
options.form.addEventListener('submit', function (e) {
e.preventDefault();
let validate = true;
const elementsRequired = document.querySelectorAll(":scope [formHr]");
[].forEach.call(elementsRequired, function(element) {
const type = element.type.toUpperCase();
if (type === 'TEXT') {
if (!validateText(element)) {validate = false;}
}
});
if (validate) {
sendForm();
// this.submit();
} else {
return false;
}
});
};
My form:
{!! Form::open(['action'=>['FormsController#send'], 'method' => 'post', 'class' => 'form', 'novalidate' => 'novalidate', 'files' => true]) !!}
<input type="text" name="name" placeholder="Name" formHr>
{!! Form::submit('Send', ['class' => 'submit-btn']); !!}
{!! Form::close() !!}
I found a solution. Help me this theme Submit form laravel using AJAX
I just add data to my code:
$.ajax({
type: "POST",
url: 'contact',
data: $(this).serialize(),
success: function () {
$("#messageSend").addClass("message-send");
$("#messageSend").text("Thank you for sending an email. You will receive an answer shortly.");
}
});
Remember to use full version Jquery!

Google recaptcha onepage issue

I've an HTML onepage website.
I want insert google recaptcha 2.0 system but something go wrong with js.
When i click on submit button no success message is shown and no message is sent.
The button Send remains clicked and no further actions happen.
WIth the original php file on bottom the form works. But i've to insert recaptcha, too much spam.
Could someone help?
Thank you
Scipio
HTML CODE
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form name="frmcontact" action="php/send.php" class="contact-frm" method="post">
<input type="text" required placeholder="Nome" name="txtname">
<p class="twocolumn">
<input type="email" required placeholder="Email" name="txtemail">
<input type="tel" placeholder="Phone" name="txtphone">
</p>
<div class="g-recaptcha" data-sitekey="xxx"></div>
<textarea placeholder="Testo del Messaggio" name="txtmessage"></textarea>
<input type="submit" class="button" value="SEND" name="btnsend">
PHP CODE THAT I WANT TO INSERT:
<?php
if(isset($_POST['btnsend']) && !empty($_POST['btnsend'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha- response'])):
//your site secret key
$secret = 'XXX';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//contact form submission code
$name = !empty($_POST['txtname'])?$_POST['txtname']:'';
$email = !empty($_POST['txtemail'])?$_POST['txtemail']:'';
$email = !empty($_POST['txtphone'])?$_POST['txtphone']:'';
$message = !empty($_POST['txtmessage'])?$_POST['txtmessage']:'';
$to = 'XXX';
$subject = 'New contact form have been submitted';
$htmlContent = "
<h1>Contact request details</h1>
<p><b>Name: </b>".$name."</p>
<p><b>Email: </b>".$email."</p>
<p><b>Phone: </b>".$phone."</p>
<p><b>Message: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
//send email
#mail($to,$subject,$htmlContent,$headers);
$succMsg = 'Your contact request have submitted successfully.';
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
else:
$errMsg = '';
$succMsg = '';
endif;
?>
JS CODE:
$('form[name="frmcontact"]').submit(function () {
var This = $(this);
if($(This).valid()) {
var action = $(This).attr('action');
var data_value = unescape($(This).serialize());
$.ajax({
type: "POST",
url:action,
data: data_value,
error: function (xhr, status, error) {
confirm('The page save failed.');
},
success: function (response) {
$('#ajax_contact_msg').html(response);
$('#ajax_contact_msg').slideDown('slow');
if (response.match('success') != null) $(This).slideUp('slow');
}
});
}
return false;
});
ORIGINAL PHP CODE:
<?php
if(!$_POST) exit;
$to = 'gopal#iamdesigning.com'; #Replace your email id...
$name = $_POST['txtname'];
$email = $_POST['txtemail'];
$phone = $_POST['txtphone'];
$subject = 'Support';
$comment = $_POST['txtmessage'];
if(get_magic_quotes_gpc()) { $comment = stripslashes($comment); }
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$msg = "You have been contacted by $name with regards to $subject.\r\n\n";
$msg .= "$comment\r\n\n";
$msg .= "You can contact $name via email, $email.\r\n\n";
$msg .= "-------------------------------------------------------------------------------------------\r\n";
if(#mail($to, $e_subject, $msg, "From: $email\r\nReturn-Path: $email\r\n"))
{
echo "<span class='success-msg'>Thanks for Contacting Us, We will call back to you soon.</span>";
}
else
{
echo "<span class='error-msg'>Sorry your message not sent, Try again Later.</span>";
}
?>

ebay-api "findItemsByKeywords" pagination in codigniter 3

Can anyone help me with this issue?
I'm making an API call with 50 entries per page.
I get results, but how can i display the next page ?
How to use pagination ? i don't have a clue where to start.
I really need some help here.
Thanks
This is the controller
if (!empty($_POST['submit'])) {
$aaa = $_POST['kikozasearch'];
}else {
$aaa = $_POST['kikozasearch'];
}
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = ''; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = $aaa; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findItemsByKeywords";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&paginationInput.pageNumber=$currentpage";
$apicall .= "&paginationInput.entriesPerPage=50";
//$apicall .= "&paginationOutput.totalPages";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
$pic = $item->galleryURL;
$link = $item->viewItemURL;
$title = $item->title;
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div><img src=\"$pic\"></td><td>$title$pag</div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<div class='alert alert-danger'><h4>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h4></div>";
}
echo "We found: ".$resp->paginationOutput->totalEntries . " resaults!";
echo "<div class='alert alert-info'>".$results."</div>";
// echo $resp->paginationOutput->entriesPerPage;
// echo "<br>";
// echo $resp->paginationOutput->totalEntries;
// echo "<br>";
// echo $resp->paginationOutput->totalPages;
echo $currentpage;
echo "/".$resp->paginationOutput->totalPages;
echo "<br />";
$totalpages = $resp->paginationOutput->totalPages;
Here is the post request
<script>
$(document).ready(function(){
$('#form').on('submit', function(info){
info.preventDefault();
$.post('<?php echo base_url();?>index.php/ebayapps/searchitem',
$('#form').serialize(),
function(data){
$('#resaults').html(data);
}
);
}); // keyup
});
</script>
If I understand correctly, you want to load more than one page of results. In this case, you will need to make numerous API requests, depending on the total number of pages you wanted to retrieve in the first place.
So say you want four pages - you need to run your function four times and increment paginationInput.pageNumber in each loop.
I hope this helps.

Laravel passing data using ajax to controller

How do I pass the id from this ajax call to the TestController getAjax() function? When I do the call the url is testUrl?id=1
Route::get('testUrl', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_POST['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
In the end, I just added the parameter to the Route::get() and in the ajax url call too. I changed $_POST['id'] to $_GET['id'] in the getAjax() function and this got my response back
Route::get('testUrl/{id}', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_GET['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
Your ajax's method is GET but in controller you use $_POST to get
value. This is problem.
You can you
$id = $_GET['id'];
But in Laravel, it have a pretty method to do this. It's here. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.
$id = Input::get("id");
If you want, you can filter request type to control exception. Docs here
Determine If The Request Is Using AJAX
if (Request::ajax())
{
//
}
#in your controller function
public function getAjax()
{
#check if request is ajax
if ($request->ajax()) {
//your code
}
return $your_data;
}

Resources