Convert JavaScript object to JSON and POST it - javascript

I have to parse my html from and POST it to another script. When I use JSON.stringify to serialize object with parsed data, $_POST array in the receiving script is empty:
$("#addQueryForm").submit(function(event){
event.preventDefault();
result = {}
result['kindArr'];
result['factor'];
$("[rel=my-form]").each(function() {
result[$(this).attr("name")] = $(this).attr("value");
});
var form = JSON.stringify(result);
$.post("add_kind.php", form , function(data) {
alert(data);
//data shows me that $_POST array is empty
});
});
But if I write json string into the query manually, it would be correct:
$.post("add_kind.php", {"kind":"Var1","kindArr":"Var12345","factor":"Var0","synonym1":"Var1","synonym2":"Var2","synonym3":"Var3"} , function(data) {
alert(data);
//data shows me that $_POST contains posted data
});
What am I doing wrong?
P.S: stringify was excess.

Maybe serialize would be better in your situation:
var form = $(this).serialize();
$.post("add_kind.php", form, function(data) {
alert(data);
});

Related

How to loop each JSON value after is retrieving its data through AJAX

var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/

Convert Json encoded data to javascript array and access value by index

I am getting json response from ajax like this
echo json_encode($data);
Ajax code:
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
success:function(ajaxresult)
{
$("#jgoli").html(ajaxresult);
}
});
Result I am getting is:
[{"paymentId":"2","paymentLabNo":"MR-622-040618",paymentTestId":"1"}]
Now I want to access my json array in javascript by index like
ajaxresult[0] = 2; i.e paymentId=2
ajaxresult[1] = 2; i.e paymentLabNo=MR-622-040618
How would I achieve that?
Note: I have tried many examples on stackoverflow, I know this question must have answered earlier. But I am still stuck. Any help would be appreciated.
$(document).ready(function(){
var data = [{"paymentId":"2","paymentLabNo":"MR-622-040618","paymentTestId":"1"}];
//Loop on the object as key=>value
$.each(data, function(key, value){
//And diplay it in the result div
$('#result').append('<p>'+data[key]['paymentId']+'</p>');
$('#result').append('<p>'+data[key]['paymentLabNo']+'</p>');
$('#result').append('<p>'+data[key]['paymentTestId']+'</p>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="result"></div>
What you are getting is a string of encoded JSON, to use it as an object you must parse it.
Check this answer
$(document).ready(function(){
$.get("ajax_call.php", function(data){
//console.log(data);
var result = JSON.parse(data);
$.each(result, function(key, value){
$('#data').append('<tr><td>'+result[key]['username']+'</td><td>'+result[key]['email']+'</td><td>'+result[key]['mobile']+'</td></tr>');
console.log(result[key])
});
});
});
$.ajax({
url:"PaymentSlip/check",
data:{val:val},
type: 'POST',
datatype: "json", // add this
success:function(ajaxresult)
{
// access return results as
//ajaxresult[0].paymentId;
//ajaxresult[0].paymentLabNo;
//ajaxresult[0].paymentTestId;
//$("#jgoli").html(ajaxresult);
}
});

parsing JSON inside of ajax sucess function

I am trying to parse and display this JSON data that gets returned. Basically I have an ajax call which reads an input, sends it via POST to a PHP page and the php page var_dump's the array which contains the data.
array(1) {
[0]=>
string(21) "jsmith#yahoo.com"
}
My AJAX Call looks like..
<script>
function searchDB()
{
var lookupemail = $('#lookupemail').val();
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: {wordpress: lookupemail},
success: function(server_response)
{
var response = server.response.1;
alert(response);
}
});
}
</script>
How do I retrieve the string that is returned and assign it to a javascript variable?
Your PHP code would have to output JSON in the first place:
$array = array('jsmith#yahoo.com');
echo json_encode($array);
To make it into an array in JavaScript you can use
var newArray = $.map(server_response, function(el) { return el; });
However, you can access the JSON directly using the json_encode in PHP.
json_encode($phparray);
and then...
server_response.arraykey

How to access the serialized data in PHP file in the following scenario?

How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories