jQuery AJAX: Uncaught SyntaxError: Unexpected token - javascript

I am trying to update my div content with new content when the user uses the search textbox:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Now I have a dropdown selecting what they want to filter the search by, the username or the business name. This is the line that is throwing the error.
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name";
Am I doing something wrong?

You should have a comma ',' at the end of the url line:
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});

You don't have dataType defined for the ajax call.
Add dataType which is the expected format of your ajax request which can be text, json etc

Try This Code
$('#business_request_filter_search_textbox').on('input propertychange paste', function () {
$.ajax({
url: "/ajax/housekeeping/business/" + $("#search_filter_selection")[0].selectedIndex == 1 ? "get-requests-by-username" : "get-requests-by-business-name",
type: "GET",
cache: false,
data: { search: $('input#business_request_filter_search_textbox').val() },
beforeSend: function(xhr) {
$('#request_area').html('<center>Please wait while we gather results...</center>');
},
success: function(data) {
$('#request_area').html(data);
},
});
});
Hope This help You :) Enjoy :)

Related

how to catch the jquery ajax function return value in another variable

I am looking to store a value which is return by the AJAX function, here is the my code, in the AJAX success it is showing well, but when am storing that data which is saying undefined.
The following serviceNumber, which I am storing the enCrypt return value
var serviceNumber = enCrypt(typeofServiceNumber);// when am catching the function data which is saying "undefined"
the following code is my ajax function
function enCrypt(id) {
if (id > 0) {
$.ajax({
url: $("baseUrl").html() + "JobProfiles/Encryption",
type: "POST",
dataType: "json",
data: { Id: id },
success: function (encdata) {
return encdata;
},
error: function (data) {
$('#loading').hide();
}
});
}
}
Can you help me to know what is wrong in my code? Thanks in advance.
You can't use return like this, because the function is async + it's a function in a function...so actually yeah you cant return there xD
Just do something like:
enCrypt(typeofServiceNumber);
//and in your ajax:
success: function (encdata) {
go_on(encdata);
},
//and then
function go_on(serviceNumber)
{
//here you can use it :D
}
just add the
cache: false,
async: false,
to you ajax function
function enCrypt(id) {
var encnum;
$.ajax({
url: $("baseUrl").html() + "JobProfiles/EncodeIds",
type: "POST",
cache: false,
async: false,
dataType: "Json",
data: { Ids: id },
success: function (encdata) {
encnum = encdata;
},
error: function (data) {
$('#loading').hide();
}
});
return encnum;
}

jQuery does not work in IE11, but works in Chrome

I have problem with jQuery. When I upload image in Chrome it performs the AJAX successfully and I am able to update the page with the response data. But in IE 11 and Firefox it does not. The code:
$(".newfoto").on('submit', (function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
e.preventDefault();
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#mailresult").html(data);
setTimeout(function() {
$("#mailresult").empty();
}, 2000);
var imgTag = '<img src="image.php?imgid=' + escape($('.myphoto').attr('id')) + '" />';
$('.myphoto').html(imgTag);
},
error: function() {}
});
}));
The correct way to prevent the form from submitting and reloading the page is to use a return false; at the end of the submit function. This will also replace e.preventDefault(); in your code.
Also, FormData is not supported on all browsers. See https://stackoverflow.com/a/2320097/584192. You may need to detect and workaround this.
$(".newfoto").on('submit', function(e) {
$("#mailresult").html('<img src="themes/standart/iconss/spin1.gif" alt="loading..." /><p>Please, wait...</p>');
$.ajax({
url: "dataok.php?act=foto",
type: "POST",
data: (typeof FormData === 'function') ? new FormData(this) : $(this).serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success
},
error: function(jqXHR, status, error) {
console.log(error);
}
});
return false;
});

MVC4 and jQuery/AJAX - Error not found when posting JSON

I am using Ajax (and jQuery UI) and when i press a button on the dialog i trigger the following action in the controller:
[HttpPost]
public JsonResult DeletePost(int adrId)
{
return Json("Hello World Json!", JsonRequestBehavior.DenyGet);
}
My JQuery Code looks like this:
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog(
{
buttons: {
"Ok": function () {
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: { adrId: 6 },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
$(this).dialog("close");
}
}
});
jQuery('.delete').click(function () {
})
})</script>
However, when i POST to the server, i get an "Error: Not Found"
The problem is with your data parameter not being a valid JSON payload.
It is not valid JSON, because jQuery is using the jQuery.param() method internally to prepare the request parameters for typical POST submissions, and it will get converted to the following string:
adrId=6
However, the server is expecting a JSON payload, and what you specified is clearly not a JSON payload. A valid JSON payload would be:
{ 'adrId': 6 }
One approach to send correct JSON in the data parameter is to refactor your jQuery AJAX to look like this:
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: "{ 'adrId': 6 }",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert("success");
},
async: true,
processData: false
});
Or you can use JSON.stringify as suggested by others.
An alternative approach would be to send your data as 'application/x-www-form-urlencoded; charset=UTF-8' which is the default, and that way you don't have to change your data parameter. The code would be much simplified:
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: { adrId: 6 },
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert("success");
},
async: true
});
JQuery will recognize that the result is valid JSON.
Try this:
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog(
{
buttons: {
"Ok": function () {
$.ajax({
...
data: JSON.stringify({ adrId: 6 }),
...
});
$(this).dialog("close");
}
}
});
jQuery('.delete').click(function () {
})
})</script>

Not refreshing data each time

I have weired problem in my project.I have 2 tabs and in one tab i have chekboxes and submit button and user will select from checkboxes and on button click he will get what he has selected from checkboxes in another tab.It runs perfectly.But sometimes it does not refresh the data from ajax ,jquery and i have to complete refresh my page.I am not able to identify the problem as i am not getting any error. Atleast i have to click for more than 15 times then it will not refresh the data otherwise it works fine.
Here is my js code:
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(opts.length == 0) return false;
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
//getFahrzeugeWidget();
$('#fahrzeuge').html(data['html']);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidgetEdit(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle-edit'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
var opts = getFahrzeuge();
if($(this).attr('id') == 'saveId')
{
saveFahrzeugeWidget(opts);
if($('#fahrzeuge input[type="checkbox"]:checked').length <=0) {
alert('überprüfen Sie bitte atleast ein fahrzeuge');
//getFahrzeugeWidgetEdit(opts);
}
}
});
The answer is getting cached. And you are receiving the same answer. Try to add a new parameter to data as timestamp.
So your data should look like this.
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle', 'timestamp': new Date().getTime()},

How to group rules in jquery

Hi I've got a simple question. I've this code below, i use ajax three times in very similiar ways the only things that change are the data passed and the id of the target. Is there a way to group these instructions in a simple one?
Thx
D.
$('#fld_email').focusout(function() {
var request_email = $(this).val();
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=firstname&email="+request_email,
beforeSend: function(){$('#fld_firstname').addClass('ac_loading');},
success: function(msg){$('#fld_firstname').val(msg);$('#fld_firstname').removeClass('ac_loading'); }
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=lastname&email="+request_email,
beforeSend: function(){$('#fld_lastname').addClass('ac_loading');},
success: function(msg){$('#fld_lastname').val(msg);$('#fld_lastname').removeClass('ac_loading');}
});
$.ajax({type:"GET",
url: "autocomplete.asp",
data: "fld=phone&email="+request_email,
beforeSend: function(){$('#fld_phone').addClass('ac_loading');},
success: function(msg){$('#fld_phone').val(msg);$('#fld_phone').removeClass('ac_loading');}
});
}
);
try:
$('#fld_email').focusout(function() {
var request_email = $(this).val();
processAjax("fld=firstname&email="+request_email, '#fld_firstname');
processAjax("fld=lastname&email="+request_email, '#fld_lastname');
processAjax("fld=phone&email="+request_email, '#fld_phone');
});
function processAjax(data, id){
$.ajax({type:"GET",
url: "autocomplete.asp",
data: data,
beforeSend: function(){$(id).addClass('ac_loading');},
success: function(msg){$(id).val(msg).removeClass('ac_loading');}
});
}
Use an object and the for control structure:
var fields = {firstname:1, lastname:1, phone:1};
for (field in fields) {
$.ajax({
type:"GET",
url: "autocomplete.asp",
data: "fld=" + field + "&email=" + request_email,
beforeSend: function() {
$('#fld_'+field).addClass('ac_loading');
},
success: function(msg) {
$('#fld'+field).val(msg);
$('#fld'+field).removeClass('ac_loading');
}
});
}

Categories