I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.
The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.
The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.
I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?
What else does it look like I could be doing wrong here?a
service.php
public function getSearch($query)
{
return $this->get("/search/search?query={$query}" );
}
I also set a new route for the controller and function
Route::post('autocomplete','Controller#autoComplete');
controller.php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
//$search_result = "test"; /*this hard coded value works for passing*/
$searchResults = $service->getSearch($search_result);
return $searchResults;
}
view.blade.php
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
Add this to your head
<meta name="csrf-token" content="{{ csrf_token() }}">
and pass the token to ajax:
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
"_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.
Related
In the below code, I'm able to transfer data but when I use the function append to transfer file and data it's not working. Can someone tell me how to transfer file from upload? Looking forward to some help
$(document).ready(function() {
var loader = '<img src="../assets/media/loader.gif" />';
$('#submit').click(function() {
confirm("Do you really want to send messages?");
$('.loading').html(loader).fadeIn();
var msg_area_cst = $('textarea[name=msg_area_cst]').val();
var num_cst = $('textarea[name=num_cst]').val();
var form_data = new FormData();
form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
form_data.append('upload', $('input[name=upload]'));
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
});
});
The problem is because you correctly declare a FormData object, but then in the next line overwrite it immediately with a string.
You need to append() all data to the FormData object. In addition you need to provide the file data to the append() method, not the jQuery object referencing the input type="file" control.
var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);
That being said, you can make this much more simple if the controls you're reading the values from are contained in a form element. Then you can use the submit event of that form and pass a reference to it to the FormData constructor.
Also you don't do anything with the result of the confirm() I assume you want to stop the form submission if Cancel is clicked, which the above example now does using preventDefault().
Finally, using html == 1 is very unreliable. Firstly html will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there's any whitespace included. I'd strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a 'success' flag.
With all that said, try this:
$('#yourForm').on('submit', function(e) {
if (!confirm("Do you really want to send messages?")) {
e.preventDefault();
}
$('.loading').html(loader).fadeIn();
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: new FormData(this),
success: function(html) {
if (html.trim() === "1") {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});
Try this ajax code
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
async: true,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
I want to know is that possible to send data from one ajax by another ajax or not?
Sounds confusing I know, but here is explanation:
I have payment method where it gets data and handling them by Ajax (unfortunately the creators of this API limited their code a lot) so even if i try to add input request in controller code of that Ajax nothing will work, that's why I need to make another Ajax to handle that input request.
Lets explain more by codes:
controller
public function orderspayonline(Request $request, $id){
error_log('masuk ke snap token dri ajax');
$midtrans = new Midtrans;
//products data + user info etc.
//here magic happens
try
{
$snap_token = $midtrans->getSnapToken($transaction_data);
echo $snap_token;
}
catch (Exception $e)
{
return $e->getMessage;
}
}
If I add anything (I mean anything) in that try{ part it will stop functioning and return error! `even I tried to redirect back my users except echoing token code that gave error as well. So it seems I really don't have any option here but to create new function and Ajax.
JavaScript
<script type="text/javascript">
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("orderspayonline")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type,data){
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
}
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result){
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result){
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
</script>
The part I need to manipulate is snap.pay(data, { where results gets back.
Currently they are return in console and disappear in a sec as the result of echo $snap_token; in my controller.
I have tried to get them in hidden input, but as I mentioned I cannot get results because I can't change my try code, even I tried to get them after catch part closed, the same thing happens Error.
Question
How can I get my results in controller?
I need to update my database with that results.
Thanks.
From what I can see you have two choices.
Add another client-side AJAX call within the snap.pay function
Redirect the submission of payment-form towards your own app and then do the onward submission from the server-side.
Option 1:
function serverSubmit(d) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: '{{url("newroute")}}',
type: "POST",
cache: false,
data: d
});
};
Then amend snap.pay to submit, e.g.
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
serverSubmit(result); // <----------
$("#payment-form").submit();
}
...
You may want to encrypt the data if it is sensitive, and you may want to decide not to submit the form if you don't get a successful result from the serverSubmit. You may also want to submit supplemental data beyond the result, but this is a start.
Option 2
Change the <form id="payment-form... action to {{url('newroute')}}
In your controller add a new method and map a post newroute to it.
public function new_method(Request $request)
{
$data = $request->validate(...);
YourModel::create($data); //however you want to save it
$url = 'old_form_submit_URL';
$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);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* There was an error */ }
}
I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.
I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.
I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.