jQuery AJAX POST Send Variable - javascript

I have the following code:
var result = confirm("You want to Subscribe to our Newsletter?");
var emailAddress = $("#subscribeEmail").val();
if (result == true) {
$.ajax({
type: 'POST',
url: '/php/subscribeNewsletter.php',
data: '{"email": "' + emailAddress + '"}',
complete: function(r){
alert(r.responseText);
}
});
}
I believe the problem is to do with:
data: '{"email": "' + emailAddress + '"}',
I am receiving an empty $_POST array on the server side of things.

Pass an object literal, not a string:
data: {email: emailAddress },
jQuery will transform the object into the URL encoded key/value pairs, which will be picked up in the $_POST array on the PHP side.
Your current code is actually sending a JSON string as the raw POST data. jQuery is seeing the data type is a string, and so it doesn't do any processing, so you'd have to access the raw POST data on the PHP side and do a JSON decode to get it.

yes problem is: data: '{"email": "' + emailAddress + '"}', it should be object:
...
data: {"email": emailAddress},
...

provide the data attribute in the ajax call as a json object instead of string.
like
data: {"email": emailAddress },

You can use like below
$.get('/Presentation/AjaxData/History.aspx', { itemID: itemid }, function (data) {
$('.history-listing-tabs>.tab-item').html(data);
});

Try this format
data: {email: emailAddress}

Better pass data to a variable and use it while sending,
var temp = 'email:' + emailAddress;
...
data: temp;
.....

Related

Not able to get value from JSON object using AJAX call

I have sample code for getting json value from servlet through Ajax call.
In success function I am getting response. It is showing Object : [{"userId":"dfeterter"}] in console.
But I am not able to get value of userId
$.ajax({
url: "Registration",
dataType: "json",
data: {
jsonbhvalue: bhvalue,
jsonuid: uid,
jsonpassword: password,
jsonfname: fname,
jsonlname: lname,
jsonmobile: mobile,
jsonemailid: emailid
},
success: function(variable) {
var obj = $.parseJSON(JSON.stringify(variable));
console.log("Object : " + obj);
console.log("cval : " + obj.userId)
});
});
Thanks To #RobertoNovelo.
You have to remove $.parseJSON as you are already setting JSON by ajax configuration. dataType: "json"
You need to use:
obj[0].userId
Your response is array of objects.
That is because your object is an array. You should either use obj[0] or assign the array to a variable and then use its members
objs = [{"userId":"dfeterter"}]
firstobj = objs[0]
console.log("Object : " + objs);
console.log("cval : " + objs[0].userId);
console.log("cval : " + firstobj.userId);

Save value in Javascript variable from $.get and use it in PHP variable

I am getting some basic info of the visitor on my site using javascript.
var userinfo = "";
//printing user info
$.get("http://ipinfo.io", function (response) {
alert("IP: " + response.ip);
alert("Location: " + response.city + ", " + response.region);
alert(JSON.stringify(response, null, 4));
userinfo = (JSON.stringify(response,null,4)); //saving json in js variable (not working, it says undefined)
}, "jsonp");
Then I want to access this value in my PHP variable:
<?php
echo $getuserinfo ; // How to store JS var here in this php var?
?>
The JS variable value is not being saved, what I am doing wrong?
And how can I store JS variable value in PHP variable?
You could make a stat page/api that you make a ajax call to from javascript.
$.ajax({
type: "POST",
url: '/setstats.php',
data: {userdata: userinfo},
success: function(){
console.log("Userdata send");
},
dataType: "json"
});
This will first be avalible at a later time then when the page initally loads, but you could now have it saved in the session for the next requests.
You are using jQuery.get method.
This method support a parameter called Data
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
After it is sent to the server to http://ipinfo.io it is available in the called script (index.php or what you have as default) in the $_GET array.
If you send data: {var1: value1, var2: value2} you will have $_GET["var1"] and $_GET["var2"]
Simply send data: userinfo and in php do a var_dump($_GET) and check what you got
I solved it by using the PHP version of the API:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
//echo $ip;
return $details;
}
$details = ip_details($userIp);

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

Ajax post - POST array is returning empty on server side

I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.

Parsing json in jquery

I have a php file somejson.php that echos a json encoded array
{"jsonone":"first json","jsontwo":"second json"}
I'm trying to access the response with jquery ajax to use this data outside the score of the ajax call. It keeps giving me all kinds of object(Object) or undefined errors.
I'm guessing it's something as easy as wrong syntax, but it's bugging me I thought I'd ask
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata[jsonone] = json.jsonone;
mydata[jsontwo] = json.jsontwo;
alert(json[jsonone] . json[jsontwo]);
alert(mydata[jsontwo] . mydata[jsontwo]);
}
});
//later will do some stuff with mydata jsonone and jsontwo
What are all the things I'm doing wrong here?
Yep, simple syntax errors :-)
You need to put quotes around your hash keys and use the '+' operator to concatenate strings:
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata['jsonone'] = json.jsonone;
mydata['jsontwo'] = json.jsontwo;
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
}
});
I think your problem comes from the dots in your alert statements.
String concatenation in javascript is done using + not . like in php.
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
Also, the array indexes should be strings (enclose in single or double quotes).

Categories

Resources