I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...
Related
HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);
this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.
I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax
I have following code in common.js file.
logic is if HighlightTextBox if data is not matching and RemoveHighlightTextBox if data is matching.
url = /Services/GetAutoCompleteData?v=
name = My & Son
actualUrl = /Service/GetData?v=My & Son&eq=true
//debuge following js code and found above values
//here problem is because of `&` sign url gets disturb as `actualUrl is /Service/GetData?v=My & Son&eq=true`
//so after `&` sign url gets ignore by js (i.e Son&eq=true code)
//i have passes values `My & Son` but actually js parsing it as `My` so how do I parse my original URL with `&` sign ?
var div = $(this).closest("div");
var elem = div.find(":text");
elem.change();
var name = elem.val();
var actualUrl = url + name + "&eq=true"
var filter = $(this).attr("filter");
if (name == "") {
div.find(":hidden").val('');
return;
}
AjaxPostCall(actualUrl, filter, function (data) {
if (data == null || data.length != 1) {
HighlightTextBox(elem);
div.find(":hidden").val('');
return;
}
RemoveHighlightTextBox(elem)
div.find(":hidden").val(data[0].Key);
elem.val(data[0].Value);
});
function AjaxPostCall(actualUrl, extraParam, onSuccess) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: actualUrl,
data: extraParam,
dataType: "json",
success: function (data) { if (onSuccess != null) onSuccess(data); },
error: function (result) { }
});
}
Try this
var actualUrl = encodeURIComponent(url + name + "&eq=true");
encodeURIComponent Thisfunction encodes a URI component.
This function encodes special characters. In addition, it encodes the
following characters: , / ? : # & = + $ #
You need to escape the parameter value with & using method encodeURIComponent() before appending to parameter string.
ex
encodeURIComponent('name = My & Son')
I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:
var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string
I want to echo out the standard string accessing it with
alert(foo.msg)
EDIT: to make the answer more clear here is my call:
var success_msg = "Your email is send successfully!";
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status == "success") {
msg.text(data.msg).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
})
ajax-share-email.php responds:
{"status":"success", "msg":"success_msg"}
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);
or e.g.
var messages = {};
messages.success_msg = "Your email is send successfully!";
// ...
msg.text(messages[data.msg]).addClass("email-msg-success");
How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:
{ "status": true }
or
{ "status": false, "msg": "The mail server is down." }
Then you can just evaluate it as a boolean without comparing it to a string value.
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text('Your email has been sent successfully!').addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
If, and only if, you start reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the functions that use it.
var messages = {};
messages.mail_success = 'Your email has been sent successfully!';
messages.post_success = 'Your data has been updated!';
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text(messages.mail_success).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)
?
IFF I understand what you are asking, I think I have all of the pieces here.
You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined
JSON.parse will not work for you (at least not in Chrome), but eval will.
var predefined = "Hi! I'm predefined";
// ...
var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
var out = eval(foo.msg); // out is now "hello world"
Note: do not use eval() if you are not sure what the content of foo.msg is.
or
var out = foo.msg=="predefined" ? predefined : foo.msg;