When I use Ajax for sending a post request I get an internal server error 500 and couldn't find a solution.
Here is my view that contains the Ajax:
<html>
<head>
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#btn').click(function(){
$.ajax({
url:"localhost:8000/test",
type:"POST",
dataType:'json',
success:function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="username" id="txt">
<input type="button" name="btn" id="btn" value="send">
</body>
</html>
and here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postTest($request request){
return response()->json(['name'=> 'khaled','age'=>45]);
}
}
and my routes:
Route::get('/upload','UploadsController#getUpload');
Route::post('/test','UploadsController#postTest');
When I click the button, it should send and asynchronous post request, but an error "internal server error 500" returns instead.
Wrong parameter definition for postTest fuction
public function postTest(Request $request){
return response()->json(['name'=> 'khaled','age'=>45]);
}
the bug can occur because it is missing csrf-token
first, add the meta : <meta name="csrf-token" content="{{ csrf_token() }}">
Then, configure the headers of the ajax requests :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')
}
});
I hope it helped you
Related
is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>
I would like check the image whether existing on server file system and the file list was store into database. I want to make a ajax call to doing validation then return the result to screen with append effect. Here is my code, but don't work :( Please help me.
UPDATE: Code is workable, but it's not my expectation, because three thousand record with caused timeout and No append effect. thanks
Controller
public function getImageList()
{
$this->load->model('image_model');
$data['list'] = $this->image_model->get_image();
foreach ($data['list'] as $key){
$result[] = $this->imageValidation($key->filename);
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($result));
}
private function imageValidation($imgfile)
{
if(!file_exists(LOCAL_IMG_TEMP.$imgfile))
{
return "<pre>". $imgfile." Not Find"."</pre>";
}
}
View
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title></title>
</head>
<body>
<script>
function makeAjaxCall(){
$.ajax({
type: "POST",
url: "http://127.0.0.1:8888/index.php/ajax/getImageList",
cache: false,
dataType : "json",
success: function(data){
$("p").append(data);
}
});
}
</script>
</script>
<input type='button' id='PostBtn' value='Check Image' onclick='javascript:makeAjaxCall();' />
<p></p>
</body>
</html>
try to use file_exists()
check it
I have been struggling with this for a couple days and have yet to find any real solutions online yet. I have a form that allows users to enter their email, then after they enter it fades out and is replaced by another form. I am using ajax to submit data from a form to a symfony2 controller, which stories it in the database and sends a response. However, the response ends up just sending me to a blank page with the response data displayed, instead keeping me on the same page and just fading the boxes as needed. I think my issue is with how I have the controller actions set up and the routing files.
EDIT
Well now the issue is that when I click on the submit button nothing happens. Nothing is sent to the controller, so nothing is being stored and no response is being given. What I changed was based on the answer by #PaulPro, appending the
<script> $('#emailForm').submit(submitForm); </script>
to the end of the html page. Thanks in advance for any help and insight!
The controller has 2 relevant actions, the one that renders the TWIG Template with the form, and the one that handles the ajax form submission and returns the response.
public function emailAction()
{
return $this->render('Bundle:email.html.twig');
}
public function submitEmailAction()
{
$em = $this->getDoctrine()-> getEntityManager();
$email = new Email();
$request = $this->getRequest();
$emailVar = $request->request->get('emailSignup');
$email -> setEmail($emailVar);
$em->persist($email);
$em->flush();
$return=array("responseCode"=>200);
$return = json_encode($return);
return new Response($return, 200, array('Content-Type'=>'application/json'));
}
This is the routing for those actions, most likely the culprit of it all:
Bundle_email:
pattern: /email
defaults: { _controller: Bundle:email }
requirements:
_method: GET
Bundle_submitEmail:
pattern: /submitEmail
defaults: { _controller: Bundle:submitEmail }
requirements:
_method: POST
And then here is the email.html.twig template and ajax script:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="{{asset('css/styles.css')}}" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm(){
var emailForm = $(this);
var path = "{{path('Bundle_submitEmail')}}"
$.ajax ( {
type: 'POST',
url: $("#emailForm").attr("action"),
emailSignup: $("#emailId").val(),
success: function(data){
if(data.responseCode==200 ){
$('.email-signup-form').fadeOut();
$('.share-form').delay(500).fadeIn();
}
}
});
return false;
}</script>
</head>
<body>
<form id="emailForm" action="{{path('Bundle_submitEmail')}}" method="POST" class="email-signup-form">
<input type="email" placeholder="e-mail address" name="emailSignup" id="emailId" required="true"/>
<input type="submit" value="Go">
</form>
<form class="share-form">
</form>
<script> $('#emailForm').submit(submitForm); </script>
</body>
</html>
You don't ever call submitForm (the function that tells the browser to use AJAX rather than a full page load). Just add a script at the end of your body that looks like:
<script>
$('#emailForm').submit(submitForm);
</script>
I am trying to build a mobile app with JQuery Mobile and PhoneGap. This app will hit a backend I'm working on with ASP.NET MVC 3. Right now, I'm just trying to get a basic GET/POST to work. I've created the following test page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="resources/css/themes/default/core.css" />
<link rel="stylesheet" href="resources/css/themes/default/app.css" />
<script src="resources/scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="resources/scripts/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
}
</script>
</head>
<body onload="initialize();">
<div id="testPage" data-role="page">
<div data-role="header" data-position="fixed">
<h1>TEST</h1>
</div>
<div data-role="content">
<input id="twitterButton" type="button" value="Test GET via Twitter" onclick="twitterButton_Click();" />
<input id="getButton" type="button" value="Test GET via MVC 3" onclick="getButton_Click();" />
<input id="postButton" type="button" value="Test POST via MVC 3" onclick="postButton_Click();" />
<div id="status"></div>
</div>
<div data-role="footer" class="ui-bar" data-position="fixed">
</div>
<script type="text/javascript">
function twitterButton_Click() {
$("#status").html("Testing Twitter...");
var vm = { q:"1" };
$.ajax({
url: "http://search.twitter.com/search.json?q=weekend&rpp=5&include_entities=true&result_type=mixed",
type: "GET",
dataType: "jsonp",
contentType: "application/json",
success: twitter_Succeeded,
error: twitter_Failed
});
}
function twitter_Succeeded(result) {
$("#status").html("Twitter GET Succeeded!");
}
function twitter_Failed(p1, p2, p3) {
$("#status").html("Twitter GET Failed :(");
}
function getButton_Click() {
$("#status").html("Testing Get...");
var vm = { q:"1" };
$.ajax({
url: "https://www.mydomain.com/myService/testGet",
type: "GET",
data: vm,
contentType: "application/json",
success: get_Succeeded,
error: get_Failed
});
}
function get_Succeeded(result) {
$("#status").html("MVC 3 GET Succeeded!");
}
function get_Failed(p1, p2, p3) {
$("#status").html("MVC 3 GET Failed :(");
}
function postButton_Click() {
$("#status").html("Testing POST...");
var vm = { data:"some test data" };
$.ajax({
url: "https://www.mydomain.com/myService/testPost",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json",
success: post_Succeeded,
error: post_Failed
});
}
function post_Succeeded(result) {
$("#status").html("MVC 3 POST Succeeded!");
}
function post_Failed(p1, p2, p3) {
$("#status").html("MVC 3 POST Failed :(");
}
</script>
</div>
</body>
</html>
When I run this page from within Visual Studio, I change the AJAX url calls to be relative calls. They work perfectly. However, because my goal is run this app from within PhoneGap, I know that this page will actually run as a local file (http://jquerymobile.com/demos/1.1.0/docs/pages/phonegap.html). Because of this, I've used the code above and created test.html on my local machine.
When I try to run this code, the Twitter test works. Oddly, all three actions work in Internet Explorer. However, when I use Chrome or FireFox, the tests to my server do NOT work. In Chrome, I notice the following in the console:
XMLHttpRequest cannot load https://www.mydomain.com/myService/testGet?q=1. Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load https://www.mydomain.com/myService/testPost. Origin null is not allowed by Access-Control-Allow-Origin.
I reviewed this: Ways to circumvent the same-origin policy. However, none of them seem to work. I feel like there is some server side configuration I'm missing. Currently, my TestGet and TestPost actions look like the following:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult TestGet(string q)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(new { original = q, response=DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestPost(string data)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(new { status=1, response = DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}
I feel like I'm SO close to getting this work. What am I missing? Anyhelp is sincerely appreciated.
Try it from an actual device or simulator and it will work. From the FAQ:
The cross-domain security policy does not affect PhoneGap
applications. Since the html files are called by webkit with the
file:// protocol, the security policy does not apply. (in Android,you
may grant android.permission.INTERNET to your app by edit the
AndroidManifest.xml)
It will always work with Twitter as it uses JSONP to respond to queries. You have to start Chrome or Firefox the proper way to tell it to allow CORS. For Chrome it is:
chrome --disable-web-security
The following code is a very simple ajax call to server that alerts back on success and complete events.
From a reason I cannot understand on my development machine it works fine and alerts on success and complete but on server it never alerts on success. WHY ???
**
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function dummy() {
$.ajax({
url: 'services/chatEngine.asmx/dummy',
async: true,
type: "POST",
complete: function () { alert('Done'); },
success: function (a, b, c) {
alert('Success');
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<div id="userList">Users:<br /></div>
<input id="Button3" type="button" value="dummy" onclick="dummy()" />
</div>
</form>
</body>
</html>
**
The server side dummy function returns nothing, code follows -
<WebMethod(True)>
Public Function dummy() As String
Return ""
End Function
You need to find out where the failure is.
1) Is the client making the request? Use your browsers developer tool request monitor or something like Charles to look at the request data. make sure the URL is correct.
2) Is the server getting the request? Use server logs or attach a debugger to verify the request is received.