How to post this array and print in php? - javascript

How can I send this array back to the server so I can handle it in PHP?
<script>
var myJSONObject = {
"onw": [
{"name": "nilesh", "age": "31", "sal": "4000"},
{"name1": "nitin", "age": "11", "sal": "14000"}]
};
document.write(myJSONObject.join());
</script>

You can use serialization method. i.e serialize the javascript variable and pass it to php, in php file you can deserialize the same.
serializing : Serializing to JSON in jQuery
Ref: http://api.jquery.com/serializeArray/

Never use document.write as its outdated, the preferred way to add elements to DOM is using appendChild
Example Code for appending:
var textNode = document.createTextNode("some text"); // creates new text node
textNode.appendChild(document.body); // adds to the end of the body
For posting data to php by using jquery:
Before sending it to server, you need to format it as String using JSON.stringify
var formattedData = JSON.stringify(myJSONObject )
$.ajax({
type: "POST",
url: "server.php",
data: formattedData ,
dataType: 'json',
success: function () {
alert("Data posted to php and processed succesfully");
}
});

var json_text = JSON.stringify(myJSONObject, null, 2);
alert(json_text);

Related

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())

Value showing undefined when trying to output data returned as json from server

I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name

CodeIgniter and JSON objects: how to push my data to database?

I have a JS file that manages my data (push the data in my JSON objects, etc), and the classic MVC structure of files from CodeIgniter.
My JS contains my JSON objects that I would like to push in my database. How could I do for it? How can I reach the controller and the model from my JS file? I just can't figure out what is the right process to achieve my goal! And I find nothing similar to my question.
EDIT
The data to push into the database is a part of the entire JSON object.The data to push is, for example: { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 }
In my JS file, I have tried this code:
$("#hexa-btn").on("click", function () {
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: JSONshapes.shapes[0].nodes[0],
cache: false,
success:
function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
And my controller has this function:
function returndata(){
$index = $this->input->post('index');
$x = $this->input->post('x');
$y = $this->input->post('y');
$weight = $this->input->post('weight');
$px = $this->input->post('px');
$py = $this->input->post('py');
$fixed = $this->input->post('fixed'); ;
echo json_encode(array('node'=>$node));
}
I am not sure at all about this function. It seems this is the role of the model to do this job, isn'it?
2nd EDIT So, I tried the solution of #Harish Lalwani, but this time with my array of nodes (not only one). I have the following function in the JavaScript file:
function sendNode(){
var node_url = "/prototype/insert_node";
var data_node = JSON.stringify(JSONshapes.shapes[0].nodes);
$.post(node_url, {'node_data': data_node}, function(data){
console.log(data.index);
});
}
and the following one in the controller (thank to this post):
function insert_node(){
$node_data = $this->input->post('node_data');
$node_data = json_decode($node_data,true);
echo 'Your Data: ' . $node_data[0]['index'];
},
But, when printing the data, I get undefined. The variable data_node is the following (so, is an array):
[{"index":0,"x":50,"y":80,"weight":2,"px":50,"py":80,"fixed":0},{"index":1,"x":189,"y":107,"weight":2,"px":189,"py":107},{"index":2,"x":95,"y":145,"weight":2,"px":95,"py":145}]
Now, I don't know anymore what to do! I find really too few examples. Can anyone put me out of my misery? Thank you very much in advance!!
Trigger this from your Js file. (include jQuery Library)
provide url, post key and value you will receive post parameters at specified URL.
jQuery.post("<URL>", {dataname: datavalue}, function( r ) {
console.log(r);
});
I am also using ajax.
From your Original Post, I see that you have a JSON object. If it is already in object form, there's no need for you to convert it at all. Just assign that JSON to a variable and pass that variable to your ajax data parameter like so:
$("#hexa-btn").on("click", function () {
var json = { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 };
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: json,
success: function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
Using ajax can solve your problem!
$.ajax({
type: "POST",
url: "test.php",
data: yourData,
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have m

How to display returned JSON from a jQuery

How to get display return values from the JSON values.I need to get value the user id
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
console.log('success' + data.success);
if (data.success) {
var Value = data.location.user_id;
alert(Value);
}
}
});
});
These values are getting in html form. In that I need to store user id in Value varable. But I receive successundefined as a output..
[{
"user_id": "139",
"mobile": "9042843911",
"gender": "male",
"hashcode": "DfAbMqLApAV6nVa1z940",
"username": "anandhsp21",
"password": "74bcff7d1199012e154f364e3f65e31d:8I",
"authorized_person": "Anandh",
"created": "2015-06-08 13:46:55",
"modified": "2015-06-08 06:43:35",
"logdate": "2015-06-08 08:16:55",
"lognum": "12",
"reload_acl_flag": "0",
"is_active": "1",
"extra": "N;",
"rp_token": null,
"rp_token_created_at": null,
"app_name": "",
"api_key": ""
}]
Please some one help. Thanks in Advance
Your get the data in array so use loop in success data
for (var i=0; i<data.length; i++) {
console.log('success' + data[i].user_id );
}
If you know the record length is 1 then use directly
console.log('success' + data[0].user_id );
Your data is an array that contains one object. So you can access this object using :
success: function(data){
console.log('success' + data[0].user_id );
Trying to log success is pointless, because there is no success key whatsoever in the received data.
Make sure that you get the response in proper json format,and as harshad pointed String male should be wrapped in double quotes.
After you get that fixed,you can access the user_id as:
data[0].user_id
data.success is undefined, because the received data is stored directly in data. That's the first argument of the success block. You can access the received data directly by data[0] to get the object inside of the array, or if you have a larger array you can do a for each loop over it, etc..
Try this, simply use json.parse()
$(document).ready(function() {
var v = ['{"user_id":"139","mobile":"9042843911"}'];
var obj = JSON.parse(v);
alert(obj.user_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get userid please follow below code I edited,
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
// this below userid is the value user_id you want.
var userid = data[0].user_id;
}
});
});
There is a json error
"gender":male
Strings male should be wrapped in double quotes.
you need to make sure that your response is formatted appropriately and according JSON.org standards.

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

Categories