How to store JS variable in a database - javascript

I'm using CakePHP and since several days I try to store a java script variable with the help of ajax (jQuery) in a mysql database.
I'm using the following code to do this:
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
But when I click on the submit button, Ajax will post the whole sourcode of my webpage. =(
What I need is a function to store a java script variable to my database but without reloading the page.
I am grateful for any help =)

You told jQuery to serialise a form element. That is, convert the form element to a text string. In other words, you are telling it to get the form's HTML code and send that to your server.
I don't know (or want to know) what the correct way of sending a form's data by AJAX is, but I do know that you need to actually do something like access the form's fields to get their values.

My js is a bit rusty but try changing:
var formData = $(this).serialize();
To:
var formData = $('#saveForm').serialize();
Or:
var formData = $('#saveForm').val().serialize();
That's assuming you want to serialize and store the html of the whole form.
To pull just a value from the form (I don't think you need serialize) try:
var formData = $('#saveForm #someInputName').val();
Of course changing someInputName to whatever the actual name of the field you want to save is.

The problem could be in data parameter.. $('#saveForm').serialize();
should be ok

Related

how to add div content to mysql without using form element

I want to save div content into mysql without using form and button means page should be opened in browser and it should send it's all div content to mysql table automatically.
here it is what i tried
var myVar = setInterval(function(){getElement()},5000);
function getElement()
{
var iBody = $("#frametest").contents().find(".bx-viewport").html();
document.getElementById("demo").innerHtml=iBody;
alert(iBody);
}
i want this demo div to be saved in mysql
If you don't want to use forms, I think AJAX is a great option.
var contents = $('#frametest').contents().find('.bx-viewport').html();
$.ajax({
url: 'path/to/php/script',
type: 'POST',
data: {content: contents},
success: function() {
// do something after sending data
}
});
This will send contents to the php script defined in the url property of the AJAX call as a POST request, and in the php script you can use the normal thing you'd do for saving it in MySQL.

Passing values for JQPlot from PHP

As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.

Extract form variable in AJAX response using jquery

All,
I have a Jquery ajax request calling out a URL. The ajax response I receive is an HTML form with one hidden variable in it. As soon as my ajax request is successful, I would like to retrieve the value of the hidden variabl. How do I do that?
Example:
html_response for the AJAX call is :
<html><head></head><body><form name="frmValues"><input type="hidden"
name="priceValue" value="100"></form></body></html>
$.ajax({
type: 'GET',
url: "/abc/xyz/getName?id="+101,
cache: false,
dataType: "html",
success: function(html_response)
{
//Extract form variable "priceValue" from html_response
//Alert the variable data.
}
});
Thanks
The html_response you get will be a string. As such, if you happen to know exactly what the page will look like, you can just search the text using indexOf.
...But that solution is messy and error prone. Alternatively, you could create a new HTML element (like a div), put your response html in there, and then obtain the hidden variable as you would access any normal html element.
For example:
var tempDiv = $("<div/>");
tempDiv.append(html_response);
var myValue = tempDiv.find("input[name='priceValue']").val();
You can create JQuery object:
var form = $(html_response);
Then get your input PriceValue using JQuery selectors & traversal.
You can read it with $(html_response).find("input[name='priceValue']").val();

Manipulate form data before it's sent with jQuery

I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}

Datatables submit form serverside data

For those of you that use the Datatables js plugin, how can I create this example with server side data?
The example uses data that is hardcoded in the HTML.
You would basically do the following:
Serialize the form data (using jquery serialize as the example shows)
Submit said data to your form handling scrip (php etc)
They already provide the jquery serialize code so I won't show that, however the jQuery AJAX function will be needed (at the least):
$.ajax({
type: "POST",
url: "some.php",
data: YOUR-SERIALIZED-DATA-HERE,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
And on your Server side PHP file you just grab the correct form array and parse your values ($_POST).
I had the same problem and didn't want to do an ajax save, so I did this:
var table = $("#mytable").datatable();
$("#myform").submit(function () {
var hiddenArea = $("<div></div").hide().appendTo("#myform");
table.$('input:hidden').detach().appendTo(hiddenArea);
// Prevent original submit and resubmit, so the newly added controls are
// taken into account
this.submit();
return false;
});
The idea is that I take all the inputs that are currently not in the dom and move them inside a hidden container.

Categories