Reputation: 37233
i have little trouble with updating database by ajax , but i couldnt make it to work. i dont know what im doing wrong.
here my php file (sendata.php)
<?php
if ( isset($_POST['register']) && $userid != 0)
{$register = $_POST['register'] ;
$sql2 =$db->setQuery("INSERT INTO .... ");
$db->query() ;
}
?>
and here my javascript code
$(document).ready(function() {
$('#register').click(function() {
$.ajax({
url: "sendata.php",
data: {
age: $('#age').val()
},
type: 'POST',
success: function(msg) {
alert("Data has been saved succefully");
$('#mydata').html("<b> age: </b>" + age);
}
});
return false;
});
});
what is heppening to me is when register button is clicked i get only the alert , that data is saved succefully but when i go to database and see , there is no record at all there. im doing something wrong ?
EDIT :
this my button
<input type="submit" id="register" name="register" value="Save my Data" />
Upvotes: 0
Views: 157
Reputation: 1
Javascript:
jQuery(document).ready(function($)
{
//prevent registering the event more than once
//$('#register').off('click').on('click',(function(e) {
(1.) I would start with:
$('form').off('submit').on('submit',(function(e) {
or ..
$('input[type="submit"]').off('click').on('click',(function(e) {
then ..
$.ajax({
//url to touch
url: "sendata.php",
data: {
age: $('#age').val()
},
type: 'POST',
//on fail
fail: function(data){
//regular javascript alert on error
alert("Oppps! Data error");
},
//on success
success: function(data) {
//regular javascript alert on success
alert("Data has been saved succefully");
//assuming this is a div with an id of mydata
$('#mydata').html("<b> Age is: </b>" + data);
}
});
//prevents default action as we are not submiting the form but rather making use of AJAX to touch the php file
e.preventDefault();
});
});
sendata.php
<?
$msg= '';
if ( isset( $_POST['age'] ) )
{
$age = filter_input(INPUT_POST, "age", FILTER_SANITIZE_STRING);
//echo $age;
//around this check if the insertion is correct and that you can talk to the db
//db handling, insertion, etc..
// $sql2 =$db->setQuery("INSERT INTO .... ");
// $db->query();
//$msg .= "Epic Win! $age";
$msg .= "$age";
}
else $msg .= 'Error, no age provided :( ';
//we are returning the data so we need to echo it as an output here.
echo $msg;
?>
Upvotes: 0
Reputation: 8200
sendata.php checks to see if 'register' is set: if ( isset($_POST['register']) ...)
So you must SET the variable 'register' in your request (I fixed the code - see bold):
$(document).ready(function() {
$('#register').click(function() {
$.ajax({
url: "sendata.php",
data: {
age: $('#age').val(),
register: "register"
},
type: 'POST',
success: function(msg) {
alert(msg);
$('#mydata').html("<b> age: </b>" + age);
}
});
return false;
});
});
sendata.php
if ( isset($_POST['register']) && $userid != 0)
{
$register = $_POST['register'] ;
$sql2 =$db->setQuery("INSERT INTO .... ");
$db->query() ;
echo "SUCCESS";
exit(0);
}
echo "FAILURE";
Upvotes: 1