Saving elements to database with $.ajax() - javascript

I'm trying to save dynamically created elements in my application.js file to the database. Would the code look something like this?:
$.ajax({
type: "POST",
data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_url'}
});
Is there anything I'm missing? Assume that oembed.title and oembed.thubnail_url hold the values I want to save, and that title and thumbnail are the database columns.

First problem I see is your data is strings. Get rid of the ' quotes
$.ajax({
type: "POST",
data: { title: oembed.title, thumbnail_url: oembed.thumbnail_url}
});

I'm going to assume you need to incorporate some user-supplied data into the new DB object - otherwise, it would be way easier to just create it from Rails.
If you're using entirely user-supplied data, you can use the serialize() method (use hidden fields for server-generated stuff):
jQuery.ajax({
url: '/path/to/whatever',
data: $('#MyForm').serialize(),
type: 'POST'
});
Or you could use the jQuery Form Plugin - it'll let you easily combine user-supplied data with server-generated data. For example:
$('#MyForm').ajaxForm({
//Hardcoded/server-generated stuff goes in here
//(and will be added to the data from the form inputs):
data: {title: oembed.title},
type: 'POST'
});
The ajaxForm() function will set up the form and its defaults, and sends an AJAX call when the user hits the submit button (see also: ajaxSubmit()).
On the Rails side, everything should work exactly the same as if the user had submitted the form normally (though you might want to just respond with a status code/message - no call for a redirect or page render).
Hope this helps!
PS: From your example, it looks like you might be able to use data: oembed in your AJAX calls. This will submit all oembed's attributes...

Related

PHP doesnt see posted data from ajax by serializeArray()

I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!

Laravel - Ability to filter database using AJAX

This is my first time attempting filtering and searching the mySQL database. From my research I have found out I need an AJAX call and some PHP query that will help my achieve the filtering I want to achieve.
This is what I want the AJAX search to do:
Have an Apply button. When I click the button I want a URL to get generated and the AJAX call to happen.
Only reload part of the page where the data queried is contented.
So far I have managed to create this:
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(data){
$('#data-holder').html(data);
}
});
});
This manages to create the URL one of the filters, but it does not take the other filters into consideration. I also did not manage to create the button. I am guessing you would need a where statement in the PHP to filter the database?
Would anyone be willing to assist me in creating the AJAX call and PHP query for the filters?
In total I have three filters, and when I click a button I want an AJAX call to filter my database with the three filters and return the results without having to reload the whole webpage.
EDIT: Here is my JS AJAX query:
$("#apply").click(function() {
$country=$('#filter-country').val();
$type=$('#filter-type').val();
$year=$('#filter-year').val();
$.ajax({
type: "GET",
url: "{{$launchsitename->site_code}}",
data: {'country':$country, 'type':$type, 'year':$year},
success: function(data) {
$('#data-holder').append(data);
}
});
});
Now I just need to create a PHP query.
you can use propriety called .Append() instead of .html() ,also here you are getting one element value on change , if you want to get the three of them at one button click , you can make it the same way that you got the val of the first one , and just adding it to the request and handle it back in PHP to divide and execute each one or just pass the three of them to your procedure , depends on what you have
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(response){
$('#data-holder').append(response);
}
});
});
Read about .append()

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.

Can I change the instance variable using ajax in rails?

I have used ajax to get the object from controller.
$('#city').on('change',function(){
$.ajax({
url: "/courses/index",
type: "GET",
data: {city: $('#city').val() },
success: function(responseData) {
alert(responseData);
}
});
So the responseData is the json format collection of the courses.
Currently, I have a html code: <%= #courses.first.name %>
How to modify the #courses instance which the result is the responseData of ajax.
Thanks.
You can't change the instance variable, because that belongs to the instance of the Ruby class you're using.
Using ajax invokes a new instance of your respective classes (on the server); javascript only works with the front-end view (HTML code / DOM), so you have to populate that with the response:
$(document).on('change', '#city', function(){
$.ajax({
url: "/courses/index",
type: "GET",
data: {city: $('#city').val() },
success: function(responseData) {
course = JSON.parse(responseData);
$(".element").html(course.name);
}
});
});
Without knowing which data you're expecting back etc, it's kind of tough to know how to "parse" your data. However, the important thing to note is that you should not be trying to change the ERB, instead identify the html and replace it with the JSON you receive back.
Also, you'll need to use something like JSON.parse to create a workable object in your javascript (which you can then use to populate your page with).
Sounds like you want to POST the information back to the rails application via Ajax.

How do you save a dynamically generated element to your database?

Let's say you use the Embedly API and make the call in your application.js file:
$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
alert(oembed.title);
});
Now you have the hash oembed and can call, for example, ombed.thumbnail_url or oembed.title in the callback function. I want to know how you would save one of these elements in the call back function to your database.
Would the jQuery code look something like this:
$.ajax({
type: "POST",
data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_url'}
});
It looks like you just need to post the title and thumbnail_url back to your application using AJAX - http://en.wikipedia.org/wiki/Ajax_(programming).
The jQuery ajax api is very straightforward - http://api.jquery.com/jQuery.ajax/.

Categories

Resources