javascript not show results on success - javascript

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.

Related

laravel, ajax call from input to controller function 500 error

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.

AJAX post to php not getting caught

Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});

Jsonresult is failing with parameter in my Ajax Call. Why is it happening?

That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request.
The script works (I get correct response on back-end).
But I cant seem to make any alerts, so I think there is some problem with the success function.
Do you guys see any obvious mistakes?
The browser gets the correct responses (Inspect webpage in chrome).
<script>
$(document).ready(function() {
var frm = $('#registerform');
frm.submit(function(x) {
x.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/v1/register',
data: frm.serialize(),
crossDomain: true,
success: function(data){
if(data == 200){
alert("successfully registered");
$('#alert').append("successfully registered");
}
if (data == 400){
alert("email or password empty");
}
if(data == 403){
alert("passwords do not match");
}
}
});
});
});
</script>
You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.
$.ajax({
url: "/echo/xml/",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType:"text xml",
success: function(xml, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
}
});
The xhr.status is what you will need to compare against instead of your data.
When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

using returned json values in calls not working

Trying to use the values I return from my php yet there are not working properly.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
// fade out the deleted comp
$("#c"+response.computer_id+"").fadeOut("slow");
// remove from the drop down
$("#comp_selection option[value='#c"+response.computer_id+"']").remove();
} else {
alert('Some error occurred.');
}
});
});
});
</script>
I am returning from the php file :
echo json_encode($ajax_result);
which is returning :
{"computer_id":1,"success":"success"}
EDIT: I found a small error in code outside of this where I was returning a different value than expected. All is well and the above was indeed correct to start with.
You should debug using firebug or whatever developer tools you have in your browser - firebug in Firefox is very good for this as you can see the JSON data passed back from the AJAX call.
That said, your issue is that the data is probably under response.d - so look at response.d.success and response.d.computer_id
Maybe the content you are receiving from your PHP server is sent as simple text, and must be sent with the headers set for JSON content:
header('Content-Type: application/json');

Categories