I have seen many solution for the above question but none of them falls in my category. My server is responding with correct json. Not able to figure what is exactly causing the issue. I get status as 0 and status text as error . Its disgusting . Issue is in deleteimage() function. There mi8 be issue in a way i am handling event.If anyone can figure out it would be good.Almost a day gone after this. Help is appreciated.
$(document).ready(function() {
//grab all form data
var form = $('#get_design_form');
form.submit(function(event) {
event.preventDefault();
var x = true;
if(category_id.value == '0'){
alert("Please select category.");
category_id.focus();
x=false;
return x;
}
if(design_no.value == ''){
alert("Please enter design no.");
design_no.focus();
x=false;
return x;
}
if (x) {
$('#send').attr("disabled",true);
$('#lm').show();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success : function(data) {
var result = data;
if(result.response_code=='101'){
$('#failure').show();
$('#success').hide();
$('#failure').text("Error Occured.Try again");
}else if(result.response_code=='102'){
$('#failure').show();
$('#success').hide();
$('#failure').text("Design no. does not exist.");
}else{
$('#con2').show();
$('#con1').hide();
$('#category_name').val(result.design_details.category_id);
$('#des_no').val(result.design_details.design_no);
//$('#image').attr('src','downloadImage?image_name='+result.design_img);
for(i=0;i<result.design_details.list_design_img.length;i++){
var html='<img id="'+result.design_details.list_design_img[i].design_img_path.split(".")[0]+'" src=downloadImage?image_name='+result.design_details.list_design_img[i].design_img_path+' style="vertical-align:middle;" width="100" height="100">';
var html1='<span style="cursor:pointer;" onclick="javascript:deleteimage(\'' + result.design_details.list_design_img[i].design_img_path + '\',\'' + result.design_details.category_id + '\',\'' + result.design_details.design_no + '\')">X</span>';
$('#img_div').append(html);
$('#img_div').append(html1);
}
}
$('#lm').hide();
$('#send').attr("disabled",false);
}
});
}
});
//return false;
$('#send').attr("disabled", false);
$('#lm').hide();
});
<script type="text/javascript">
function deleteimage(image_name,category_id,design_no)
{
alert("hii"+image_name+","+category_id+","+design_no);
var answer = confirm ("Are you sure you want to delete?");
if (answer)
{
$.ajax({
url: "http://192.168.0.2:8080/JaydeepSarees/deleteOthersDesignImgPath",
data: jQuery.param({image_name: image_name,category_id: category_id,design_no: design_no}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
type: "post",
success: function (data) {
alert("hii");
var result=data;
alert(result.response_code);
if (result.response_code == 100) {
alert(result.response_code);
$("#"+image_name).remove();
}
},error: function (jqXHR,exception) {
console.log(jqXHR);
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.'+jqXHR.statusText;
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
});
}
return false;
}
</script>
I needed to use an relative path when trying to send request to server where in i was using absolute path that was the reason i was getting status as 0.
url: "deleteOthersDesignImgPath"
instead of
url: "http://192.168.0.2:8080/JaydeepSarees/deleteOthersDesignImgPath",
Related
I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.
i am trying to make this ajax to submit my form but it only goes to the very last errror(Unexpected error! Try again).when i remove the datatype:json part,it then alerts undefined
function ajax(action,id){
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "POST",
url: "ajax.php",
data : data,
dataType: "json",
success: function(response){
if(response.success == "1"){
if(action == "save"){
$(".dert-form").fadeOut("fast",function(){
alert(here first);
});
}else if(action == "delete"){
alert(here to delete);
}
}
},
error: function(res){
alert("Unexpected error! Try again.");
}
});
}
here is ajax.php
if($action == "save"){
/* Check for blanks */
$err = "You have blank fields. ";
echo json_encode(
array(
"success" => "0",
"msg" => $err,
)
);
}
Here is a working example of your code with some adjustments:
function ajax(action,id){
action = 'save';
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "GET",
url: "http://demo.ckan.org/api/3/action/package_list",
data: data,
dataType: "jsonp",
success: function(response){
console.log(response);
if(response.success == "1"){
if(action == "save"){
$(".dert-form").fadeOut("fast",function(){
alert("here first");
});
}
else if(action == "delete"){
alert("here to delete");
}
}
},
error: function(res, textStatus, errorThrown){
console.log("Unexpected error! Try again.");
}
});
}
I'm hitting a data.gov API endpoint and logging the response to the console. Note, the dataType has to be jsonp since I'm make a cross-domain request. You can also look at the JSBin I created with the above code.
use json format for data instead or query string
data = {"action":action,"item_id":id};
So I have a javascript ajax call like so:
$.ajax({
type: "POST",
url: "/checkout/doCharge",
data: dataString,
success: function(data) {
if(data == '1'){
$("#CheckoutSubmit").prop('disabled', false);
}
else{
$.growl.error({ message: "Your card was declined! Please try again." });
}
}
});
return false;
And the php call is:
$response = $this->stripe->charge_card($amount, $card, $desc);
if($response['paid'] == 'true'){
echo '1';
}
else{
echo '0';
}
Right now, the if(data == '1') is not working. it doesn't throw any error either. I am trying to get data as 1 if the paid response is true and 0 if the response is false.
Use $.trim to remove extraneous whitespace around the response.
success: function(data) {
data = $.trim(data);
if(data == '1'){
$("#CheckoutSubmit").prop('disabled', false);
}
else{
$.growl.error({ message: "Your card was declined! Please try again." });
}
}
I have a form I am trying to submit via ajax from PHPAcademy's tutorial found here
Basically the form needs to submit via ajax, simple enough. But when I try do that, it just opens the PHP file in the browser. PLEASE HELP!
here is the ajax code:
$('form.login_settings').submit(function(){
var that = $(this),
url = '../login_settings_submit.php',
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
I have tried using e.preventDefault(); but with no luck
I have also tried changing the initial function from
$('form.login_settings').submit(function(){
to
$('form.login_settings').on('submit', function(){
What am I doing wrong?
It's pretty easy friend:
Java Script Code:
$(function() {
$('form.login_settings').submit(function(e){
e.preventDefault();
var that = $(this),
type = that.attr('method'),
data = that.serialize()
$.ajax({
type: type,
url: '../login_settings_submit.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
});
use jQuery .serialize method to parametrize form data and write code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
and if you wanna check ajax error then you can use
,error : function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status === 404) {
alert('The requested page not found. [404]');
} else if (jqXHR.status === 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
after success method. It's good to check ajax error always when you are in production.
I have created a javascript and a WebMethod. It works in IE but not in firefox and chrome
MyWebMethod
[WebMethod]
public string Send(string name, string email, string message)
{
try
{
MailMessage objMailMessage = default(MailMessage);
objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(email, name,System.Text.Encoding.UTF8);
objMailMessage.To.Add("feedback#abc.in");
objMailMessage.Subject = "Feedback";
objMailMessage.Body = "<b>Name :</b> " + name + "<br/><br/>";
objMailMessage.Body += "<b>Email :</b> " + email + "<br/><br/>";
objMailMessage.Body+= "<b>Message :</b> "+message;
objMailMessage.IsBodyHtml = true;
objMailMessage.Priority = MailPriority.High;
CommonFunctions.CommonFunctions.SendEmailMessage(objMailMessage);
return "success";
}
catch (Exception ex)
{
Logger.Log.Error(ex);
return "Fail";
}
}
MYScript
$.ajax({
datatype: 'text',
type: 'POST',
url: options.url,
data: { name: $(this_id_prefix + '#name').val(), email: $(this_id_prefix + '#email').val(), message: $(this_id_prefix + '#message').val() },
success: function (data) {
$(this_id_prefix + '#loading').css({ display: 'none' });
var xmlDoc = data;
var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue;
if (returnvalue == "success") {
$(this_id_prefix+'#callback').show().append(options.recievedMsg);
setTimeout(function () {
$(this_id_prefix + '.holder').show();
$(this_id_prefix + '#callback').hide().html('');
}, 2000);
if(options.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$(this_id_prefix+'#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$(this_id_prefix+'div#contactable_inner').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$(this_id_prefix+'#overlay').css({display: 'none'});
}
} else {
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
setTimeout(function(){
$(this_id_prefix+'.holder').show();
$(this_id_prefix+'#callback').hide().html('');
},2000);
}
},
error:function(){
$(this_id_prefix+'#loading').css({display:'none'});
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
}
});
I am not able to get return value from webmethod to script. In Success funcation I want to check that if(data=="Success") but here I am not able to check that. Is there anything wrong in script like datatype or any other issue? Here var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue; is not working. It works locally fine but after publish to server it's not working. It return object xmldocument in data. It's not returing string. I have changed datatype to text