jQuery blocking ajax post - php

Im trying to have a form do a post using ajax method it is getting blocked by jquery line:7845
xhr.send( options.hasContent && options.data || null );
how can i fix this, keeps omiting ' send.php 404 not found '
send.php is in inside js folder here is my code for php file
$('#contact').submit(function(e){
e.preventDefault()
if(!$('#contact').valid())
return false;
$('#submit').fadeOut(200,function(){
$('.sending').fadeIn(200);
});
$.ajax({
url: 'js/send.php',
type: 'post',
data: {name:$("input[name='name']").val(),
email:$("input[name='email']").val(),
comments:$("textarea[name='comments']").val(),
},
success: function(data) {
if(data==1)
{
$('.sending').html('Sent Successfully Thank You!');
$('#contact').fadeOut(500);
$("#contact input:not(#submit)").val('');
$('#contact textarea').val('');
txt_name = null;
}
else alert("error sending");
},
error:function(err)
{
alert("error sending");
}
}); });

Related

Ajax DELETE redirects even if prevented

I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.
My controller's action:
public function deletePhoto(Photo $photo)
{
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);
return response()->json(['result' => 0]);
}
return response()->json(['result' => 1]);
}
It works this way while adding photos (it adds but doesn't redirect).
Here is my ajax code:
$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.
How do I solve this problem?
Add a prevent default to your submit event. The page is redirecting because you're initiating a submit event.
e.preventDefault();
Change submit event to:
$("#form-submit-button").click(function(e){
});
try this:
$('#deleteForm').submit(function(e) {
e.preventDefault()
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
you need to add preventDefault to prevent the page from redirecting
check from console if there is errors in javascript code to work the e.preventDefault

trouble in call a ajax file in jquery

This below coding is working in chrome browser but not in mozilla. How to solve this problem in mozilla firefox.
$(document).ready(function() {
$("#del_enquiry").click(function() {
var enquiry = new Array();
$('input[name="del_enq"]:checked').each(function() {
enquiry.push(this.value);
});
if(confirm("Do you want to delete the Records"))
{
var delid="deleteid="+enquiry;
$.ajax({
url: "delete_enquiry.php",
type: "POST",
data: delid,
cache: false,
success: function(data) {
if(data==1) {
alert("Record Deleted Successfully");
} else {
alert("Record not Deleted");
}
}
});
}
});
});
You can use onsubmit atttribue of form tag function before submitting the form.
Inside my function write your confirm box conditions.
if(confirm("Do you want to delete?"))
{
return true;
}

How can I retry an ajax request on empty response

I would like to retry an ajax request when response data is an empty json object.
My ajax code is following.
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
$(this).ajax();//retry ajax request here, if data is empty
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
PHP
echo json_encode(array(
'type'=>$paymentType,
'btn'=>$this->PaymentBtn,
'usd' => round($this->finalUSDAmount,2),)
);
You can put your ajax request in a function and then call that function If the respons is empty.
Like this:
function yourCall(){
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
yourCall();
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
}
this setup will however keep trying the ajax call untill it gets a valid respons. This meaning that it will keep firing if the respons length == 0
Just Simply Do Following:
$.ajax({
url : 'index.php?r=funding/getPaymentButton',
type : 'POST',
data : {email:benfEmail,data:JSON.stringify(data),paymentType:method},
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});

Handle error in jQuery.ajax() when something doesn't work

I have a php file with a form that is sent using jQuery.ajax(). The problem that I have if the email is not sent and the error message is not shown.
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
$('#result').css('background', 'green');
},
error: function(responseText) {
$('#result').css('background', 'red');
}
});
return false;
});
});
As the email is not sent the error not shows anything but the success yes. So, I change my mail.php code for that other code.
<?php
if(2 > 4) {
true;
} else {
false;
}
?>
When I press the button, the success action stills working and I don't know why.
The error callback is only triggered if the ajax call fails, not if the PHP mail function fails, and not if you return false, that would be a success as you received something back from the server (the string "false").
To catch errors like that you can either trigger an error from PHP or just catch it in the success handler:
success: function(data) {
if (!data || $.trim(data) == 'false') {
$('#result').css('background', 'red');
}else{
$('#result').css('background', 'green');
}
},
and PHP
<?php
echo 2>4 ? 'true' : 'false';
?>
Remove the error function & make changes to your success function
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
if(responseText)$('#result').css('background', 'green');
else $('#result').css('background', 'red');
}
});
The error function will not trigger unless jQuery fails to connect to your php file, in this case you would wan't to handle your own errors, first off what does this do?
if(2 > 4) {
true;
} else {
false;
}
this would not send anything back to jQuery i recommend the following
if(2 > 4) {
echo 'true';
} else {
echo 'false';
}
then in your jQuery
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(result) {
if(result === 'true') {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
},
error: function(error) {
alert(error)
}
});
return false;
});
});
In your both cases, the success callback is fired:
success: function(responseText) {
if(!!responseText) //!! convert string to boolean
$('#result').css('background', 'green');
else
$('#result').css('background', 'red');
},
First in mail.php file echo that you want to return:
<?php
if(2 > 4) {
echo "true";
} else {
echo "false";
}
?>
And then in success function do that:
success: function(responseText) {
if(responseText) {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
}
It also depends on the version of the jquery you are using. If its 1.9 then you can handle it using the done, fail and always function
For 1.9
var request = $.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
}
});
request.done(function(e){
//GET THE STATUS FOR THE EMAIL FROM THE PHP SCRIPT
//ASSUMPTION THAT FETCHING e=1/0 - 1 - Success, 0 - Failure
if(parseInt(e))
{
$("#result").css("background","green");
}
else
{
$("#result").css("background","red");
}
});
1) Your php script doesn't return anything. For instance, if you eliminate all javascript from your html page, and your form's action attribute specifies myphp.php, and myphp.php looks like this:
<?php
$html = "<html><head></head><body><div>Hello world.</div></body></html>";
?>
What will be displayed after you click on the form's submit button?
2) The error function is called if the request fails. Getting a response of nothing or false from your php script is not a failure of the request. A successful request means that the browser sent out a request, the server received the request, the server caused your php script to execute, and the server sent back the results of your php script as a response. A request fails if the server is too busy to respond to the request, the server crashes while handling your request, you request a file that doesn't exist, etc.

Send This array to php and get results in div (FCBKcomplete)

I'm using an autosuggest plugin that allows me to select multiple items from a dropdown menu (demo here). I want a query to be sent to a php file (I will be preoccupied with the query itself later) and get a result back without leaving the page.
The php file is pretty much empty right now:
<?php print_r($_REQUEST); ?>
But I know I made a mistake with my jquery somewhere since the search box is not displaying properly anymore.
Here's the code I built up, I'm not sure what to put in the "data" field.
<script type="text/javascript">
$(document).ready(function(){
$("#select3").fcbkcomplete({
json_url: "data.txt",
addontab: true,
maxitems: 10,
input_min_size: 0,
height: 10,
cache: true,
newel: false,
filter_selected: true,
maxitimes: 5,
// I did this
onselect:"get_venue",
});
// I also did this
function get_venue() {
$("#select3 option:selected").each(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
WHAT DATA GOES HERE?
},
success : function(data){
$('#phpmessage').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
});
}
});
</script>
Sorry for such a long post everybody :)!! Thanks :))
Error I'm getting:
Is not a function: return func.call(func, _object);
function funCall(func, item) {
var _object = {};
for (i = 0; i < item.get(0).attributes.length; i++) {
if (item.get(0).attributes[i].nodeValue != null) {
_object["_" + item.get(0).attributes[i].nodeName] = item.get(0).attributes[i].nodeValue;
}
}
return func.call(func, _object);
}
function checkFocusOn() {
if (focuson == null || focuson.length == 0) {
return false;
}
return true;
}
You want to loop over each of the items in the search box, these have a class of .bit-box. Create an array of these search terms then send them in as data into the ajax request.
function get_venue() {
var data = [];
$('.bit-box').each(function() {
data.push( $(this).text );
});
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
'choices[]': data
},
success : function(data){
$('#phpmessage')
.removeClass()
.addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true){
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
}

Categories