Ajax goes always in error section - javascript

I have the following Ajax call on click(), The record deletes from the database table, But the ajax error section code executes, Not the success section. Also i do get an error of 405,
But the records gets delete, Following is the code.
$(".DeleteUser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "users/"+id,
type: 'DELETE',
dataType: "text",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
},
error: function() {
alert('fail');
}
});
console.log("It failed");
});
Server Side Code :
public function destroy($id) {
$user = $this->find($id);
$user->delete();
$notification = array(
'message' => 'User has been Deleted !',
'alert-type' => 'success',
);
return redirect()->route('users.index');
}

You have used 'type: "DELETE" '. Instead of that you should USE 'type:"post"' . You can also use 'get'

you are not ending your response.But redirecting to some other page.
Skip that redirection and end the request-response cycle.
public function destroy($id) {
$user = $this->find($id);
$user->delete();
$notification = array(
'message' => 'User has been Deleted !',
'alert-type' => 'success',
);
//return redirect()->route('users.index'); //skip it
header('Content-Type: application/json');
echo json_encode($notification);
}

Related

how to call delete route with ajax in laravel?

i want to call route resource with ajax, when i put type as delete i got error (exception "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException")
and given message (message "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.").function almost work beacuse after make refresh the status also change but i am the above error.
route :
Route::resource('category', ArtistCategoryController::class);
controller :
public function destroy($id)
{
$category = ArtistCategory::findOrFail($id);
$deleteResponse = $category->update([
'status'=>'d'
]);
if ($deleteResponse) {
deleteMessage();
return redirect()->back();
} else
errorMessage();
}
view :
</i>
ajax:
<script>
$(".categoryDelete").on('click', function (e) {
e.preventDefault();
let id = $(this).data('id')
// console.log(id)
$.ajax({
url: '/artist/category/'+id,
type: 'DELETE',
data:{"id": id, "_token": "{{ csrf_token() }}"},
success: function (data)
{
alert(data)
},
error: function (e){
alert(e)
}
});
})
</script>
solved it with some changes in destroy method
because i have used return return redirect()->back();it gives error and this is unacceptable
updated
public function destroy($id): \Illuminate\Http\JsonResponse
{
$category = ArtistCategory::findOrFail($id);
$deleteResponse = $category->update([
'status'=>'d'
]);
if ($deleteResponse) {
return response()->json([
'data' => [
'id' => $id
],
'status' => 'success',
]);
} else
{
return response()->json([
'data' => [
'id' => $id
],
'status' => 'error',
'message' => __("Couldn't Delete. Please Try Again!")
], 500);
}
}
You need to set the csrf token in the header. Have a look at the docs in the bottom of the page: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token
Create a meta tag with the token like this:
<meta name="csrf-token" content="{{ csrf_token() }}">
And grap it like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Select2 POST AJAX Request 500 Error Laravel

I'm trying to use select2 retrieving large data in my dropdown using the following article.
Getting 500 Internal Server Error in my console log.
I have store token in HTML meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And sending a token as a parameter in my POST request.
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
$( "#test" ).select2({
ajax: {
url: "path/to/url",
type: "POST",
dataType: 'JSON',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
<select class="test" id="test" style="width:100%;"></select>
I have checked routes using php artisan route:list and clear cache using php artisan config:cache. But still getting the same error link. and link.
Is there anything I'm missing? I would be grateful if you can help me out to debug/inspect my Request and Response.
Tried
error: function(err){
console.log(err)
}
Server-Side \ Controller
public function getdata(Request $request){
$search = $request->search;
if($search == ''){
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->limit(5)->get();
}else{
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
$response = array();
foreach($data as $i){
$response[] = array(
"id"=>$i->id,
"text"=>$i->name
);
}
return response()->json($response);
}
Happy Coding.

How to use ajax for request the WHMCS hooks function and get my required return data?

I read the WHMCS demo code for developing a provisioning module:
the frontend code, overview.tpl.
the backend code, provisioningmodule.php.
but my code follow by the upper I want to use ajax for request, so the whole page will not re-render.
My frontend ajax code:
jQuery.ajax({
url: url,
type: "POST",
data: {
...
qn_action: "bmc"
},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus){
console.log('ldl:',data) // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
jQuery('.powercontrol').removeClass('disabled');
jQuery(i_id).css('display', 'none');
jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
},
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})
in my backend PHP code:
function qidicatedserver_ClientArea(array $params)
{
// Determine the requested action and set service call parameters based on
// the action.
$qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';
$tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';
$bmc_action = "";
$server_name = "";
$templateFile = 'templates/overview.tpl';
$bmc_result = "";
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
"status"=>200,
"data"=>"my test return data"
)
);
return $resp;
}
try {
// Call the service's function based on the request action, using the
// values provided by WHMCS in `$params`.
return array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
'data' => array(
"status"=>"200",
"data" => array(
"bmc_result" => null
)
),
),
);
} catch (Exception $e) {
//echo $e;
// Record the error in WHMCS's module log.
logModuleCall(
'qidedicatedserver',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
// In an error condition, display an error page.
return array(
'tabOverviewReplacementTemplate' => 'templates/error.tpl',
'templateVariables' => array(
'usefulErrorHelper' => $e->getMessage(),
),
);
}
}
when the ajax request executed, there will get error, execute the below code:
console.log('error: '+jqXHR.responseText); // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg); // the console log: `Error msg: Error: Parsing JSON Request failed.`
So, there must be issue in there, my problem is how to use ajax for HTTP request in WHMCS custom provisioning module, but I try get failed like upper. (I tried use form request PHP, there can get correct data, but there will re-fresh the whole page, its not my desired, I don't what the page to be refresh)
Who can tell me how to use ajax for request WHMCS hook function and return correct data as my wish?
You can find more introduction of WHMCS provisioningmodulethere.
EDIT-01
I tried change the return PHP code like this:
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => json_encode(array(
"status"=>200,
"data"=>"dasdas"
))
);
return $resp;
}
but still this error.
Put your Ajax/PHP code in separated file, not in _ClientArea method, suppose your module called 'mail_service', then create a file in:
\modules\servers\mail_service\for_json.php
for_json.php
<?php
#define("ADMINAREA", true);
define("CLIENTAREA", true);
#define("SHOPPING_CART", true);
require_once(__DIR__ . '/../../../init.php');
require_once(ROOTDIR . '/includes/dbfunctions.php');
#require(ROOTDIR . "/includes/orderfunctions.php");
#require(ROOTDIR . "/includes/domainfunctions.php");
#require(ROOTDIR . "/includes/configoptionsfunctions.php");
#require(ROOTDIR . "/includes/customfieldfunctions.php");
#require(ROOTDIR . "/includes/clientfunctions.php");
#require(ROOTDIR . "/includes/invoicefunctions.php");
#require(ROOTDIR . "/includes/processinvoices.php");
#require(ROOTDIR . "/includes/gatewayfunctions.php");
#require(ROOTDIR . "/includes/modulefunctions.php");
#require(ROOTDIR . "/includes/ccfunctions.php");
#require(ROOTDIR . "/includes/cartfunctions.php");
#include_once(ROOTDIR . '/includes/clientareafunctions.php');
#use WHMCS\ClientArea;
#use WHMCS\Database\Capsule;
#use WHMCS\Smarty ;
file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
{
// do your job
//header('Content-type: application/json; charset=utf-8');
header("Content-Type: application/json", true);
header('HTTP/1.0 200 OK');
echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
}
?>
and use the follwing JS code:
jQuery.ajax({
url: "/modules/servers/mail_service/for_json.php",
type: 'POST',
data: {qn_action: 'bmc'},
cache: false,
dataType: 'json',
success: function (data, textStatus){console.log('ldl:',data)},
error: function(jqXHR, e){
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})

Jquery Ajax not working on server but working on localhost

I have the following jquery code that posts data to a php file and works fine on localhost. But when this code is now on the server the script returns an error instead of data.
$.ajax({
type: 'POST',
url: 'scripts/info.php',
data: {
accountNumber: accountNumber,
agentName: name
},
success: function( data ) {
alert(data)
},
error: function(xhr, status, error) {
// check status && error
alert(status)
}
});
This is the code in the php file that handles the post request:
$args0 = array(
'accountNumber' => $_POST['accountNumber'],
'dateReceived' => date("Y-m-d"),
'firstNames' => $_POST['agentName'] '
'regNumber' => $_POST['accountNumber'],
'surname' => $_POST['agentName']
);
try {
$client = new SoapClient(WSDL_URL, array(
'trace' => 1,
'exceptions' => true,
'connection_timeout' => 300));
$params = array(
'arg0' => $args0,
);
$client->__setLocation(WSDL_LOCATION);
$response = $client->upload($params);
$response = $client->__getLastResponse();
echo $response;
Please help
$.ajax({
type:"post",
url:"/pay/index.php?submit_order=yes",
dataType:'json',
data:{
'rmb': $('#rmb').val(),
'couponid': $('#cid').val(),
'title' :$('#title').text(),
'user' :$('#user').text(),
'phone' :$('#phone').text(),
'code' :$('#code').text(),
'size' :$('#size').text(),
'isinvoice':$('[name=isinvoice]').val()
},
beforeSend:function(){
beforeSend.attr('disabled',true);
beforeSend.html('submitting').removeAttr('href');
},
success:function(data){
if(data.errorcode==1){
$('.pay-fail').show().text(data.message);
}else{
if(data.url){
location.href=data.url;
}else{
alert('post ok!');
}
}
},
error: function(){
alert('submit error,then try again');
}
})
This is my jQuery ajax for pay. It works on localhost and on server.

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

Categories

Resources