Saving data in CakePHP, and posting JSON via AJAX simultaneously? - javascript

So I have a form, AND I have a KnockoutJs app, with a CakePHP back end. When I hit Cake's default "save" button, I'm wanting to spit out and post a JSON along with the standard form data.
Here's what I have in my JS so far:
$('input.saveProgram').click(function() {
var theJson = ko.mapping.toJSON(pvm, mapping);
$.ajax({
url: 'http://localhost/cake/programs/edit',
dataType: 'json',
type: 'POST',
data: theJson
});
});
In Cake, I'm trying to use the the Request handler in my controller, but to no avail:
if($this->RequestHandler->setContent('json', 'application/json')) {
// standard saving code
}
In my Cake app I've tried die($this->request->data) to see what's going on and the JSON doesn't seem to be posting at all.

Here's a solution as I interpret your question. In your controller:
if($this->RequestHandler->isAjax()){
// "spit" out json
echo $this->data;
//decode data into an array
$decodedData = json_decode($this->data);
//standard saving code would
$this->Model->save($decodedData);
}

Related

Datatable.js + POSTing data PHP

I'm trying to setup my datatable to POST to the contents of it's rows into my PHP script so that I can store it in a database.
I have a working HTML page, which when I click "+ Add Mapping" a BS modal appears and I can add a row to the datatable.
<script>
$(document).ready(function() {
var t = $('#parameters_config').DataTable();
$('#add_new_mapping').on('click', function() {
$('#add_field_mapping').modal('hide');
var wb_field = $("#add_field_mapping #wb_field").val();
var adobe_field = $("#add_field_mapping #adobe_field").val();
t.row.add([
adobe_field,
wb_field,
]).draw();
$('#add_new_field_mapping').trigger("reset");
});
});
</script>
This all works perfectly. I now would like to retrieve all data rows and POST them to my script so that I can process the submitted data and store. So far, I've come up with this based on information provided:
<script>
$(document).ready(function() {
$('#parameters').submit(function(event) {
var table = $('#parameters_config').DataTable();
var dataToSend = table
.rows()
.data();
console.log( 'Data', dataToSend);
alert( 'There are '+dataToSend.length+' row(s) of data in this table');
$.ajax({
type: 'POST',
url: '{$this->homeURL}',
data: dataToSend,
dataType: 'json',
});
});
});
</script>
In my console window I see the following returned for "dataToSend" but no actual data!
[Array[2], context: Array[1], selector: Object, ajax: Object]
Where am I going wrong?
Where the examples went wrong
The two examples you linked in your post aren't really related to what you're trying to do (from what I can gather about your goal).
The first example is about how to obtain data from the server with a POST instead of the default GET, and has nothing to do with sending data to the server for some purpose.
The second example is about serverside processing, which is where you have pagination, ordering, sorting, filtering, and all other DataTables features handled in your own server code where you then send the results to the client (which is pretty complicated and unless you have a huge number of rows, unnecessary).
Therefore, remove serverSide: true!
Your Goal
What you actually want to do (I think) is send your data to a php script so that you can do something with it. This is not handled by any DataTables API call, but is a fairly simple feature to implement. All you really need is a function that will make an AJAX call that will send the data to the script.
Solution
The way you can do this is by obtaining the data with the t.data() API call, and then sending it with an ajax request. It might look like this:
function sendData(){
var dataToSend = t.data();
$.ajax({
type: 'POST',
url: 'URL OF SCRIPT HERE',
data: dataToSend
});
}
Then you simply have to call sendData() whenever it is that you want to send the data. Of course, you'll have to ensure that your controller handles the data correctly, but that's a different matter entirely.

Correct jQuery syntax for doing a $.post with a header (ASP.NET MVC)

I'm working on a ASP.NET MVC project that uses some jQuery on the client side. I have a jQuery call like this, which works correctly:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
I want to do the exact same call, except I also want to send in a custom header. I am able to successfully create and send a custom header like this:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: "/report_observation/" + submitType,
cache: false,
type: "POST",
data: {
'viewModel': $('form').serialize(),
},
headers: headers,
success: function (data) {
// Deal with the data that came back from the ASP.NET MVC controller
},
error: function (response) {
alert("Error: " + response);
}
});
There are two problems with this second bit of code. One is that I have to make a custom url to go to the correct controller, and I don't know of a way to simply use $('form').attr("action") to automatically go to the correct place.
The second -- and bigger -- problem is that I'm not able to pass over the form data with $('form').serialize() as I could in the one liner $.post example. Doing a #Html.Raw(Json.Encode(Model)) in my Razor cshtml file doesn't send over the model for the whole form, presumably because this code is within a partial view that doesn't know the state of the models in the other partial views that make up this form.
Anyway, I'm thinking there must be an easy way to take this code...
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
...and incorporate the headers property into this bit of code:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
However, I can't figure out the correct syntax. Any ideas?
OK, I figured it out. The second example can indeed work if the data field looks like this:
data: $("form").serialize(),
In other words, I had to NOT assign it to the viewModel parameter.
yes, for the second problem use that dev5000 says, and, for the URL, simply get the value for the attribute action fo the form and use it:
var url = $("from").attr("action");
$.ajax({
url: url,
...
})

Retrieving PHP JSON data through AJAX - correct structure of data request

I have a PHP file called terminal_tester.php which runs a number of terminal actions and creates json data at the end using
echo json_encode($jsonData);
The data looks like this
{"source":"Betting Tips","published":"2015-05-20 15:20:22;","status":true,"eventIDs":["27448131","27448900"],"TipsTB":"TIP 1 MLADENOVIC TO BEAT RISKE\",\"TIP 2 DOLGOPOLOV TO BEAT GULBIS\"]","TipsTW":"[]"}
I now want to populate my HTML file with this data, but am having trouble understanding the correct format for the Ajax data input. I am trying the below in the script area of my html file
function callbackData(){
return $.ajax({
dataType: 'JSON',
url: 'terminal_tester.php',
type: 'GET',
cache: false,
data: jsonData
});
};
callbackData().success(function (data) {
document.getElementById("phpReturn2").innerHTML = jsonData
document.getElementById("phpReturn3").innerHTML = eventIds
document.getElementById("phpReturn4").innerHTML = published
});
but I'm not getting any response. I've searched and I think the problem lies in the data: area of the ajax request but am also confused by the need of a GET command in the PHP file. Could somebody explain how to correctly structure the ajax request?
EDIT
terminal_tester.php has quite a few functions which come together at the end to build the json data, the final part of the php file looks like this
$jsonData = createJson($eventIds, $TipsTB, $TipsTW, $status);
echo json_encode($jsonData);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsonData));
fclose($fp);
First, I think your json data is incorrect. It should be like this-
{"source":"Betting Tips","published":"2015-05-20 15:20:22","status":true,"eventIDs":["27448131","27448900"],"TipsTB":["TIP 1 MLADENOVIC TO BEAT RISKE","TIP 2 DOLGOPOLOV TO BEAT GULBIS"],"TipsTW":"[]"}
Second, normal jquery ajax syntax is -
$.ajax({
dataType: 'JSON', //This means data which come back from terminal_tester.php should be in json format.
url: 'terminal_tester.php',
type: 'GET', // If you are using get request then you should get data by $_GET[]
cache: false,
data: {"jsonData":jsonData}, // Edited this from your code.
success:function(data){ //This data is coming from terminal_tester.php
alert(data.result);
}
});
In terminal_tester.php, it should be like this-
if(isset($_GET['jsonData'])){
$jsonData = $_GET['jsonData']; // GET array (Edited)
// your operation with $jsonData
// In the end, below json will be get in success data.
echo json_encode(array('result'=>true));
}
Hope this helps you!!
$.ajax().success() has a data parameter for accessing the data sent back from your GET request. eventIds and published are both properties of data.
callBackData().success(function (data) {
document.getElementById("phpReturn2").innerHTML = jsonData;
document.getElementById("phpReturn3").innerHTML = data.eventIds;
document.getElementById("phpReturn4").innerHTML = data.published;
});

Trouble with posting jQuery to JSON

I am trying to write a script that allows posting to a JSON file. For some reason the process is succeeding, but the JSON file isn't being written to.
Here is my jQuery code:
$(function() {
var data = {
name: 'cool',
drink: 'cool2',
};
$.ajax({
type: "POST",
url: '/api/orders',
dataType: 'json',
async: false,
data: JSON.stringify(data),
success: function() {
alert("Thanks!");
}
})
});
Here is my JSON code (/api/orders)
[
{"id":1,"name":"Ben","drink":"Americano w/ Creme"},
{"id":2,"name":"Ben2","drink":"Americano w/ Creme2"},
{"id":3,"name":"Ben3","drink":"Americano w/ Creme3"}
]
I can't figure out why Chrome is saying it is succeeding, but the code isn't posting to the JSON file.
The problem isn't with your JavaScript. The JSON.stringify just concerts the data to a JSON string and passes it to the url. Your problem will be in the Url that it is posted to /Ali/orders. That looks like a directory to me instead of an API to handle the string. I could be wrong in that as certain technologies hide that stuff. Still you need to look at where the data is going to.

Save form data into local json file using jquery

I have a basic form with some input fields. I want to save the form data into a json file on submitting the form.
The format of the saved data in the json file should be like this.
[
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"}
]
I tried doing this by using this code, but no data is saved in my 'story.json file'
$('form').submit(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'story.json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
},
failure: function (data) {
alert('Please try again');
}
});
});
I want to save this form data on my local file.
Please help me to find the correct way of doing this. Thanks
You need to post data to a simple php file...
like url: 'story.php'
In that php file create a 'story.json' using fopen and store that json
EDIT: if you want to use serialize() than use someting like this
data:{'mydata':$(this).serialize()}
and in php file
parse_str($_POST['mydata'],$newarray) ;
echo json_encode($newarray);
JavaScript cannot save to a file unless it's a FireFox plugin.
What you do is post a form (sent it to the webserver) then let server side script handle it.
Serialize does not turn the form values into a JSON string:
http://api.jquery.com/serialize/
And when you use $.post then you have to return false in the $('form').submit(function() or the browser will submit the form for you.
Submitting a form is when you click a button and the whole page goes white for a moment and then you get a new page.
Ajax ($.post, $.get, $.getJson ...) is when you send information to the server without refreshing the page. Google maps is an excellent example.
Calling the serialize method on the form jQuery object does not return a JSON representation of its data. It returns a querystring representation of its data. As has been mentioned above, you will need to use a server side script to interpret (and manipulate) sent data and store it in a file as JSON.

Categories

Resources