JQuery.ajax(): Issue with parameter data when consuming a WCF Service - javascript

I'm using JQuery to consume a WCF Service. Actually this works fine:
var para = ' { "Parameter" : { "ID" : "5", "Name" : "Peter" } }'
$.ajax({
type: "POST",
contentType: "application/json",
data: para,
url: url
success: success
});
But I don't want to pass the data parameter as String and I think it should be possible to pass ist as array in any way. Like that:
var para = { "Parameter" : { "ID" : 5, "Name" : "Peter" } }
But when I try this I'm getting an error. What I'm doing wrong?
Thanks

var para = '{ "ID" : "5", "Name" : "Peter" }';
$.ajax({
type: "POST",
data: para,
url: url
success: success
});
If you format it like this you should be able to get the values as
$_POST will return array('ID' => '5', 'Name' => 'Peter');
but you can also access it by doing:
$_POST['ID'] and $_POST['Name']
Also you could make use of the jquery post function:
var para = '{ "ID" : "5", "Name" : "Peter" }';
$.post(
url,
para
);

You can use JSON.stringify function from the json2.js. Then you ajax call will be
var para = { Parameter : { ID :5, Name : "Peter" } };
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(para),
url: url
success: success
});
The usage of manual conversion to the JSON string is not good because of possible spatial characterless in the string which must be escaped (see http://www.json.org/ for details).

Related

How to pass javascript variable to ajax 'data' attribute

I am tying to pass a javascript variable as an ajax paramater but it is being sent as null. Simply passing 'host' gives 'host' itself which isn't what is desired
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: '{'
hostname '=' + host '}',
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
Try the following:
data: {'hostname' : host},
Pass the data as an object, using key you can access the value of the variable on the server side.
USE:
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: {
"hostname": host
},
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
If you are trying to send data as a string make use of JSON.stringify()
dataToSend = JSON.stringify({ "hostname": host });
And in your AJAX
data : dataToSend
I feel the problem is you have made the wrong JSON data format.
the correct JSON format should be like this:{key:value}
Give an eg. here:
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
ex:the employee contains 3 elements
Wish can make some help :)

UNDEFINED - multiple return values from PHP with jQuery AJAX

Because I get undefined. Where I am failing?
Code:
function add(id,cost){
var info = {
"id" : id,
"cost": cost,
};
$.ajax({
data: info,
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});
}
archive a.php
PHP:
$cost=$_POST['id']*$_POST['cost'] + 137;
echo json_encode(array("r1" =>$_POST['id'], "r2" => $cost));
Why do you think $.ajax will understand datos as a JSON? You need to specify it, you can do it using several ways.
Parsing it
success: function (datos) {
datos = JSON.parse(datos);
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
Specifying in $.ajax itself
$.ajax({
data: info,
url: 'a.php',
type: 'post',
dataType:"json",
....
Setting header in PHP (doesn't work for < IE8)
header('Content-Type: application/json');
I would suggest you to use a combination of first one and third one. Lets not leave any stone unturned.
Datos is probably a string
You can do:
datos = JSON.parse( datos );
Or, you can set the return type to JSON:
$.ajax({
data: info,
dataType: 'json',
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});

Jquery ajax url eval

I have to fire an ajax call against two different domain based on the platform of the client (mobile/desktop):
var baseDomain = (isMobile()) ? "http://m.test.com" : "http://www.test.com";
function AddProduct(ProductId, ButtonClientId) {
$.ajax({
type : "POST",
eval("url : \""+baseDomain+"/data/call.aspx/AddToShoppingCart\",");
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
}
I cannot go thru this as I always get the "SyntaxError: missing formal parameter". Where I'm wrong?
Try this:
$.ajax({
type : "POST",
url : baseDomain + "/data/call.aspx/AddToShoppingCart",
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
The URL is just a string, so create the string you want in a variable and assign it to the url property of the Ajax options:
var baseDomain = isMobile() ? "http://m.test.com" : "http://www.test.com";
function AddProduct(ProductId, ButtonClientId) {
$.ajax({
type : "POST",
url: baseDomain + "/data/call.aspx/AddToShoppingCart",
contentType : "application/json; charset=utf-8",
data : '{productId:' + ProductId + ', quantity: 1, isSingle: true}',
dataType : "json",
success : function(data) {
ProductAddedSuccess(data.d, ButtonClientId);
},
error : ProductAddedError
});
}
The reason for the error is you are placing a function call (to eval()) in the middle of an anonymous object declaration!
e.g.
{
propName1: "Value 1",
someFunctionCall(),
propName2: "Value 3"
}
Which makes no sense to Javascript :)

What is the right way of sending a var on AJAX

I have a javascript function that calls a Webmethod. I tried sending a regular string to the webmethod and it works. On var empid= $('#' + txtId).val() Im getting the right value of the text box. What is the right way of sending empid over ajax ? I have tried a few thing and they dont work. Any help would be appreciated. Thanks
.js
function toggle(txtId, lblname, txtcode) {
var empid = $('#' + txtId ).val();
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{ id: empid }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).html(data.d);
}
});
}
.asmx.vb (webmethod)
Public Function GetEmployeeName(ByVal id As String) As String
Return "It works"
End Function
This is a screen shoot when removing contentType
Instead of
data: '{ id: empid }',
use
data: { id: empid },
Its sending JSON
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
You can use like below:
var empid=$('#txtEmpId').val();
Pass empid in data as
data: { id: empid },
Check out the fiddle here: http://jsfiddle.net/gN6CT/103/

How to pass Javascript array to PHP file using AJAX?

I have to pass a Javascript arry to a PHP file while AJAX call.
Below is my js array:
var myArray = new Array("Saab","Volvo","BMW");
This JS code has to pass JS array to PHP file using AJAX request and will show count of array.
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : myArray},
success: function (data)
{
alert(data);
}
});
}
This myphpfile.php file has to return the count of the array
<?php
$myPHPArray = $_POST["myJSArray"];
echo count($myPHPArray);
?>
There is error in PHP file. I am getting undefined index: myPHPArray. How should acheive my required functionality?
Convert js array in json format by JSON.stringify
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},
success: function (data)
{
alert(data);
}
});
}
And In the PHP use json_decode function to get value in array
json_decode($_POST["myJSArray"]);
Use JSON.stringify to converts a value to JSON and send it to server.
data: JSON.stringify({"id" : 1, "myJSArray" : myArray})
You could use JSON.stringify(array) to encode your array in JavaScript, and then use
$array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.please check this link
Pass Javascript Array -> PHP
What seems to me is that your array is not available in the function scope:
function ProcessAJAXRequest(){
var myArray = new Array("Saab","Volvo","BMW"); // this has to be in fn scope
$.ajax({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)}, // do the stringify before posting
success: function (data){
alert(data);
}
});
}

Categories