Jquery send Json data not working - javascript

I want to sent some JSON data with ajax this is my script
$(document).ready(function () {
jsonObj = [];
$('.img-bg').map(function () {
var self = this;
var next = $(this).nextAll('.rectangle');
if (next.length > 0) {
next.map(function () {
item = {};
item.src = self.src;
item.left = $(this).css('left');
item.height = $(this).css('height');
jsonObj.push(item);
});
}
});
var data={ "firstName" : "Ray" };
jsonString = JSON.stringify(jsonObj);
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: jsonString,
success: function(response) {
console.log(response);
}
});
});
</script>
And jsonObj gives
[Object, Object, Object]
0: Object
height: "341px"
left: "10px"
src: "http://localhost/docAuto/test.jpg"
__proto__: Object
1: Object
height: "321px"
left: "54px"
src: "http://localhost/docAuto/image.jpg"
Output of jsonString
[{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}]
Both var is not send, but if I send data it's working. My Json file is wrong?

You need to pass the options to data as an object. Here's a fixed $.ajax call:
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonString },
success: function(response) {
console.log(response);
}
});
Your testajax.php should now see the jsonString in URL variable json.
edit: fixed my response. I misread your code due to the problems with indentation.

You don't need to use JSON.stringify to send a json object via the jQuery $.ajax() method... jQuery will take care of that conversion behind the scenes. Just use jsonObj as your data parameter.

You need to use POST in upper case.

I think your JSON is missing the key part. When I added the key: 'first', it worked. You got one mighty Json Array there:
JSON.stringify({ first: [{"src":"http://localhost/docAuto/test.jpg","left":"10px","height":"341px"},
{"src":"http://localhost/docAuto/image.jpg","left":"54px","height":"321px"},
{"src":"http://localhost/docAuto/image.jpg","left":"43px","height":"295px"}] })
JSFiddle link http://jsfiddle.net/jyrkim/suvG7/1/
Json Arrays, syntax etc link

Related

Pass map array to a PHP page

For my project, I'm using this:
var arr = new Map(); to create a map with JS.
After each click on elements, I'm using this to populate the map.
arr.set(roomid + '_' + date, {
status: updatedStatus,
date: date,
roomid: roomid
});
After few clicks, on the console panel, I have:
[Log] Map {"48_2019-03-09" => {status: "Open", date: "2019-03-09", roomid: 48}, "48_2019-03-19" => {status: "Open", date: "2019-03-19", roomid: 48}} (2) (app.js, line 93)
So, this is what I want.
Now I need to pass this datas to PHP via Ajax like this:
$.ajax({
type: 'POST',
data: { datas: arr },
url : 'update.php',
success: function(responseText){
...
}
});
On my PHP page, I have the following code:
$arr = $_POST;
print_r($arr);
But this code output:
Array
(
)
But this doesn't work because my PHP page print an empty array.
What I'm doing wrong please ?
Thanks.
you need to convert the map to a json object. Easiest way I know to do this is to stringify and then parse to a JSON object.
JSON.parse(JSON.stringify([...arr]))
$.ajax({
type: 'POST',
data: { datas: JSON.parse(JSON.stringify([...arr])) },
url : 'update.php',
success: function(responseText){
...
}
});
Ref: http://2ality.com/2015/08/es6-map-json.html
Ajax expects an object, not a Map. So you need to convert your Map to an object before passing it to the ajax request.
function mapToObject(map) {
var obj= {}
map.forEach(function(value, key) {
obj[key] = value
}
return obj
}
....
$.ajax({
type: 'POST',
data: { datas: mapToObject(arr) },
url : 'update.php',
success: function(responseText){
...
}
});
EDIT: just noticed, if you need to pass a full JS object to PHP you need to convert it to JSON.
So the real ajax call should be:
$.ajax({
type: 'POST',
data: JSON.stringify({ datas: mapToObject(arr) }),
url : 'update.php',
success: function(responseText){
...
}
});
and on your server:
$data = file_get_contents("php://input");
print_r(json_decode($data, true));

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

Parse a json reply from a jquery result in php

I have a simple search form which query an external server for result with jquery
$("#formsearch").on("submit", function (event) {
// everything looks good!
event.preventDefault();
submitFormSearch();
});
function submitFormSearch(){
// Initiate Variables With Form Content
var searchinput = $("#searchinput").val();
$.ajax({
type: "GET",
url: "https://external-server/api/",
headers: {"Authorization": "xxxxxxxxxxxxxx"},
data: "action=Search&query="+searchinput,
success:function(json){
console.log(json);
$.ajax({
type: "POST",
url:'search_func.php',
data: "func=parse&json="+json,
success:function(data) {
console.log(data);
$('#risultato_ricerca').html(data);
}
});
}
});
}
The first GET ajax works properly and I get correct data but trying to send this json data to my php script in post I can't get data.
This is the code in search_func.php
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'parse':
parse($_POST['json']);
break;
default:
break;
}
}
function parse($json) {
$obj = json_decode($json,true);
var_dump($obj);
}
... it displays NULL
Where I'm wrong ?
EDIT:
SOLVED
changing:
data: "func=parse&json="+json,
to:
data: { func: 'parse', json: JSON.stringify(json) },
json code is correctly passed to search_func.php
Changed function parse in php file to:
function parse($json) {
$data = json_decode(stripslashes($json),true);
print_r($data);
}
Thank you.
Is the javascript json variable correctly filled (i.e. what does your console show you?) Possible you must encode the json variable to a string before posting.
i.e: instead of data: "func=parse&json="+json, use data: "func=parse&json="+JSON.stringify(json),
See this: http://api.jquery.com/jquery.ajax/
The correct syntax is: data: { func: 'parse', json: my_json_here }
If this doesn't works is probably that you have to encode the JSON to a string (see JSON.stringify())

Parse Json data in Jquery

I am new to Jquery, Ajax and JSON.
I am facing issue with the parsing of Json data.
I have been through many questions on stackoverflow
Parsing JSON objects for HTML table
Access / process (nested) objects, arrays or JSON
Parse JSON in JavaScript?
How could I parse through this JSON object in JQuery?
and many more...
Still I am not able to parse the Json data.
My Jquery Looks like :
$.ajax({
/* type : "POST", */
url : "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data : "processDateInput="+processDate,
dataType : "json",
async: true,
success : function(result) {
var od = JSON.stringify(result) ;
var obj = JSON.parse(od);
console.log(obj.od);
console.log(obj.od.percentageCompleted);
console.log(od);
$.each(JSON.parse(od), function(idx, obj) {
console.log(obj.tagName);
});
}
});
I have tried all the combinations to parse this data, but the js console print as "undefined"
I am able to print the json object as :
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"10/11/2014",
"11/11/2014",
"12/11/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"remainingTime": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
Please help me how can I fetch dateProcessed array and percentage complete.
Try this code.
$.ajax({
/* type : "POST", */
url: "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data: "processDateInput=" + processDate,
dataType: "json",
async: true,
success: function (result) {
var od = JSON.stringify(result);
var obj = JSON.parse(od);
$.each(obj, function (index, value) {
console.log(obj[index][0].percentageCompleted);
console.log(obj[index][0].processRunning);
console.log(obj[index][0].remainingTime);
console.log(obj[index][0].successBatchCount);
console.log(obj[index][0].totalBatchCount);
console.log(obj.processDateInput);
$.each(obj[index][0].dateProcessed, function (ind, val) {
console.log(val);
})
});
}
});
When you specify the dataType as JSON, jQuery will automatically parse it for you. Parsing it again as you are (multiple times, even) will cause issues. Try this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
}
I'm not entirely sure what your $.each loop is trying to do as there is no tagName property in your object.
What is the is the return data of your AJAX call
is like this then
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"09/12/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
you can parse it like this
var json = JSON.parse(result);
var od = json['od'];
var processDateInput = json['processDateInput'];
$.each(od, function(index, value){
console.log(value, index);
});
hope it would work on you.
no need of parsing it because you have already mentioned it as json you can simply do like this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
console.log(od);
$.each(result, function(idx, obj) {
console.log(obj[0].dateProcessed);
});
}

Convert data attrs to get/post data

How do I convert data attributes to valid post (or get) data?
$('#nav').find('a').click(function(){
var params = $(this).data();
$.get({
type: "get",
url: "/view/",
data: params
});
})
I get this error:
POST http://127.0.0.1/Site1/%5Bobject%20Object%5D/ 404 (NOT FOUND)
You can use jQuery.param(),
$('#nav').find('a').click(function(){
var params = $(this).data();
params = $.param(params);
$.ajax({
type: "GET"
url: "/view/",
data: params
});
})
EDIT:
Actually the problem is you're using $.get() method like $.ajax().
$.get() doesn't accepts ajax settings object. Change it to $.ajax() than you don't need to use params.
jsFiddle DEMO
I think this should work:
$('#nav').find('a').click(function(){
var params = $(this).data();
$.get("/view/",params,function(){
//success callback
});
})
Without seeing the html it makes answering this more difficult but try something like this. $.post('YourUrl', { paramName : $("elementID").val(), paramName2 : $("#elementId").attr("data")}, function(data){ DoSuccessHere });
The jQuery get function takes an object for its data parameter, i.e.
$('#nav').find('a').click(function(){
var params = {
param1: 'foo',
param2: 'bar';
}
$.get({
type: 'get',
url: '/view/',
data: params
});
});
You can assign multiple values from multiple data sources in this way, e.g.
var params = {
id: $(this).id(),
name: $(this).attr('name');
}

Categories