jQuery AJAX with PHP to upload contents to MYSQL DB - javascript

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!

As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>

I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Related

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Response values overlapping in ajax

I am making an application where I need to have multiple Ajax requests. But the problem is that I am getting same response values for both Ajax requests.
In each request there needs to be a data named activityCode but doing that I keep getting the value of ScoreBoardResponse even in the heartbeat function too. If I rename anyone of the activityCode to any other name the problem gets sorted. But why does this happen?
Here is the following code:
JS
var allJoined = false;
var roomName = $('#room').val();
var playerNameSet = function () {
if(!allJoined) {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 1,
room: roomName
},
success: function (ScoreBoardResponse) {
var obj = JSON.parse(ScoreBoardResponse);
var count = Object.keys(obj).length;
if (count == 1) {
playerOne_name.html(obj.p1_name);
setTimeout(playerNameSet, 3000);
}
else if (count == 2) {
playerOne_name.html(obj.p1_name);
playerTwo_name.html(obj.p2_name);
allJoined = true;
//Start the heartbeat to check if the other player is alive
setTimeout(startHeartbeat, 15000);
clearTimeout(playerNameSet);
}
},
error: function (error) {
console.log(error);
}
});
}
};
setTimeout(playerNameSet, 3000);
function startHeartbeat() {
$.ajax({
type: "POST",
url: "gameEngine/app.php",
data: {
activityCode: 2,
room: roomName
},
success: function(beat) {
console.log(beat);
},
error: function(error) {
console.log(error);
}
});
setTimeout(startHeartbeat, 15000);
}
PHP
.
.
.
elseif (isset($_POST['activityCode']) == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) == 2 && isset($_POST['room'])) {
echo "request reached here";
}
isset() returns either true or false if the POST variable exists or not. It does not return the variable value, the you need to add another check in your condition :
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 1 && isset($_POST['room'])) {
$response = $gameHandler->getPlayerOrder($_POST['room']);
echo $response;
}
elseif (isset($_POST['activityCode']) && $_POST['activityCode'] == 2 && isset($_POST['room'])) {
echo "request reached here";
}

Getting a post variable inside a function

I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>

jquery call other self-declared function in autocomplete select event

Can I call a function in autocomplete select event?
I have a function call getResult() which will retrieve data from database, the function is working smooth, just I fail to call this function in autocomplete's select event. Below is my code:
Auto-complete code:
$(function()
{
//auto complete for facultyID
var availableTags = <?php
$sql = "SELECT FacultyID from tblfaculty";
$result = mysql_query($sql, $DBLink) or die("Error " . mysql_error($DBLink));
$id_list = array();
while($row = mysql_fetch_array($result))
{
$id_list[] = $row['FacultyID'];
}
echo json_encode($id_list); ?>;
$("#FacultyID").autocomplete(
{
source: availableTags,
autoFocus:true,
select: function(event, ui)
{
getResult();
}
});
});
getResult() function:
function getResult()
{
$(function()
{
var Semester = $('#Semester').val();
var Year = $('#Year').val();
var Course = $('#Course').find(":selected").val();
var Subject = $('#Subject').find(":selected").val();
var FacultyID = $('#FacultyID').val();
var TimeSlot = $('#TimeSlot').val();
var Location = $('#Location').val();
$.ajax(
{
type: 'POST',
url: 'ajax_get_time_table.php',
data: {Semester:Semester+", "+Year, Course:Course, SubjectID:Subject, FacultyID:FacultyID, TimeSlot:TimeSlot, Location:Location},
dataType: 'json',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
//do something
}
else
{
//do something
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
}
Is there any wrong with my code?
You don't have to put everything in a doc ready block in getResult() function:
$(function(){});
because the DOM is already loaded and you are able to call this function inside autocomplete's select event.

Zend 2: problems with Ajax

I created a small function to test Zend-Ajax interaction.
In my view I set following code
<script type="text/javascript">
var urlform = '<?php echo $this->url('inbox/default', array('controller'=>'messages', 'action'=>'addmessage')); ?>';
</script>
<div onclick="ajaxtest();">Click</div>
Then, I created following function within file custom.js, already associated to the layout
function ajaxtest() {
$.post(urlform, null, function(data) {
if (data.success) {
alert('Ok');
} else {
alert('Failed');
}
}, 'json');
}
And finally, this is the code of my addMessageAction
public function addMessageAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
return $response;
}
When I click on the div associated to the javascript function, nothing happens, no alert is displayed.
Where am I wrong? Does it depend on particular zend settings?
I solved the problem by ridefining function in the following way:
var ajaxpost = $.post(urlform2).fail(function() {
alert("Failed");
})
ajaxpost.done(function(data) {
var parsed = jQuery.parseJSON(data);
if (parsed.success == 1) {
alert('Ok');
}
});

Categories

Resources