I have an AJAX call in my view to an action in my controller. However, I always get an Error 400. Below is the code for my AJAX call:
$.ajax({
cache: false,
url: '/dummy/index.php/module/controller/checkCross',
dataType: 'json',
type: 'POST',
data : {"male":parents[0],"female":parents[1]},
success: function(result){
alert(result);
}
});
Below is the code in the controller:
public function actionCheckCross(){
if(Yii::app()->request->isPostRequest) { // check if POST
$flag = CrossingMatrix::model()->checkParentsIfCrossed($_POST['male'],$_POST['female']);
if($flag){
return true;
}
else{
return false;
}
} else { // direct URL request will be GET, so show error
throw new CHttpException(400, Yii::t('app', 'Direct access is not allowed.'));
}
}
Any ideas?
You are expecting json data, but you send empty page to browser. You should encode result like that:
echo CJavascript::jsonEncode((bool)$flag);
Yii::app()->end();
In your code you returned value. Notice that your yii exception message is Direct access is not allowed but your error is Your request is invalid.
Related
I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault(); // Disable normal behaviour of the element (Form)
var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}
console.log(formData); // Log to the console the Input data
$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
Route:
Route::post ('user/save', 'CustomerController#createNewCustomer');
Controller:
public function createNewCustomer (Request $request)
{
$inputArray = $request->all();
print_r ($inputArray['form']);
// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response
return response ()->json ($response);
}
In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}
I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?
The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.
You can access like this
$request['name of field'];
i think you need to receive the data in the controller as json:
$request->json('field_of_interest')
The problem is your formData variable. Instead of:
var formData = {
form: $("#newCustomerForm").serialize()
}
it should be
var formData=$("#newCustomerForm").serialize();
I have a simple Javascript funcion:
function checkParams()
{
$.ajax(
{
url: 'login.php',
type: "GET",
contentType: false,
cache: false,
processData: false,
async: true,
data:
{
user: $("#user").val(),
pass: $("#pass").val()
},
success: function(data)
{
$("#mydiv").load("loader.php");
},
error: function()
{
$("#mydiv").load("index.php");
}
});
}
And A simple PHP function which checks for the right user & pass string and I should return an error condition if something fails..
I found examples where it's suggested to do something like:
function foo()
{
/* code ... */
/*error condition */
echo "error";
}
But honestly, it's not working..
How can I tell to ajax, from PHP, that I want ro return an 'error condition' ?
The jQuery.ajax() error handler only fires when the HTTP status result indicates an error; that is, the page returns a 4xx or 5xx status code.
You can do one of the two following options:
1) Set the status code with header('HTTP/1.0 400 Bad Request') (or any other relevant HTTP status code) before you echo "error".
2) Rather than using an error status, have both your success and failure conditions emit an array, converted to JSON withjson_encode(), that is then decoded in your javascript and processed into a success or failure as appropriate in your success function.
In this bit of code change to RETURN SOMETHING
success: function(data)
{
return true;
},
error: function()
{
return false;
}
basically
$result = your ajax return;
if ($result)
{
header('Content-Type: application/json');
}
else
{
header('HTTP/1.1 500 Internal Server Yourserver');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 'whatever you want to call it')));
}
I have a validation that, when successful creates a session variable:
if( password_verify($password, $artist_password) ) { // if this is true
// create $_SESSION artist name
$_SESSION['artist_name'] = $artist_name;
return $artist_name;
} else {
echo "Incorrect Password";
}
This validation is initiated by an Ajax request.
If there are errors with the validation, I echo a message. This echoed message is received by the Ajax success method via the data argument.
$.ajax({
url: '../includes/login_validation.php',
type: 'post',
data: inputs,
success: function(data){
$("span#error_msg").html(data);
},
// returns 'Incorrect Password'
My problem is in defining the return response from the PHP file.
For example, when there's an error, the PHP script echoes a message and in turn this response is received and processed through the Ajax success method and placed into a html placeholder.
However, if the SESSION variable is assigned I want to return that data and include it in a redirect.
My question is, how can I discern between an echoed response as the return value and a returned value containing other data (e.g $_SESSION['artist_name']).
And if successful, how can I include it in my redirect so that the redirected page will have access to the session variable.
window.location.href="artistWorkshop.php"; // plus session variable
How about doing a little JSON formatting:
if( password_verify($password, $artist_password) ) { // if this is true
// create $_SESSION artist name
$_SESSION['artist_name'] = $artist_name;
echo '{"status":"success","result":"'.$artist_name.'"}';
} else {
echo '{"status":"error","result":"Incorrect Password"}';
}
Next, handle the output in JS:
$.ajax({
url: '../includes/login_validation.php',
type: 'post',
data: inputs,
success: function(data){
var obj = JSON.parse(data);
if (obj.status == 'success') {
// redirect
window.location.href="artistWorkshop.php?artist="+obj.result;
}
if (obj.status == 'error') {
// throe error
$("span#error_msg").html(obj.result);
}
},
});
You could handle multiple formats this way. Problem was is the JS was interpreting any output as a success, because the AJAX call itself was successful. Now, you have a message to determine the actual result of the request. In your code, to determine an actual failure of the ajax request, your would need to include a error node:
$.ajax({
url: '../includes/login_validation.php',
type: 'post',
data: inputs,
success: function(data){
$("span#error_msg").html(data);
},
error: function(data){
// handle the error
},
If you go that route, check this out:
http://api.jquery.com/jquery.ajax/
My success/error handling is not working as expected. In this example my php runs as intended, however, the intent of the processing failed. Let's say I was looking up a username in the database... if I found the username I would return $ajax_result['success'] = 'success';, but if I did not find the username I would return nothing. The success call works fine, but the error call is not firing.
The error in firebug I am getting is TypeError: response is null and therefore the error alert I have set does not fire.
What is the best way to solve this without actually returning $ajax_result['success'] = 'whatever';
example return from php would be something like this when processing went as expected:
$ajax_result['success'] = 'success'; // add success info
echo json_encode($ajax_result); // return result array to ajax
for 'errors' I am simply returning :
echo json_encode($ajax_result); // which is null in this case
the ajax:
var showInfo = function() {
$('#show-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user_show.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
alert('success');
}
else
{
alert('error');
}
});
});
}
You can not json_encode a null value, easiest and cleanest way to make this work would probably be to make success a bool and set it to either true or false depending on if it succeeded or not (This is ususaly what most user expects a 'success' or 'result' parameter in response to be, not a string).
//PHP:
header('Content-Type: application/json'); // To let the client know that its json-data.
$ajax_result['success'] = $wasSuccessfull; // true or false
die(json_encode($ajax_result)); // Exit the script with the json response.
//JavaScript:
if (response.success) {
alert('success');
} else {
alert('error');
}
try this one:
if (!response.success) {
alert('error');
}
else
{
alert('success');
}
I'm using jQuery and AJAX to validate my form when someone creates a new user on my website. I'm programming in OOP PHP, together with the jQuery and AJAX.
I'm using this code:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function() {
$('.sideBarNewUserWrap').fadeOut();
}
});
return false;
But how do I return an error message, if the e-mail already exists?
Hope it's info enough, else I'll just add some more.
Thanks in forward :)
* UPDATE *
This is my PHP checking if email exists:
$email_count = mysql_num_rows($check_email);
if($email_count){
return false;
}
* UPDATE *
success: function(data){
if(data.error){
$('.sideBarNewUserWrap').fadeOut();
} else {
$('.sideBarNewUserError-email').fadeIn();
}
Now this looks pretty much as a failure because.
if(data.error) then it's okay?
Shouldn't it be something like:
if(date.error){
//Error message
}
And not the other way around?
Well, If I try to enter an email which already exists, it tells me as it should, but why does this work? In my eyes I'm doing something wrong here?
php:
$result = array('error' => true); // or $result = array('error' => false);
echo json_encode($result);
js:
success: function(response) {
if (response.error) {
// ...
}
}
You can get the response in the function:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function(response) {
if (response == "ok")
{
$('.sideBarNewUserWrap').fadeOut();
}
else
{
// error happend
}
}
});
return false;
You can return string, int in PHP or even XML, JSON, whatever you want to validate on client side
You can return data by using an echo in your handler.php file.
To receive this in jQuery just place a parameter in the success function of the Ajax function.
success: function(returnedValue)
{
// Here you check if returned value e.g. "returnedValue == 1"
}
basically in the handler.php you should verify whether email already exists or not and then send to the client (at least) two different responses (eg. 0: email exists, 1:ok).
In the success callback you can read the response data so you can tell the user the operation status