I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.
Related
I am working in php codeigniter and I tried like this in my code.
var dataSource = $.ajax({
url: <?php echo $url=$this->BASE_URL."home/destination_place" ?>,
method: "POST",
data: { id : id,firstName:firstName },
dataType: "html"
});
This is my returning array but it is not getting in the data source field
[{"id":"1","firstName":"dubai"},{"id":"2","firstName":"munnar"},{"id":"3","firstName":"wayanad"},{"id":"4","firstName":"kovalam"}]
I hope somebody will help me to solve this.
hopefully
I tend not to use .ajax because it's bulky and messy. The .get() and .post() methods work well and are nice and clean.
var dataSource = '';
$.post('<?= $this->BASE_URL.'home/destination_place' ?>',
{ id: id, firstName: firstName },
function(resp){ dataSource = resp; });
The third argument is the callback function, which takes the response as a function parameter. You can then assign it to a variable outside the callback.
Something to bear in mind is that AJAX is asynchronous. The response value will not be available until the call to the remote machine completes. For this reason, all data processing should be triggered inside the callback function, where in this case we are assigning resp to dataSource.
dataType parameter is the type of data you're expecting to get from server.
If I undearstand correctly, you want to get JSON from server, but u specified dataType as html. Try:
var dataSource = $.ajax({
url: <?php echo $url=$this->BASE_URL."home/destination_place" ?>,
method: "POST",
dataType: "json",
data: { id : id,firstName:firstName },
});
My url parameter need to included the query string due to the system need to pass the token everytime request a link. I would like to use ajax POST to my PHP page.
Below is my ajax code:-
var data = new Array();
data[0] = $('#coupon_code').val();
data[1] = $('#coupon_value').val();
var jsondata = {"data": data}
var json = JSON.stringify(jsondata);
$.ajax({
url:"index.php?route=coupon/create&token=csrf1234567",
cache:false,
processData: false,
type: 'post',
dataType: 'json',
contentType: 'application/json',
data:{json},
success:function(){}
});
However, my PHP script is like below to make sure I have everything passed to server side:
public function create()
{
var_dump($_REQUEST);
}
It only have following output:-
array(2) {
["route"]=>
string(13) "coupon/create"
["token"]=>
string(11) "csrf1234567"
}
Inside the chrome insepct it shows
**Query String Paramaters**
route:coupon/create
token:csrf1234567
**Request Payload**
[object Object]
It does not have POST variable to pass to my PHP. I want to use type POST, and json to accomplish this, any idea how to solve it?
SOLVED:
data:{json},
change to
data:json,
Thanks for the solution!
SOLVED:
data:{json},
change to
data:json,
Thanks for guest271314!
So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()
I've been struggling with converting an Array of objects to JSON, or any other PHP readable format so I can send it over AJAX.
I'm using localStorage and I save an object into it, I save it using
JSON.stringify(data)
Now when I loop through all the localStorage data, I add it to an array using the following code
var locations = new Array();
for(var i = 0; i < localStorage.length; i++){
locations[i] = JSON.parse(localStorage.getItem(localStorage.key(i)));
}
The end result looks like this.
This is my $.ajax request
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: locations,
success: function(data) {
console.log(data);
}
});
The only problem is that I can't seem to convert it to a readable format to send to PHP
Any clues? Thanks!
Make your post data an object.
$.ajax({
type: "POST",
url: "store.php",
dataType: "json",
data: {location: locations},
success: function(data) {
console.log(data);
}
});
Then on your PHP: print($_POST['location']);
You can also simplify like this.
$.post('store.php', {location: locations}, function(data) {
console.log(data);
});
You should also be able to pass the content directly from localStorage -- no need to build an array from it.
Data formed with JSON.stringify() can be sent through $.ajax and interpreted by PHP.
You can use PHP's input stream to read your data:
$json = file_get_contents('php://input');
$array = json_decode($json);
For more info on PHP's I/O streams, see http://php.net/manual/en/wrappers.php.php
I'm trying to send data from Entity Framework database to js script on my webpage. This is my MVC Controller:
public ActionResult Index()
{
var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0
ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));
var test = ViewBag.wordsToShow;
return View();
}
And in index.cshtml I've put this code:
<script>
var wordsJson = "#ViewBag.wordsToShow.ToString()";
var wordsAsObject = JSON.parse(wordsJson);
</script>
The problem is, javascript says:
Invalid character
In the line where I'm parsing json to javascript object. The reason is: json string doesn't look like it should. This is part of what's inside "wordsJson" variable in web browser:
What can I do to make it work?
You're going about in an overly roundabout way. JSON is called "JavaScript Object Notation" for a reason. There's no need to put it in a string and re-parse it. You can just use the JSON as JavaScript.
ASP.NET MVC has a helper for serializing values as JSON, so you can just use that and assign it to a variable in your JavaScript:
<script>
var wordsAsObject = #Html.Raw(Json.Encode(ViewBag.wordsToShow));
</script>
This would eliminate the need to do the JSON serialization within your Action.
I suspect that the reason you're encountering this issue is that by default, values inserted into a view with # are automatically HTML encoded. You can use Html.Raw() to prevent this, as I've done above, but as I said, there's no reason to put it into a string first and parse it.
I always create Method that return JsonResult/string
like:
public string GetData()
{
//your logic here
string json_sales = JsonConvert.SerializeObject(<<your data>>);
return json_sales;
}
and in JavaScript I just do AJAX request:
$.ajax({
url: 'PUT_YOUR_URL_HERE_To_METHOD_GetData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Make: maka.value }),
async: true, // Or false
cache: false,
success: function (data) {
//do something
}
},
error: function (xhr) {
alert('error');
}
})