Saving data with ajax to a database - javascript

How can I save info that I have in a div named '#time' to a database?
<div id="time" style="float:right;font-size:15px;">0:00:00</div>
The code above is a jq count up timer.
What I'm trying is to save every tick in the database.
How can I do this?
$.ajax({
type: "POST",
url: "setupcounter.php",
data: {action: 'save',
field: $("#time").val(),},
success: function(msg){
}
error: function(){
alert('error');
}
});

Actually you want to get text of div. So do this..
Just replace
$("#time").val()
with
$("#time").text()

var time = $('#time').val();
//Just add whatever params you need to the datastring variable.
var dataString = 'time='+time+'&action=save';
//Check console that you are sending the right data
console.log(dataString)
$.ajax({
type: "POST",
url: "setupcounter.php",
data: dataString,
success: function(msg){
console.log(msg);
}
});
In php you would do:
$time = $_POST['time'];
$action = $_POST['action'];
//Db stuff
Fiddle

Related

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

Using jQuery or Javascript redirect to given page with a value

I have a dropdown, on its change it should redirect to a page with the dropdown's value say as a POST
I tried something like this:
$(document).ready(function() {
$('some_dropdown').change(function() {
var id = $(this).val();
var datastring = 'id=' + id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
window.location.href("xyz.php");
}
});
});
});
On the xyz.php page:
if ($_POST['id']) {
Blah Blah..
}
It's not recognizing that id value on the xyz page. I want it's value on the redirected page.
Edited - To make things more clear, I tried out to print the xyz.php's contents on my original page (instead of redirecting) like this -
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
FYI, "somediv" was <div class="somediv"></div> in my original page(no-redirecting) and it worked!! It could identify the id. Some how can't work it out with redirecting. It can't identify the id.
Edited --
Last thing, if I don't redirect and use
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
The data loads perfect, my question is can I make some changes in the dynamically loaded textboxes and insert them in the database
If you have to make a post request can make it by appending a virtual form.
Here is the code for that.
$(document).ready(function() {
$('[name="some_dropdown"]').change(function() {
var mval = $(this).val(); //takes the value from dropdown
var url = 'xyz.php'; //the page on which value is to be sent
//the virtual form with input text, value and name to be submitted
var form = $('<form action="' + url + '" method="post">'+
'<input type="text" name="id" value="' + mval + '" />'+
'</form>');
$('body').append(form); //append to the body
form.submit(); //submit the form and the page redirects
});
});
and on PHP
if(isset($_POST['id'])){
echo $_POST['id'];
}
Your datastring should be key value pair. Like this.
var datastring = {'id':id};
you have few mistakes in your code so your correct code will be like this
$('.some_dropdown').change(function(){
var id = $(this).val();
var datastring = 'id='+id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html){
window.location.href= "xyz.php?"+datastring+"";
}
});
});
});
and php code
if(isset($_GET['id'])){
Blah Blah..
}

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

jquery json post not working

Well, im trying to post a variable in jquery to my controller. But it seems that the posting is not successful. I am not getting any value when i try to retrieve it in my controller. It says undefined index. Here's what I have:
my jquery:
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:'<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>',
type: 'POST',
async: false,
data: data,
dataType: 'json'
// success:function(data){
// alert(data);
// },
// error:function(data){
// alert(data);
// }
});
});
});
my controller:
function instantiateButtonValue(){
echo $_POST['data'];
// $this->set('data','some');
// $this->render('json');
}
I think you should enclose with " quotes instead of ' quotes in URL.
From PHP you should encode as JSON instead of direct echo, to retrieve the value by JQuery.
like below
echo json_encode($_POST['data']);
i got an idea from this link here
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:"<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>",
type: 'POST',
async: false,
data: {data:data},
dataType: 'json'
});
});
});

Categories

Resources