Insert data in MySQL Database using AJAX on checkbox tick - javascript

Before getting stuck here, I had a look at the implementation of question asked here
I tried implementing the code and wish to insert data at checkbox click inside MySQL database. It might have been done already if I was supposed to insert data on form submission but I have to individually insert 8 bit data by turning their flag ON/OFF at checkbox tick.
I tried doing it, but don't know where exactly I am going wrong.
Below are the code snippets :
PHP CODE insertIntoAbbaa.php :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$updateCon = mysqli_connect("192.168.0.7", "uzer", "password", "remondb");
if (!$updateCon) {
die("not able to cconnect" . mysqli_error());
}
if(isset($_POST['firstOutputData'])){
$firstData = mysqli_escape_string($updateCon, $_POST['firstOutputData']);
if(!$firstData){
echo "nopes !";
}
$updateValue = mysqli_query($updateCon, "INSERT INTO update_abbaa(rfu_id, upadate_index, update_value) values(1,'$firstData',1)");
if(!$updateValue){
echo "nopes !";
}
mysqli_close($dbget);
echo "Saved !";
}
else{
echo " nothing happened ! ";
}
?>
</body>
Below is the onclick event I am calling on checkbox tick :
HTML onclick code snippet :
<span class="toggle">
<input type="checkbox" onclick="onOffFunction1()" id="onoff1">
<label data-off="Off" data-on="On"></label>
</span>
Now, I am trying to call the above mentioned function in javascript as follows :
function onOffFunction1() {
var firstCb = document.getElementById("onoff1");
if (firstCb.checked) {
document.getElementById("firstBitData").innerHTML = "1";
document.getElementById("firstBitData").style.backgroundColor = "green";
var firstOutputData = "1";
$.ajax({
url: "insertIntoAbbaa.php",
type : "POST",
data : "firstOutputData"+firstOutputData,
success: function(data)
{
alert("success !" + data);
}
});
}
The output shows me "nothing happened" message as I have written in PHP script
Please go easy on me I am a beginner !

The error message 'Nothing happened' is caused because this check:
if(isset($_POST['firstOutputData']))
is false. That means there is no value inside $_POST with index 'firstOutputData'. The first place you need to look for an error like that is your AJAX call and if you pass the parameter correctly, which you don't.
This:
data : "firstOutputData"+firstOutputData,
should be:
data : {firstOutputData: firstOutputData}

Related

ajax request is successful, but php is not running

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

loading message with jquery and calling id

I made a small shoutbox for my site and I am loading the page with jquery and storing all my data in a database like usual. anyways, when a user wants to edit a post they double click on it and they can edit their post. I am using the following code to show the editor and let them do whatever they need to with it. sadly something isn't working and that something is:
i cant include my tag id in the url: on my ajax call
Here's is a look at the code
<? php
public function make_editable($shout, $id) {
$string = "<span ondblclick=\"javascript: edit_shout('".$id."'); return false;\">".$shout."</span>";
return $string;
}
?>
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id={$id}",
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>
If i replace the {$id} with say, 1 for example, then it works correctly and loads the text of shout id 1 into the field like its supposed to, but if I try and load dynamically using $id, it just gets an error because the $id is coming up as blank... Thanks for your help :).
Uhm... if the variable is in javascript you can do:
url : "/chat?loadModule=3&id=" + $id,
If it is php then you have to do
url : "/chat?loadModule=3&id=<?=$id?>",
But like the other guys said, without more code we can't help much.
Very easy fix thanks to #Dranes for his help. Simply needed to add +
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id=" + $id,
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>

Save form inputs to txt, popup result, no page changing

I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article

Unable to send jQuery variable with string content to PHP using jQuery AJAX function?

The code snippet for the jQuery function looks like:
function addMessage() {
if (textval != "") {
text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
alert(text_string);
$.ajax({
type:"POST",
url:"process.php",
data: {'text_string': text_string},
cache:false,
success:function(){
alert("submitted")
}
});
$("input[type=text]:last").val("");
}
enterButton = 0;
}
The process.php code looks like:
<body>
<?php
//$host = "localhost";
$text_string=$_POST['text_string'];
echo "string submitted is".$text_string;
?>
</body>
I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:
Undefined index: text_string
I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?
If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:
<?php
session_start();
// Store value in session if it is passed
if (isset($_POST['text_string'])){
$_SESSION['text_string'] = $_POST['text_string'];
}
// Read and echo value from session if it is set
else if (isset($_SESSION['text_string'])){
$text_string=$_SESSION['text_string'];
echo "string submitted is".$text_string;
}
?>
Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)
Hope this helps! Let me know if you have any questions.

data-attribute wont submit content

I'm busy developing my first Twitter application. However, I'm stuck at something basic which I cant solve for some reason. I used to use data-attributes alot, but I just cant get it to work. It just wont submit the content of my data-attribute
Part of my HTML.
<div id="invTweet" class="_invitation-tweet-inner no-select" data-tweet="Here comes the content of the tweet which will be submitted">Here comes the content of the tweet</div>
<div id="post-invitation-tweet" class="button blue post-tweet">Post Tweet</div>
Part of my Javascript
var tweet = $("#invTweet").attr("data-tweet");
$(document).on('click',"#post-invitation-tweet",function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../includes/db-requests/db-postInvitationTweet.php",
data: {tweet:tweet},
success: function(data){ finishInvitationTweet(data); }
});
});
function finishInvitationTweet(data) {
alert(data);
}
I use alert(data) for debugging purposes. When I click on the Post Tweet button, an alert will open with the echo "Undefined index: tweet emptyTweet". Look below for a snippet of my db-postInvitationTweet.php:
//Get Tweet data
$tweetMsg = safe($mysqli,$_POST['tweet']);
//Check if $tweetMsg is empty. No > post tweet.
if ($tweetMsg != '') {
$post_tweet = $connection->post('statuses/update', array('status' => $tweetMsg));
if (187 == $connection->http_code) {
echo "statusDuplicate";
die();
}
if (!$post_tweet) {
echo "tweetError";
} else {
//Update the invitation_sent column in database
$stmt = $mysqli->prepare("UPDATE members SET invitation_tweet = '1' WHERE oauth = ? ") or die (mysqli_error($mysqli));
$stmt->bind_param('s', $access_token['oauth_token']);
$stmt->execute();
$stmt->close();
echo "tweetSuccess";
}
} else {
echo "emptyTweet";
}
What am I missing :')
What version of jQuery are you using? As of around version 1.4 the appropriate way to access a data attribute would be through the data() method, see method signature and docs here.
If you change that you may be able to get it to work just fine. See jsFiddle with working solution as proof of concept.
Changed
var tweet = $("#invTweet").attr("data-tweet");
To
var tweet = $("#invTweet").data("tweet");

Categories

Resources