How to express != in URLs - javascript

I wrote the following ajax call to fetch data using the nb (number of document view) parameter:
if ($("#fetch").hasClass("active")) {
$.ajax({
url: "ServletAjaxController",
type: "POST",
dataType: "json",
data: "c=" + controller + "&nb=300",
success: onSuccess,
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
});
}
Now I want to do the same thing but expressing nb != 300 instead of the equal expression. Any IDEAs?

Related

How to call one ajax inside other ajax in a chained manner?

How to call multiple ajax calls one after another in a chained way?
Hi,
I am having a controller method which returns json based on the start limit and end limit which needs to done by ajax call.
So, initially in first ajax call start limit =1 and end limit=100 and on success of this ajax, same ajax call should be called with updated start limit =101 and end limit=200.
Like wise multiple ajax reuqests needs to be sent till actual dead line of 1000 i reached.
So totatlly 10 ajax calls from 1-100,101-200,201-300 e.t.c till 1000 have to be sent.
Actually i am sending these chained ajax;s this way,
$.ajax({
url: getdata/100/200",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//2nd ajax
$.ajax({
url: getdata/101/201",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//3rd ajax
$.ajax({
url: getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
}
}
But all the time only my first ajax is getting success and rest of the ajax;s are not getting executed and giving 404 error.
Is there any timeinterval needs to be set for calling one ajax inside?
What is the mistake i am doing here..?
can anyone help me in this issue?
Thanks
You can solve these issue by using function like following :-
// Make initial call to function with your data
myAjaxCall(data, 1, 100);
function myAjaxCall(data, startLimit, endLimit)
{
$.ajax({
url: "getdata/"+startLimit+"/"+endLimit, // Concat variables as per your codes
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
myAjaxCall(data, endLimit+1, endLimit+100);
}
}
});
}
If you need to chain Ajax call try to use Jquery.Deferred
it will looks like:
$.when($.ajax(...)).then($.ajax(..)) ...
You can achive this by recursive function
function ajaxRun(data){
$.ajax({
url: "getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(resultData) {
json=JSON.stringify(resultData);
console.log("json" + json);
console.log(JSON.stringify(resultData));
if(json != null && json != "") {
ajaxRun(data);
}
}
});
}
Hello change your parameter name every ajax success method like
success: function(resultData)
second time
success: function(secondresultData)

Jquery - Calling a ajax function within ajax function

Can I use ajax function withing a ajax function.
In my case there are two ajax calls. First ajax will return some data , If it is successful then the second ajax should be called .
Below is my code snippet,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here"
dataType = "json",
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
Some more info :
I had checked chrome dev console and the error I am getting is
//success - 1
success: function(data) {
//Error message : Uncaught SyntaxError: Unexpected identifier
That was the error message I got.
And yes I cleared the syntactical mistakes and I was getting the same error message.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here",
dataType : "json"
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
I checked the service URL in RESTClient extension of firefox browser and again yes , there is Jsondata coming from that service.
Any good suggestion will be highly appreciable
Merry Christmas :)
There are some errors in your scripts.
In the first ajax call, where are the commas to separate the members ?
url:"my service url here",
dataType= "json",
and this should be:
dataType : "json",
Going back to your answer, yes you can but, what if you had the third ajax call?
Your code would be a mess and really hard to read.
The best would be to use promises.
This is the best way to work with asynchronous in javascript (that's also the reason why I've commented your async:false ).
You can read how promises work here.
$.ajax already returns a promise:
var promise = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url:"my service url here",
dataType: "json",
});
which could be chained with another one:
promise.then(function(result){ });
I tend to prefer the approach where I split my ajax call in different function which create a new promise and return it; just in case I want to manipulate the result:
You can split the two ajax calls:
function FirstAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
// async : false,
url:"my service url here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
and
function SecondAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
// async:false,
url: "my second service URL here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
Now you could resolve the first one and chain the second one:
FirstAjaxCall()
.then(function(result){
return SecondAjaxCall(result);
})
.then(function(result){
// final result
})
.fail(function(reason){
// reason should contain the error.
});
As you can see FirstAjaxCall() is resolve in the .then() branch and it passes it's result in the anonymous function. Same thing happens with the second ajax call SecondAjaxCall(). If something fails in the first or the second call the errors are trapped here:
.fail(function(reason){
// reason should contain the error.
});
The beauty of promises is you can chain them or execute them in parallel.
Yes you can.
Something wrong in your code that I can see is that }//success-1 is before });//ajax - 2 and it should be after.
also there is a missing coma ( ,) after url:"my service url here",
replace the '=' you have by ':' for your two dataTypes.
your should correct that and try again.
Try something like below in a structured way:
//First method with callback
function myFirstCall(callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here",
dataType= "json",
success:function(data){
callback();
});
}
// Second method
function mySecondCall() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my second service url here",
dataType= "json",
success:function(data){
});
}
//Let's trigger it
myFirstCall(function() {
mySecondCall();
});
You have to change "=" after the first "dataType" to ":"
dataType= "json", => dataType : "json",
and move "alert" function to the outside the second $ajax block.
$.ajax({ => alert('inside ajax-2');
alert('inside ajax-2'); $.ajax({
Last, order of closing brackets are opposite.
}//success-1 => });//ajax - 2
});//ajax - 2 }//success-1
The following code should work as you thought.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here"
dataType : "json",
//success - 1
success:function(data){
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
alert('inside ajax-2');
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function (data) {
//some functionality
}//success-2
});//ajax - 2
}//success-1
});//ajax - 1

Ajax passing null value to controller

I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.

Server does not receive data from ajax call

I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});

Syntax error in Javascript function

Java script
$('#senurl').click(function () {
$.ajax({
type: "POST",
url: "/Admin/Coupon1/Reject",
dataType: "json",
data: "id="+#Model.id+"&url="+#url
});
});
ReferenceError: Expired is not defined
[Break On This Error]
data: "id="+2925+"&url="+Expired
You probably want (but see also below):
$('#senurl').click(function () {
$.ajax({
type: "POST",
url: "/Admin/Coupon1/Reject",
dataType: "json",
data: "id=#Model.id&url=#url"
});
});
...because you have to think about what the browser sees, and if #url gets replaced with Expired by the server, from the error you can tell that what the browser sees for your code is:
data: "id="+2925+"&url="+Expired // <=== What the browser sees with your current code
Even better, let jQuery handle any potential URI-encoding needed by passing it an object instead:
$('#senurl').click(function () {
$.ajax({
type: "POST",
url: "/Admin/Coupon1/Reject",
dataType: "json",
data: {id: #Model.id, url: "#url"}
});
});
If you don't want to pass jQuery an object and let it handle the URI-encoding for you, then you'll want to handle it yourself:
data: "id=#Model.id&url=" + encodeURIComponent("#url")
$('#senurl').click(function () {
$.ajax({
type: "POST",
url: "/Admin/Coupon1/Reject",
dataType: "json",
data: "{id:'" + #Model.id + "', 'url': " + #url + "}",
success: function (response) {
alert( response.d);
},
error: function (data) {
alert(data);
},
failure: function (msg) {
}
});
});
Try this it is working fine. If you are using url routing then you might get some other error.
so better get the respone output and check..
I think its because #url variable is assigned data Expired without quotes.

Categories

Resources