how to change the code from $.ajax() to $.getJSON - javascript

this code works using ajax and I want to change it using json, what is the right way to use it?
AJAX
$('#movie-list').on('click', '.see-detail', function() {
$.ajax({
url: 'http://omdbapi.com',
dataType: 'json',
data: {
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
success: function (movie) {
$('.modal-body').html(`...`);
}
})
});
JSON
$('#movie-list').on('click', '.see-detail', function() {
$.getJSON('http://www.omdbapi.com/?apikey=myapikey&i=='+ $(this).data('id') +'', function(data) {
$('.modal-body').html(`...`);
});
});

Look at the documentation:
jQuery.getJSON( url [, data ] [, success ] )
So:
jQuery.getJSON(
'http://omdbapi.com', // url
{ // data
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
function (movie) { // success
$('.modal-body').html(`...`);
}
);
While you could munge the query string on to the URL by mashing strings together: Don't. We use libraries to do it because they are less error prone and know all the rules for properly escaping data.

Related

Remake ajax function

Is there a way to make a function that converts default ajax function.
This is the ajax function i have
$.ajax({
type: "POST",
url: "http://" + document.location.host + '/userajax',
data: 'type=register&name=' + name,
beforeSend:function() {
},
success: function(response) {
}
});
This is what i want it to look like
ajax('url', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
},
success: function(transport) {
}
});
Ive tried to search on the internet but did not find anything
Sure, you can create the function like this:
function ajax(url, params){
// everything is now available here
console.log( url ); // output: http://www.google.com
// you can get the data of the params object like this
console.log( params.method ); // output: get
// you can execute the beforeSend like this:
params.beforeSend();
// additionally you might want to check everything.
// maybe if the method is NOT set, you want it to always use GET
switch(arguments.length) {
case 1: url = throw new Error('Url should be set');
case 2: params.method = 'get';
case 3: break;
default: throw new Error('illegal argument count')
}
}
You would call this like:
ajax('http://www.google.com', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
// some function
},
success: function(transport) {
// some function
}
});
This certainly is possible, it's just a bit of work. Some of the basics you need:
First of all, you need a good understanding of the XMLHTTPRequest API, you can find more info on that on MDN.
Next, finding out how to do a callback, that is actually quite simple, you can pass an anonymous function reference as an option or attribute for a function. That goes like this:
function doSomething(variable, callback){
variable = variable + ' something'; // just doing something with the variable
callback(variable);
}
// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });
You should get an alert that says 'doing something'.
And finally you should know how to read an object, passed as 'options' in the ajax function. Say you have a function like this:
function foo(url, options){
console.log(url);
console.log(options.method);
console.log(options.parameters.name);
}
// call it like this
foo('https://google.com/', {
method: 'get',
parameters: {
name: 'myName'
}
});
That should log the url, method and parameters in the console.
Now from here, you should have all the pieces to put the puzzle together. Good luck!
I don't think so. but you can do this:
$(document).ready(function(){
var parameters = {
name: $("#name").val(),
desc: $("#desc").val()
};
$.ajax({
url: 'path/to/file',
data : parameters,
beforeSend: beforeSubmit,
dataType: "json",
type : 'POST',
})
.done(function(data) {
})
.fail(function() {
console.log("error");
})
})
Also note I don't set the function for the beforeSend directly in the call, I will create an externe function which gives me more freedom.
so I could do this:
function beforeSubmit(){
if(something !== 'somethingelse'){
return false; //ajax call will stop
}else{
return true; //ajax call
}
}

jquery -ajax not check the boolean value from controller

i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.
result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);

Declare one Ajax Function and fill it with different variables

I'm trying to make my page more efficient by using a separated ".js" file and trying to declare multilple used functions only one time. So I have to declare them in a way, that they caa be used for different situations. For Example passing different data.
Here is my Ajax Function in the "functions.js" file:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
console.log(data);
$(div).html(data);
}
});
}
Here is my Code in my PHP File where I use this function and pass Parameters:
CallAjax('POST', 'about.php', '{ aufid : id }', '#con2');
My Problem is the "data" section. How can I declare it? The way I'm doing it doesn't work.
I don't want to use a new Ajax Function everytime when I need different data... I'm trying to trigger less functions as possible.
If you have any tips to make the page more efficient by trying to use less code, then it would be awesome if you mention them, too! Thank you!
you can do it like this:
var obj = {
aufid: 1
};
CallAjax('POST', 'about.php', obj, '#con2');
I propose js callback:
function CallAjax(type, url, data, div){
$.ajax({
type: type,
url: url,
data: data,
success: function (data) {
callback(data);
}
});
}
var obj = {
id:1
};
CallAjax('POST', 'about.php', obj, function(response){
$(div).html(response); //or other
});
or a more elegant way in promise:
function CallAjax(type, url, data){
return $.ajax({
type: type,
url: url,
data: data,
});
}
var obj = { id: 1 };
var jxhr = CallAjax('POST', 'about.php', obj);
jxhr.done(function(response){
//successful callback goes here...
}).fail(function(response){
//failure callback goes here...
}).always(function(response){
//always callback goes here...
});
: )

jQuery json ajax function

I am having a kind of a weird problem, or maybe I do not understand how js and jQuery is working.
I have a small js that is sending an id and a value using AJAX. After a lot of experimentation I finally found a working solution which is:
$.post('dashboard/xhrDeleteListing', "id=" + id, function() {
alert(1);
});
However, I would like to use json format for the data part of the call. So what I did (to make sure that my JSON is correct) was the following:
var myJSON = {
id: id
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
But this didn't work. First, php server didn't get anything (nothing in $_POST), second, the callback function didn't run (alert(1) was never executed). To my surprise, the following call did create a $_POST['id'] value:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
but again the callback function didn't run. It only run after removal of 'json' datatype argument).
The version of jQuery is v1.11.0.
Can anyone help me to figure out what am I doing wrong?
Regards,
The important point here is when you do this like:
$.post('dashboard/xhrDeleteListing', {'id': id}, function(z) {
alert(1);
}, 'json');
the 'json' paramter is the dataType of data expected from the server, not from you to send.
It means in your backend after doing your server side task you have to return a valid json string but it seems you want to do a server action without any return value, that's why you have to remove 'json' from your arguments.
var myJSON = {
"id": "id"
};
$.post('dashboard/xhrDeleteListing', JSON.stringify(myJSON), function() {
alert(1);
}, 'json');
Try this :
$.ajax({
url: 'dashboard/xhrDeleteListing',
type : 'POST',
dataType : 'json',
data: {
'id':id,
},
success : function(callback_record) {
alert(callback_record);
}
});

Return data for first key stroke undefined in jQuery autocomplete

I am trying to implement jQuery autocomplete using the approach illustrated below (i.e. a separate source function and an intermediary variable for the data). Right now I'm trying to get the data to the source part of the autoComplete function.
The code below works with one fatal issue, the very first key stroke returns an undefined returnData variable. Can any one explain what's going on?
var returnData;
function sourceFn() {
return $.ajax({
url: //REST URL,
dataType: "jsonp",
async: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
returnData = data;
},
})
}
}
$("input#search-input").bind("autocompleteselect", jQuery.proxy(function (event, ui) {}, this)).autocomplete({
appendTo: "#yt-result-list",
source: function (request, response) {
sourceFn(request, response).done(alert("returnData: " + JSON.stringify(returnData)));
}
}).data("autocomplete")._renderItem = jQuery.proxy(function (ul, item) {
alert(item);
}, this)
});
});
});
Try specifing the minLength: 0 when initializing the autocomplete, check the value of returnData to see if you get the json back from the server (use firebug).
Looks like you're not getting from the ajax call with one letter only, the autocomplete is triggering sourceFn() correctly.

Categories