Select2 Dynamic Select AJAX - ajax

I have the following AJAX script:
$.ajax({
type:'POST',
url: '/carrier/manifests/storeManifestShipments',
data: {
proNumber: proNumber,
bolNumber: bolNumber,
poNumber: poNumber,
SpecInst1: SpecInst1,
SpecInst2: SpecInst2,
SpecInst3: SpecInst3,
billTo: billTo,
originName: originName,
originAddress1: originAddress1,
originAddress2: originAddress2,
originCity: originCity,
originState: originState,
originZip: originZip,
consigneeName: consigneeName,
consigneeAddress1: consigneeAddress1,
consigneeAddress2: consigneeAddress2,
consigneeCity: consigneeCity,
consigneeState: consigneeState,
consigneeZip: consigneeZip,
shipmentProjectedDate: shipmentProjectedDate,
shipmentWeight: shipmentWeight,
shipmentPieceCount: shipmentPieceCount,
createdBy: '{{Auth::user()->id}}',
_token: $('input[name=_token]').val(),
dataType: 'json',
},
success: function(response) {
if(response !== undefined) {
$('#createShipment').modal('hide');
var shipmentSelect = $('.shipmentSelect');
var option = new Option(response.pro_number, response.id, true, true);
shipmentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
shipmentSelect.trigger({
type: 'select2:select',
params: {
data: response
}
});
console.log('success');
}else{
console.log('failed');
console.log(response);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
toastr.error('Validation error - Make sure all required fields are filled!', 'Error Alert', {timeOut: 5000});
console.log('Internal error: ' + jqXHR.responseText);
} else if (jqXHR.status == 422) {
toastr.error('Validation error - Make sure all required fields are filled!', 'Error Alert', {timeOut: 5000});
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
As you can see, within the success event I lay out something similar to how the example suggests it here: https://select2.org/programmatic-control/add-select-clear-items.
The problem is that it doesn't want to "select" the item from the select2 that is referenced (.shipmentSelect). It doesn't throw an error either, but nothing really happens. It does print the success message in the console.
The response is formatted as such:
id: 1
pro_number: 1234
name: person1
.....
So I'm curious if there is a different way of formatting it, but I believe the issue comes from the following lines:
shipmentSelect.trigger({
type: 'select2:select',
params: {
data: response
}
});
I believe I need to provide maybe something else besides the general response?
Thanks

Related

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

While converting from jquery to angularjs why am I getting this error?

Jquery Code
$.ajax({
url: '/ad_creation/get_campaign_objective/'+id,
dataType: 'text',
success: function(response) {
var campaign_objective = 'Error. Please refresh and try again.';
if (response == 'WEBSITE_CONVERSIONS')
campaign_objective = response;
if (response == 'WEBSITE_CLICKS')
campaign_objective = response;
$('select[name=campaign_objective]').val(response).hide();
$('#existing-campaign-objective').html(campaign_objective).show();
$('#campaign-objective-select').show();
if (campaign_objective == 'WEBSITE_CONVERSIONS'){
// Show pixel block again.
$('#select-pixel').show();
}
hideAjaxLoader('existing-campaign-loader');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('Invalid response', thrownError, xhr, ajaxOptions);
hideAjaxLoader('existing-campaign-loader');
}
});
Angularjs code
$http({
method:'get',
dataType:'text',
url:'/ad_creation/get_campaign_objective/'+Number(id)
})
.success(function(data){
console.log(data);
})
I get the error Unexpected token w. I have also tried not casting the id to number but still get the error.
Check the content-type of the response headers.
If it is 'application/json' angular tries to parse the response.
The error might be because of it.

Trap message/exception in jquery to ELMAH

In my MVC3 application, I am returning messages from my stored procs. If it is 'successful', I'm moving forward else displaying a custom error page.
When the message is something else, I want to trap it in ELMAH. The problem that I am facing is that the return message is not really an error so I'm not able to figure out how to handle it. I still want to display the custom error page after catching the error in ELMAH.
Please help.
$.ajax({
url: "../XYZ",
type: 'POST',
dataType: 'text',
async: false,
data: JSON.stringify({ abcData: abcData, strDeb: strDeb, strCre: strCre }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (logout != "Logout") {
if (data.toLowerCase() != "successful") {
**//alert(data.toString());
window.location.href = "../Error";**
} else {
window.location.href = "../ABC";
}
}
},
error: function () {
var sessionWindowElement = $('#SessionLayoutLogOutWindow');
sessionWindowElement.data('tWindow').center().open();
}
});

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources