How to send array javascript to php? - javascript

I am trying to send an array with ajax to PHP. Could someone please
suggest a way to achieve it ?
My Code :
guardarRuta: function(){
console.log('Guardando ruta...');
for (var i = 0; i < marcadores.length; i++) {
latLngMarcadores.push({'tipo': 'parada', 'latitud': marcadores[i].position.lat(), 'longitud': marcadores[i].position.lng()});
}
latLngOrigenDestino.push({'tipo': origenDestino[0].tipo, 'latitud': origenDestino[0].marker.position.lat(), 'longitud': origenDestino[0].marker.position.lng()});
latLngOrigenDestino.push({'tipo': origenDestino[1].tipo, 'latitud': origenDestino[1].marker.position.lat(), 'longitud': origenDestino[1].marker.position.lng()});
Ext.Ajax.request({
url: 'http://becea.mx/dabbawalas_valeria/adm/save_route_adm.php',
method: 'POST',
params: {
nombre: 'RutaNueva',
data: {"marcas" : JSON.stringify(latLngMarcadores)},
},
reader: {
type: 'json',
rootProperty: 'status'
},
success: function(response) {
//Ext.Viewport.setMasked(false);
Ext.Msg.alert('Listo', 'Ruta guardada con éxito!');
},
failure: function() {
//Ext.Viewport.setMasked(false);
Ext.Msg.alert('ERROR', 'Error de servidor');
}
});
}
<?php
$elements = json_decode($_POST['marcas']);
echo($elements[0]);
?>

First, as pointed by #Burak Öztürk, you must directly send data as is (not using JSON.stringify()), like this:
params: {
nombre: 'RutaNueva',
data: {"marcas" : latLngMarcadores},
},
Then data is an object of objects, not an array.
Currently in PHP you're decoding it with:
$elements = json_decode($_POST['marcas']);
This keeps objects as objects! Instead use:
$elements = json_decode($_POST['marcas'], TRUE);
This way, objects become associative arrays and you can access and iterate them as expected.

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

how to pass array of object in Javascript to C# mvc5 model

is there a way to pass an array of object and then assign it to model?
i searched that making the same variable name in your model and object will do the work but it doesn't work for me.
the model always get null values.
var answers = [];
var answerOthers = [];
var comment = $("#message").val();
$("input:radio:checked").each(function () {
var questno = $(this).attr("data-question");
var ansid = $(this).val();
answers.push({ QUESTIONID: questno, ANSWERID: ansid});
if ($(this).val() == 3)
{
var txtOther = $("#otherTxt-" + $(this).attr("data-question")).val();
answerOthers.push({
QUESTIONID: questno,
ANSWER: txtOther
});
}
});
$.ajax({
url: 'insertQuestions',
data: { answers: answers, answer_others: answerOthers, userid: userid , comment: comment },
method: 'GET',
success: function ()
{
alert("saved");
},
error: function (e)
{
console.log(e);
}
});
c# controller
public void insertQuestions(List<ratingsModel.ANSWERS> answers,
List<ratingsModel.ANSWERS_OTHERS> answer_others, int userid , string comment)
{
insertAnswers(answers,userid);
insertAnswer_others(answer_others, userid);
MySqlConnection myconn2 = new MySqlConnection(cmn.connstring);
myconn2.Open();
string query3 = "INSERT INTO comments (userid,comment) VALUES" +
" (#userid,#comment)";
MySqlCommand cmd2 = new MySqlCommand(query3, myconn2);
cmd2.Parameters.AddWithValue("#userid", userid);
cmd2.Parameters.AddWithValue("#comment", comment);
cmd2.ExecuteNonQuery();
myconn2.Close();
}
You cannot do that with a GET (the data you pass to the method would need to be a query string and to represent your collections you need individual name/value pairs with collection indexers, for example
data { [0].QUESTIONID: xx, [0].ANSWERID: yy [1].QUESTIONID: zz, .... etc }
But it should not be a GET in any case. Your method is changing data so it should be a POST (and in addition, if your collections were large, your would exceed the query string limit and throw an exception)
Change the ajax code to
$.ajax({
url: #Url.Action('insertQuestions'), // dont hard code your url's
data: JSON.stringify({ answers: answers, answer_others: answerOthers, userid: userid, comment: comment }) // modify,
contentType: 'application/json', // add
method: 'POST', // change
success: function() {
....
As a side note, if you had generated your form correctly using the strongly typed HtmlHelper methods, then you code could simply have been
$.ajax({
url: #Url.Action('insertQuestions'),
data: $('form').serialize(),
method: 'POST',
success: function() {
....
and none of the code for generating the arrays would be required.

Jquery send Json data not working

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

Knockout mapping data from ajax post vs Static data

I've encounted a strange problem with Ko mapping.
I use this piece of code:
var PList = [{ "Region": { "RegionName": "SomeRegion" }, "CDetails": {}, "Category": { "Name": "SomeCategory" }, "PSource": 1, "PDate": "0001-01-01T00:00:00"}];
var PViewModel = ko.mapping.fromJS(search('someSearch', 'True'));
var PViewModel2 = ko.mapping.fromJS(PostList);
function search(queryString, isFirst) {
$.ajax({
type: 'POST',
url: 'url',
data: { 'searchQuery': queryString },
dataType: 'json',
success: function (dt) {
if (isFirst != 'True') {
ko.mapping.fromJS(dt, PostsViewModel);
}
return dt;
}
});
};
Strangely I see 2 outcomes:
When I go to PViewModel (the one populated by ajax) I see it as undefined
When I go to PViewModel2 (the one with static data) I can see the objects as expected
*The static data of PViewModel2 is just a copy of the data returned by the ajax post.
My questions are:
Does anyone know why is this so? And how to fix it?
Furthermore, is the if (isFirst != 'True') clause the right way to init the ko view model?
You are dealing with an asynchronous operation (an Ajax request). These operations do not have return values. Therefore, this can never work:
ko.mapping.fromJS(search('someSearch', 'True'));
That's what the success callback is for. Incoming data can only be handled there.
function search(queryString, targetObservable) {
$.ajax({
type: 'POST',
url: 'url',
data: { 'searchQuery': queryString },
dataType: 'json',
success: function (dt) {
ko.mapping.fromJS(dt, targetObservable);
}
});
};
search('someSearch', PostsViewModel);

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>

Categories