When users submit form, in php fields are validated. If there is some error php return echo message that there is an error (it doesn't return an ERROR to ajax). So the ajax is still "success".
If I comment grecaptcha.reset(); in the ajax success, and when user submits the form for the second time then $response != null && $response->success returns false in php.
How to fix this, so that there is no grecaptcha.reset() after ajax successs, and that it is enough for user to pass the captcha for only once.
Here is the reCAPTCHA in the html form:
<div class="g-recaptcha" style="display:inline-block;" data-sitekey="6LdDlHIUAAAAAD3hgpRSSsNpS7SaRILGNTNiyak_"></div>
Here is the jQuery:
jQuery('#some_form').submit(function(e){
e.preventDefault();
var FormData = jQuery(this).serialize();
jQuery('.buttonHolder').css('display', 'none');
jQuery('#spinner-1').css('display', 'block');
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
dataType : 'json',
data : {
action : 'some_form',
security : rml_obj.check_nonce,
data1 : FormData
},
success : function( response ) {
PUM.open(7939);
//alert(checkbox_chk);
jQuery('.pum-content').html(response.message1);
jQuery('.copy-url').html(response.message2);
jQuery('.buttonHolder').css('display', 'block');
jQuery('#spinner-1').css('display', 'none');
//grecaptcha.reset();
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
},
});
});
And here is the php code for testing reCAPTCHA:
require_once "recaptchalib.php";
$secret = "6LdDlHIUAAAAALFlTOx-9T63cODtjs7eno******";
$response = null;
$reCaptcha = new ReCaptcha($secret);
$data = $_POST[ 'data1' ];
parse_str($data, $output);
$var1 = $output['var1'];
$var2= $output['var2'];
if ($output["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$output["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//insert data into db ...
header("Content-type: application/json; charset=utf-8");
echo json_encode(
array("message1" => 'message1',
"message2" => 'message2')
)
} else {
header("Content-type: application/json; charset=utf-8");
echo json_encode(
array("message1" => 'error reCAPTCHA')
}
Thaks ArtisticPhoenix for the good advise. After further investigating the same reCAPTCHA response cannot be validated twice. Changes in php fields validation have fixed my issue.
Related
we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
Requirement :
I want to show the message "completed" once if we got response from browser :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function(){
var selected = [];
$('.assigneeid-order:checked').each(function() {
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response){
response = $.parseJSON(response);
$.each(response, function(index, val) {
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
In an ajax call, the member success is being used when the request succedeeds. You can use this method to inform the user the server gave a success response.
success: function(response){
//Your code here to inform the user
response = $.parseJSON(response);
$.each(response, function(index, val) {
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
You can use the member error the same way to tell the user that the server indicated that the request failed.
error: function(response)
{
//not good, tell it to the user
}
Hello,
You can add a div in display none in your HTML and put it in display block when you have an answer from the broswer.
In your success function in your ajax code, you put the code to do it.
Example:
$('#completed-message').text('Completed');
$('#completed-message').css('display', 'block');
I'm new to php and stuck in my tracks here, so any help is appreciated. I've written a few functions in a JS file to render and update a gallery view for a WordPress template I made. From the updateGallery() function, I make an AJAX call after pressing a submit button on the page, but am receiving a "parsererror."
Arguments(3) [{…}, "parsererror", SyntaxError: Unexpected token A in JSON at position 0 at parse (<anonymous>)
at Ut (https://…, callee: ƒ, Symbol(Symbol.iterator): ƒ]
I tried the code for the API request directly in my WP template to render a response and it worked as expected, but when I try to incorporate my script I get the error and I can't figure out what's causing it.
JS
function updateGallery() {
var county = $("#county").val();
jQuery(".galleryGrid").fadeOut("fast", function() {
console.log("ajax request");
jQuery(".galleryGrid").html("").hide();
$.ajax({
type : "GET",
dataType : "JSON",
url : ajax.url,
data : {
action: "get_gallery_data",
county_id : county
},
error: function(response, error) {
console.log(arguments);
alert("Failed because: " + error);
},
success : function(response) {
if(response.type === "success") {
console.log("Success")
renderGrid(response.data);
}
}
});
});
}
PHP
add_action("wp_ajax_nopriv_get_gallery_data", "get_gallery_data");
add_action("wp_ajax_get_gallery_data", "get_gallery_data");
function get_gallery_data() {
$county_id = $_REQUEST[county_id];
$base_api_url = "https://some.api.com/";
$filters = array(
"field" => "field_153",
"operator" =>"is",
"value" => $county_id
);
$filters_url = rawurlencode(json_encode($filters));
$api_url = $base_api_url."?filters=".$filters_url;
$request = wp_remote_get($api_url, array(
"headers" => array(
"Application-Id" => "5xxxxxx",
"REST-API-KEY" => "0xxxxxx",
),
));
$body = wp_remote_retrieve_body($request);
$output = json_decode($body, true);
echo $output;
die();
};
$output = json_decode($body, true);
//Change
$output = json_encode($body, true);
i have a problem in ajax, indeed, i try to send value with ajax to my upload function before submit.
But when i check the $_POST array in my php code, there is only the value of the form, and not from the ajax, and I don't know why.
Here is my code :
HTML:
<button id="btn_saisie" class="btn btn-app saver adddocu" ><i class="fa fa-save whiter"></i></button>
<form action="/uploader/adddocu" id="form_saisie" class="form_saisie" method="POST" enctype="multipart/form-data">
<input type="file" name="document" class="val_peage form-control form_num" id="document" data-rest="document" placeholder="Document">
<input type="text" name="description" class="val_parking form-control form_num" id="description" data-rest="description" placeholder="Description">
JS :
$( ".adddocu" ).click(function() {
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2'); });
function api_sendvalue_adddoc(){
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$.ajax({
type: 'POST',
url: '/uploader/adddocu',
data: {pays:pays, magasin:magasin},
success: function(data){
alert(data);
$("#form_saisie").submit();
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
}); }
PHP:
public function adddocu(){
$path = './asset/upload/pdf/';
$path2 = '/asset/upload/pdf/';
$config['upload_path'] = $path;
$config['encrypt_name'] = false;
$config['file_ext_tolower'] = true;
$config['allowed_types'] = 'pdf';
// die(var_dump($_POST));
$this->load->library('upload', $config);
foreach($_FILES as $id => $name)
{
$this->upload->do_upload('document');
$upload_data = $this->upload->data();
$url = $path2 . $upload_data['file_name'];
$data = array('nom' => $upload_data['raw_name'], 'description' => $_POST['description'], 'url' => $url, 'user_id' => '17');
$this->db->insert('pdf', $data);
}
redirect("/login/docu");
}
So, when I var_dump the $_POST array, I only have the value of "description", and not of "pays" and "magasin".
Can you help me please?
Thanks for your time.
Seems like you are accessing localstorage value , you are posting it somewhere and then submiting the form.
More you are submiting the form which dont have this pays & magasin so i have a trick using which you can achieve it.
Create two hidden inputs inside your HTML form like
<input type="hidden" name="pays" id="pays">
<input type="hidden" name="magasin" id="magasin">
Now before ajax call give them values after getting it from local storage, like this.
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$("#pays").val(pays);
$("#magasin").val(magasin);
$.ajax({ .... });
Continue your code and enjoy.
Hopefully it will work for you.
The issue is because you are not preventing the form from being submit normally, so the AJAX request is cancelled. Instead of using the click event of the button, hook to the submit event of the form and call preventDefault(). Try this:
$('#form_saisie').submit(function(e) {
e.preventDefault();
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2');
});
EDIT:
Here is a working example of a ajax post to codeigniter:
View
<script>
$( document ).ready(function () {
// set an on click on the button
$("#button").click(function () {
$.ajax({
type: 'POST',
url: "[page]",
data: {pays: "asd", magasin: "dsa"},
success: function(data){
alert(data);
$("#text").html(data);
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
});
});
});
</script>
Controller
<?php
// main ajax back end
class Time extends CI_Controller {
// just returns time
public function index()
{
var_dump($_POST);
echo time();
}
}
?>
Output
array(2) {
["pays"]=>
string(3) "asd"
["magasin"]=>
string(3) "dsa"
}
1473087963
Working example here
So you should check the request that you're making from AJAX, on dev console. There you should get the response with the var_dump($_POST).
to debug try to make your controller return only the $_POST data, comment the rest. and same thing on javascript side, test only the ajax post and data received.
This issue works fine when calling ajax from PHP, but I can't seem to get it working with Laravel 5.2. All I'm trying to do is send an email using AJAX when submitting a form.
This is my routes.php entry for sending the email:
Route::post('/send', 'CommsController#send');
And this is my layout.blade.php file:
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
...
$( "#send" ).button().click(function(event) {
var form = $( "#contact-form" ),
postAction = form.attr('action'),
isValid = form.valid(),
valSum = $(".validation-summary");
if ( isValid ) {
var postData = {
message_type: "contact"
,first_name: first_name.val()
,last_name: last_name.val()
,email: email.val()
,message: message.val()
};
// process the form
$.ajax({
type: "POST",
// our data object
url: postAction, // the url where we want to POST
data: postData
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success ) {
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
valSum.html( data );
} else {
// $( ".validation-summary" ).html( "Message sent." );
valSum.html( data.message );
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
valSum.html( "Server Error: " + data.statusText + " processing your request, please contact Dorothea or report a bug." );
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
} else {
return false;
}
});
And finally here is my CommsController send() function:
public function send(Request $request) {
//check if its our form
if ( Session::token() !== Request::get( 'csrf-token' ) ) {
return Response::json( array(
'message' => 'Unauthorized attempt to create setting'
));
}
$message_type = strval(Request::input('message_type'));
$first_name = strval(Request::input('first_name'));
$last_name = strval(Request::input('last_name'));
$email = strval(Request::input('email'));
$message = strval(Request::input('message'));
$to = "robinson.jeanine6#gmail.com";
// subject
$subject = "Dorothea - Contact Us";
Mail::send('email.contact', ['request' => Request::all()], function ($message) use ($request) {
$message->from($this->email, $this->email);
$message->to($user->email, $user->email)->subject($subject);
});
$response = array(
'status' => 'success',
'message' => 'Message sent.',
);
return Response::json( $response );
}
This question is related to the one I posted here, but instead of getting a MethodNotAllowedHttpException, all that been returned now from the AJAX call is the CSRF-token value.
Replace .done callback with .success to get the return data.
.success(function(data) {
if (data.status != 'success' ) {
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
}
// eventually, print out the return message
valSum.html(data.message);
})
Just wanted to let everyone that tried to help me out know that sending of emails works fine in Laravel if I change the post request to a get request.
Not too sure why this is, so if anyone can shed some light as to why this would be the case that would be great.
I'm trying to submit a HTML form to a server and it fails. I have several issues here.
I'm making a CORS request. It is a request by the client and I can't do anything about it.
( My app resides in localhost:3000/login.html & My server resides in http://localhost:3001/Login/auth )
The server in localhost:3001 accepts JSON requests and give back a JSON Responce.
(I have disabled the web-security in the browser to allow the CORS Requests)
So, I have created the HTML Form and tried to submit it with AJAX. Here you can see the code.
$(function(){
$("#loginform").submit(function(e){
e.preventDefault();
// var data = $("#loginform").serialize();
var data = {"username" : $("#username").val(),"password" : $("#password").val()};
alert(JSON.stringify(data));
$.ajax({
type: "POST",
url: "http://localhost:3001/Login/auth",
data: data,
contentType: "application/json",
crossDomain : true,
dataType: "json",
success: function(data) {
alert("success" + JSON.stringify(data));
},
error:function(data){
alert('error : '+JSON.stringify(data));
}
});
});
});
I have created the mock server in PHP (codeigniter). Here is the code for that.
public function auth(){
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$debug_export = var_export(file_get_contents('php://input'), true);
file_put_contents('new.txt',$debug_export . PHP_EOL, FILE_APPEND);
$user = 'admin';
$pass = 'admin';
$token = '1';
foreach($input_data as $key=>$value) {
if ($key === 'username') {
$this_user = $value;
}
if ($key === 'password') {
$this_password = $value;
}
}
if(isset($this_user) && isset($this_password)){
if($this_password === $pass && $this_user === $user){
echo json_encode(array('token'=>$token));
}else{
echo json_encode(array('token'=>'null'));
}
}
return 0;
}
When I submit a form, I get a response like this.
....
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/Login.php</p>
<p>Line Number: 77</p>
....
My 'new.txt' file has the log details as following.
''
'username=admin&password=admin'
I have really no idea what I'm doing wrong here. Can anyone help me out here?