I have a field (called name), Every time i write in this field, an ajax script (live search sends data from twig to the controller without reloading) checks if the data already exist or not showing a message. My problem is that i could't set a name for this field, i tried this but it does not work
{{ form_label(form.name) }}
{{ form_widget(form.name,{'id':'name','attr':{'name':'name'}}) }}
{{ form_errors(form.name) }}
and here my function in the controller which i'm sure it works properly,
public function searchBackTeamAction(Request $request)
{
if($request->isXmlHttpRequest())
{
$serializer = new Serializer(array(new ObjectNormalizer()));
$em = $this->getDoctrine()->getManager();
$teams= $em->getRepository('TeamBundle:Team')->findOneBy(['name'=>$request->get('name') ]);
$data = $serializer->normalize($teams);
return new JsonResponse($data);
}
}
and here is my script i'm also sure that it works properly
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: $("#name").serialize(),
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
</script>
Could you please help me ?
Use following javascript
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: {"name": $("#name").val()},
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
Related
I am working with Laravel Datatable and I have stuck in one point. Below code for delete the entry in the TagManagement model. But it isn't delete the entry and worse thing is it didn't show any error. Can anybody find the error in below code?
view
$(document.body).on("click",".remove-tag", function () {
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
Controller
public function destroy($id)
{
$tagManagement = TagManagement::find($id);
$deleted = $tagManagement->delete();
if ($deleted) {
return "SUCCESS";
} else {
return "FAIL";
}
}
public function loadTags()
{
$Tags = TagManagement::all();
return DataTables::of($Tags)
->addColumn('action', function ($tag) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $tag->id . '" class="btn btn-default remove-tag remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
}
**Route**
Route::get('/delete-tag', 'AdminPanel\TagController#destroy');
Your route and controller method don't seem to correspond. First of all, it is better to use the "delete" HTTP request method for delete actions, but this is not what is causing your problem.
You defined your route as /delete-tag but in your controller you expect an $id as a parameter to your destroy method. In order for that to work you would need to have the route like this /delete-tag/{id} and construct the URL for your ajax call correspondingly on the frontend. I'm surprised you don't get the Missing argument 1 for App\Providers\RouteServiceProvider::{closure}() exception for malforming your request this way.
Laravel documentation explains very well how to define routes with parameters.
It would be helpful if you included Laravel version in your question.
Here is how it should work:
Route definition
Route::delete('/delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('delete-tag');
JS function
function deleteTag(id){
let route = '{!! route('delete-tag', ['id' => '%id%']) !!}';
$.ajax({
type: 'post',
url: route.replace('%id%', id);,
data: {_method: 'delete'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
It is not your Datatable problem, you missed some code, you did not define route & jQuery function properly, your destroy($id) function received a parameter but you do not receive any parameter in your route & you not send _token in your ajax action you need to send _token
Check My code I am edited your code.
//Change your Route
Route::get('delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('deleteTag');
//Change your function
function deleteTag(id){
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('deleteTag', '') }}/'+id,
data: {_token: '{{csrf_token()}}'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to use jquery ajax in laravel5. What actually happens all the time is consolelog giving me an internal server error 500. I found some csrf solutions and added them to my code but they didnt help me. Any ideas?
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
$.ajax({
type : "POST",
url : "/save_like",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {photoId : photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
I also added this meta to my head:
<meta name="csrf_token" content="{{ csrf_token() }}" />
Everything goes through routes:
`Route::any('/save_like', 'Controller#saveLike');`
To the controller:
public function saveLike($photoId){
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
}
First the _token should be always sent in the http request so you could just add it to the data :
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
var _token = $('meta[name="csrf_token"]').attr('content');
$.ajax({
type: "POST",
url: "/save_like",
data: {_token:_token, photoId:photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
internal server error 500 mean the problem come from your server what mean in your case here it come from the action saveLike in your controller, so my guess is that this problem come from the expression WHEREid= ? :
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
____________________________________________________________^^^^^^^^^^
You're passing an array to = and that will cause the issue, try :
public function saveLike(){
$photoId = INPUT::get('photoId');
DB::update("UPDATE `photo_links` SET likes=likes+1 WHERE `id` = $photoId");
}
Hope this helps.
That's what i use in my app:
$("#captcha-gen-button").click(function(e){
e.preventDefault();
$.ajax({
url: "/captcha-ajax",
method: "POST",
headers: { 'X-CSRF-Token' : '{!! csrf_token() !!}' }
}).done(function(image) {
$("#captcha-img-container").html(image);
});
});
I think the problem is here:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
What happened when there is no token? beforeSend won't return anything. Change to this:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
return xhr;
},
I get the following issue when the user click the "login" button. Everything get well until the "addOrCreateUser" function. Here the POST request seems to be executed (I get an OK alert). Nevertheless, I have no log in my server side. I tried to lunch the "addOrCreateUser" based on a button click and then it works. Any idea?
.controller("LoginController", function ($scope, $cordovaOauth, $http, $localStorage, $location) {
$scope.form = {};
$scope.login = function () {
$cordovaOauth.facebook("xxxxxxxxxxxx", ["email"]).then(function (result) {
$localStorage.accessToken = result.access_token;
getUser($localStorage.accessToken);
}, function (error) {
alert("There was a problem signing in! See the console for logs");
console.log(error);
})
}
function getUser(token) {
$http.get("https://graph.facebook.com/v2.6/me", {
params: {
access_token: token,
fields: "id,email",
format: "json"
}
}).then(function (result2) {
$scope.form = {
'id' : result2.data.id,
'email' : result2.data.email
}
addOrCreateUser($localStorage.accessToken, $scope.form);
}, function (error) {
alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
}
function addOrCreateUser (token, form) {
$http.defaults.headers.common['Auth-Token'] = token;
$http({
url: API_URL + "/profiles",
data: form,
method: 'POST',
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
alert("ok" + data )
}).error(function (data, status, headers, config) {
alert("ko")
});
}
})
I'm trying to get a form to work with Ajax and json but can't seem to work it out:(
If anyone can help out I'd really appreciate it! Been reading so many different tutorials but not getting it right.
In my index.php I have a form with only a image that works as a button.
Then in another file (allFunctions.php) I have a class. Within that class I have a function called
giveCandy() which is connected to the button.
Then I have a js file that I'm now trying to get working with this. But When I click the button the page still refreshes and I get the value true printed out.
UPDATE: Still problem with the page refreshing...
The index.php file:
<form action="index.php" method="POST">
<input type="hidden" name="candy" />
<input type="image" id="button_candy" class="four columns" src="views/img/candy.png"/>
</form>
Then in my functions file:
function giveCandy ()
{
if ( isset($_POST['candy']))
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$candyPiece = 10;
$query = $db->prepare("SELECT fullness, lastfed FROM userdata WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
$data = $query->fetch();
$newFullness = $candyPiece + $data['fullness'];
try
{
$query = $db->prepare("UPDATE userdata SET fullness = $newFullness, lastfed = CURRENT_TIMESTAMP WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
//$this->calculateFullness();
echo json_encode($query);
}
catch (PDOException $e)
{
echo 'Sorry iti could not eat at this time';
}
}
}
Then the js file:
$(document).ready(function () {
$('#button_candy').click(function (event) {
event.preventDefault();
$.ajax({
url: 'index.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#query').fadeOut(function () {
$('#query').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});
allFunctions.php:
if ($_POST['candy']) {
allFunctions::giveCandy();
}
class allFunctions {
static function giveCandy ()
{
$db = Database::getInstance();
// ....
Js:
$(document).ready(function () {
$('#button_candy').submit(function (event) {
event.preventDefault();
$.ajax({
url: '../model/allFunctions.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#result').fadeOut(function () {
$('#result').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});