I'm trying to create AJAX form with Symfony, but my form return empty object. When I send manualy writed text or array everything works fine. Where is the bug? I do something wrong with form or javascript code is the problem?
/**
* Renders the "new" form
*
* #Route("/", name="demo_new")
* #Method("GET")
*/
public function newAction(Request $request) {
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity);
return $this->render('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
)
);
}
/**
*
* #Route("/", name="demo_create")
* #Method("POST")
*
*/
public function createAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity, array(
'action' => $this->generateUrl('demo_create'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return new JsonResponse(
[
'message' => 'Success!',
'data' => $data
], 200);
}
$response = new JsonResponse(
array(
'message' => 'Error',
'form' => $this->renderView('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
))), 400);
return $response;
}
}
and Javascript code:
function initAjaxForm()
{
$('body').on('submit', '.ajaxForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
console.log(data.data);
console.log(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
}
Had same issue today with version 2.8 gonna leave this here in case it end up healping someone else i've added this to my form builder
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}
Related
When I send a photo I get a 422 error from axios with message:
The preview must be a file of type: jpg, jpeg, png, pdf.
But I sent the photo in the correct format. I don't really understand where the error is.
My vue component methods:
data() {
return {
name: '',
description: '',
preview: '',
}
},
methods: {
create() {
this.projectStore.createProject(this.name, this.description, this.preview)
},
onFileChange(e) {
let img = e.target.files[0]
let reader = new FileReader()
reader.readAsDataURL(img)
this.preview = img
},
},
My store(Pinia) method:
async createProject(name, description, preview) {
let formData = new FormData()
formData.append('preview', preview)
console.log(formData);
axios.get('/sacntum/csrf-cookie').then(response => {
axios.post('api/create', {
name: name,
description: description,
preview: formData,
}, {
headers: {
'content-type': 'multipart/form-data',
}
})
.then(response => {
if (response.data.success) {
console.log(response)
} else {
console.log('response')
}
})
.catch(function (error) {
console.error(error)
})
})
},
My Controller in Laravel:
public function createProject(Request $request)
{
if (Auth::check()) {
$attr = $request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string|max:1000',
'preview' => 'required|mimes:jpg,jpeg,png,pdf|max:2048',
]);
$generated_new_name = time() . '.' . $attr['preview']->getClientOriginalExtension();
$request->preview->move(public_path('preview_images'), $generated_new_name);
$project = Project::create([
'name' => $attr['name'],
'description' => $attr['description'],
'preview' => $generated_new_name,
]);
$success = true;
$message = 'Project created successfully';
} else {
$success = false;
$message = 'You are not logged yet';
}
$response = [
'success' => $success,
'message' => $message,
];
return response()->json($response);
}
I tried to make formdata in vue component and then pass to store but it didn't help
Use the below code in the controller
$photo = $request->file('image');
$imagename = time() . '.' . $photo->getClientOriginalExtension();
// Add Normal Image...
$destinationPath = public_path('uploads');
$photo->move($destinationPath, $imagename);
echo '<pre>';
print_r("Upload Successfully. Store File : laravel_code/public/uploads & laravel_code/public/uploads/thumbnail_images");
I'm new to using PHP. I'm implementing an email subscription form that is wrapped in a google captcha function. I'm using ajax to call the server-side code. The issue I'm having is the success() method inside the ajax is not being invoked when the function executes correctly.
Some details: the 3rd party email subscription returns a json object with a single key-value pair, {message: "you've been added"} or {message:"error,try again"}
The function has run 'successfully if we hit the else clasue in the php file. when this happens, it runs the error() callback for some reason? even though i have a status 200
I suspect im not returning valid json or something? Thanks in advance!
Here is my JS
$(".subscribe-form").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var formAction = form.attr("action");
var formMethod = form.attr("method");
var formResponse = $("#form-response");
grecaptcha.ready(function () {
grecaptcha
.execute("6Lcgdq4UAAAAAFjthnpc_WQ4leumC1UmlyLk0OwR", {
action: "submit",
})
.then(function (token) {
var recaptchaResponse = document.getElementById("recaptchaResponse");
recaptchaResponse.value = token;
$.ajax({
url: "/wp-content/themes/hello-elementor/submit.php",
type: "POST",
data: formData,
dataType: "json",
success: function (data) {
console.log(data);
if (data.error) {
formResponse.html(data.error);
} else {
formResponse.html(data.success);
}
},
error: function (data) {
console.log(data);
formResponse.html("Error, please try again");
},
});
});
});
});
Here is my sumbit.php - I've removed the secret for obvious reasons.
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$ttrurl = "https://3rdpartysubsciptionservice/addEmailDetails.aspx?first_name=$fname&last_name=$lname&email=$email";
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "secret_code",
'response' => $_POST['recaptcha_response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$res = json_decode($response, true);
// Take action based on the score returned
if ($res['success'] == false && $res['score'] <= 0.5) {
// Score less than 0.5 indicates suspicious activity. Return an error
$error = "Something went wrong. Please try again later";
$output = array("error" => $error, "success" => "");
http_response_code(400);
echo json_encode($output);
} else {
// This is a human. Insert the message into database OR send a mail
$curl = curl_init();
curl_setopt_array($curl, array(CURLOPT_URL => $ttrurl));
$ttrres = curl_exec($curl);
curl_close($curl);
$message = json_decode($ttrres, true);
$output = array("error" => "", "success" => json_encode($message));
http_response_code(200);
echo json_encode($output);
}
?>
please note that you set dataType: "json" in your ajax and your response does not seem to be json.
use this code on top of your php code:
header('Content-Type: application/json; charset=utf-8');
I learn MVC and make some AJAX interaction. So I've routes file with
'cart/addProductAjax' => 'cart/addProductAjax',
CartController with actionAddProductAjax:
<?php
class CartController
{
public function actionIndex() {
}
public function actionAdd($productId) {
Cart::addProduct($productId);
$referer = '/';
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
header("Location: $referer");
}
public function actionAddProductAjax() {
$productId = $_POST['productId'];
print_r($_POST);
exit;
Cart::addProduct($productId);
$itemsAmount = Cart::countItems();
exit(json_encode($itemsAmount));
}
}
And JS piece of code that send request and receive response from the server:
document.body.addEventListener('click', event => {
if(event.target.classList.contains('add-to-cart')) {
event.preventDefault();
let productId = event.target.dataset.id;
let response = fetch("/cart/addProductAjax/", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(productId),
})
.then(response => response.json())
.then(response => console.log(response));
}
});
And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?
I am using laravel 4 and I am trying to display login validation by using ajax. I have the following javascript validation:
jQuery('#form-signin').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('#form-signin').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".validation-error-inline").hide();
}
})
.done(function(data)
{
$('#validation-login').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
and in my userController:
public function doLogin() {
Input::flash();
$data = [
"errors" => null
];
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => 'Invalid username or password',
);
return Response::json($response_values);
}else
{
echo 'error';
}
}
}
The problem is that it always displays "error" message, which means that jaax request isn't performed. What is wrong?
In your doLogin() function try
return Response::json(array(
'validation_failed' => 1,
'errors' => 'Unknow error'
))
instead of
echo "error"
i use ajax to create a session and to redirect the page when the user clicks on a button like this .. im using this in the facebook api(using the api to create a session with the user.id)
FB.login(function(response) {
if (response.session) {
FB.api('/me', function(user) {
if (user!=null) {
var request = new XMLHttpRequest();
if(document.getElementById("ans2").value==""){
document.getElementById("belowbutton2").innerHTML ="Don't leave it blank!!";
}
else{
var request2 = new XMLHttpRequest();
request.onreadystatechange=function(){
if(request.readyState==4 && request.status==200){
document.getElementById("debugger").innerHTML = request.responseText;
window.location = "weekques/weekques.php";
}
}
var uid = user.id;
alert(uid);
var jqXHR = ($.ajax)({url:"sessions.php?uid="+uid,
async:false,
cache: false,
timeout: 30000,
error:function(){
window.location = "http://www.xyz.com";
},
success:function(){
request.open("GET", "weekques/answer.php?ans="+document.getElementById("ans2").value, true); //+"&qid="+qidjs
request.send();
}
});
}
}
});
}
});
but the problem is that the window is redirecting before the session is created ..
heres the
sessions.php file
<?php
session_start();
require_once("connection.php");
$user=mysql_query("SELECT * from `thebirbals`.`FBusers` where uid='$uid';");
$row_count=mysql_num_rows($result);
$_SESSION['uid']=$_GET["uid"];
$uid = $_SESSION['uid'] ;
if($row_count==1){
$_SESSION['name'] = $check["name"];
$_SESSION['profile_link'] = $check["profile_link"];
$_SESSION['dp'] = $check["dp"];
}
else{
require_once('facebook/src/facebook.php');
$facebook = new Facebook(array(
'appId' => '1550598824560526',
'secret' => '4cf28242b5abfa26be8fd3e2074e5724',
'cookie' => false
));
$fql = "SELECT first_name,profile_url,pic_small from user where uid=$uid";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
foreach($response as $val)
{
$_SESSION['name']=$val["first_name"];
$_SESSION['dp']=$val["pic_small"];
$_SESSION['profile_link']= $val["profile_url"];
$name = $val["first_name"];
$profile_link = $val["profile_url"];
$dp = $val["pic_small"];
echo "done";
}
$insert=mysql_query("INSERT INTO `thebirbals`.`FBusers` ( `uid`, `name`, `profile_link`, `dp`) VALUES ('$uid', '$name', '$profile_link', '$dp');");
}
?>
i want to redirect after the sessions.php is finished running this does not happen
ty in advance for any help .. :)
I took a stab. Not sure if this will fix your issue entirely, but take it as a starting point:
FB.login(function (response) {
if (response.session) {
FB.api('/me', function (user) {
if (user != null) {
if (document.getElementById("ans2").value == "") {
document.getElementById("belowbutton2").innerHTML = "Don't leave it blank!!";
}
else {
var uid = user.id;
alert(uid);
$.ajax({ url: "sessions.php?uid=" + uid,
async: false,
cache: false,
timeout: 30000,
error: function () {
window.location = "http://www.xyz.com";
},
success: function () {
$.get("weekques/answer.php", $.param({ "ans": document.getElementById("ans2").value }), function (data) {
alert("Answer received");
document.getElementById("debugger").innerHTML = data;
window.location = "weekques/weekques.php";
});
}
});
}
}
});
}
});