insert javascript variable into mysql - javascript

I have created a quiz page named quiz.php. It contains javascipt which calculates the correct answers of the user (amountCorrect variable). I want to insert this variable to mySql db via scorepage.php but my code doesn't work. Any help ???
Here is the part of javascript
function show_score() {
var amountCorrect = 0;
...
if(radio.value == "right" && radio.checked) {
amountCorrect++;
}
}
alert("Correct " + amountCorrect + " out of 6");
$.ajax({
type: "POST",
url: "http://localhost/Istoselida/scorepage.php",
data: "score1=" + amountCorrect,
success: function () {
$('ul#posts').prepend(wall_post);
}
});
}
And here is the part of the scorepage.php
include('db2.php');
$member_id=$_SESSION['member_id'];
$result=mysql_query("select * from studentstable where id='$member_id'")or die(mysql_error);
$row=mysql_fetch_array($result);
$score1 = mysql_real_escape_string($_POST['score1']);
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row");

You're trying to pass $row in the UPDATE statement. $row is an array, not a value. Try:
$sql = mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row[id]");

put row id $row['filedname']
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= ".$row['id']);

Related

AJAX Post values not received in PHP

Below is my ajax file. Here I passed all my text box values.
And I post that values to edu.php. There I want to update two tables like details and test.
But nothing is updating in my database.While I checked the value with var_dump the string seems to be empty.But while passing from ajax I checked it with an alert it shows all the values in text box. So I believe problem is happening while posting from ajax to php.
AJAX Code
$('#edubackgroundsubmit').click(function (event) {
event.preventDefault();
alert("Hello");
var per_email = $('#per_email').val();
var master_overall = $('#master_overall').val();
var master_pass_year = $('#master_pass_year').val();
var master_college = $('#master_college').val();
var master_univ = $('#master_univ').val();
var data1 ="master_qual="+master_qual+"&master_overall="
+master_overall+"&master_pass_year="+master_pass_year+"&master_college="+master_college+"&master_univ="+master_univ
+"&edu_flag="+edu_flag;
alert(data1);
$.ajax({
type:"POST",
url: "edu.php?per_mobile="+per_mobile,
dataString1: data1
}).done(function( dataString1 )
{
alert(dataString1);
$('#edu_alert').append(
'<div class="alert alert-success text-center">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + dataString1 + '</div>');
});
});
PHP File
if (isset($_POST['pass_year_12'])) {
$pass_year_12 = $_POST['pass_year_12'];
} else {
$pass_year_12 = "";
}
$l1 = "UPDATE test
SET edu_flag='$edu_flag'
WHERE per_mobile='$per_mobile'";
$l2 = "UPDATE details
SET master_qual='$master_qual',
master_overall='$master_overall',
master_pass_year ='$master_pass_year ',
master_college='$master_college'
WHERE per_mobile='$per_mobile'";
$exec = mysqli_query($link, $l1);
if (mysqli_query($link, $l2)) {
echo "Education Details Updated Successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
This is wrong. What's this bit:
dataString1: data1
You need to change it as:
data: data1
The function $.ajax() POSTs only those given in the data attribute.
Problem with your code is hat you are sending the data at edu.php?per_mobile
so you need to add isset condition before the code... like this
if(isset($_REQUEST['per_mobile'])){ //write your code here }
and also replace datastring to data.
and then try.
Hope it may help.
For instance you can also use jQuery get or post method, that is more reliable and easy to learn.

Submitting form using JQuery, AJAX and PHP

I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.

Prevent already selected option Jquery autocomplete with MYSQL

I am using Jquery Autocomplete to fetch a list of tags from a mysql table. When the user picks one tag from the list, it gets saved on the page. I am trying to prevent the already saved tag from being displayed again.
Here is my code:
HTML
<input type="text" id="tag">
<input type="text" id="tags" style="display:none;">
Jquery
$('#tag').autocomplete({
source : function(request, response) {
$.ajax({
url : 'tags.php',
dataType : "json",
method : 'post',
data : {
searchQuery : request.term,
selectedTags: $('#tags').val() //sends already selected terms
},
success : function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label : code[0],
value : code[0],
data : item
}
}));
},
error: function(jqxhr, status, error)
{
alert(error);
}
});
},
autoFocus : true,
minLength : 1,
select : function(event, ui) {
var names = ui.item.data.split("|");
tag_ids = [];
tag_names = [];
tags = $('#tags').val();
if(tags != '')tag_names = tags.split(',');
tag_ids.push(names[1]);
tag_names.push("'" + names[0] + "'");
$('#tags').show();
$('#tags').val( tag_names.join( "," ) );
$('#tag').val('');
}
PHP
$searchQuery = $_POST['searchQuery'];
$selectedTags = $_POST['selectedTags'];
if(!empty($selectedTags))
{ $query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN ?");
$query->execute(array($searchQuery . "%", $selectedTags));
}
else
{
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ?");
$query->execute(array($searchQuery . "%"));
}
When I select the first suggestion, it gets saved in #tags but then no other suggestion is displayed. If there is any other suggestion to achieving this, that'd be great.
I figured it out. I was trying to pass an array to the prepared statement.
PDO doesn't work that way.
To solve this, I declared the number of parameters first and then put them in the prepared statement while using foreach to bindvalue to each parameter.
Here is the final solution:
//exploding the string to an array first
$selectedTags = explode(',', $selectedTags);
//creating another array with parameters equal to the size of the selectedTags
$bindValues = implode(',', array_fill(0, count($selectedTags), '?'));
//putting the parametes
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN (" . $bindValues .")");
//binding values
$query->bindValue(1, $searchQuery . '%');
//Now, using foreach to bind selected tags values
foreach($selectedTags as $k => $selectedTag)
{
//using k+2 as index because index starts at 0 and first parameter is the search query
$query->bindValue($k+2, $selectedTag);
}
$query->execute();
And this solved the problem. I hope it helps others too.

How to use jQuery/Ajax to perform MySQL Query

I'm trying to use jQuery to check if the username that the user entered in a form is already taken. Below are the relevant codesnippets in Java, and existence.php.
*javascript*
var username = document.register.username.value;
usernameTaken = checkUserExistence(username, 'username');
function checkUserExistence(str, type){
var dataString = '?str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existence.php",
data: dataString,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
$("#submit").val('Succes!');
return 1;
}else{
$("#submit").val('Failure!');
return 0;
}
}
});
}
return false;
}
*/JavaScript*
<?php
include("inc/connect.php");
$data = $_POST["str"];
$type = $_POST["type"];
switch($type){
case "username":
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
break;
}
?>
What am I doing wrong?
My website is supposed to show live hints to the users, like 'your username is too short' etc. All hints are working, but the ones where it should say 'your username is already taken' won't show. The form gets processed to my PHP-register function, where usernames that are already taken get rejected, so somehow the checkUserExistence-function and the existence.php page are not working.
Edit:
For a live demonstration of my code, go to:
http://beta.somentus.nl/index.php
The usernames 'Admin', 'Somentus' and 'Rik' are already taken, try them out :)
$data = $_POST["data"];
should be:
$data = $_POST["str"];

Inserting a data on a database using AJAX/JSON/Jquery

I'm trying to create a small chat application but for the sake of minifying the bytes being transferred is there any other way on writing this javascript that is less heavy than this code?
Here is my javascript:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
Can this also be done on a JSON format too? because I think some says that json is lighter.. not sure though
here is my php code
$con = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt=$con->prepare($sql);
$stmt->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$text=$_POST['message'];
$sql4 = "INSERT INTO $tblname2(msgid,username,message_content,message_time,recipient)VALUES(:aid,:a,:b,NOW(),:c) ";
$stmt5 = $con2->prepare($sql4);
$stmt5->bindParam(':aid',$tblpre,PDO::PARAM_STR);
$stmt5->bindParam(':a',$_POST['name'],PDO::PARAM_STR);
$stmt5->bindParam(':b',$text,PDO::PARAM_STR);
$stmt5->bindParam(':c',$usern,PDO::PARAM_STR);
$stmt5->execute();
As user2401175 saies. Why not use a framework, thats what they are here for.
jQuery is really simple and easy to understand.
You could try adding this, just before your "" tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Under this include of jQuery, you may now use the jQuery Post method to do your ajax request.
In html Use
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
then Create javascript object like this
var changePacket = {
date1:value1,
data2:value2
}
And send Ajax request
$.ajax({
url: "phpFile.php",
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(changePacket)},
success: function(response) {
alert('hip hip hurray');
},
error: function(response) {
alert('some thing wrong happend');
}
});
In php
$json = $_POST['json'];
$data = json_decode($json);
now user your variable like this $date->data1 and $date->data2

Categories

Resources