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

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

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",

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.

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"];

Getting multiple LIVE values into JavaScript from AJAX/PHP

I'm making a web application and I'm trying to make it so when you enter the ID of a provider it automatically outputs them into a span, this is my AJAX/JS call
<script>
function showHint(str)
{
if (str.length == 0)
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../include/proveedores.php?q=" + str, true);
xmlhttp.send();
console.log(telfValor);
}
}
</script>
<span id="txtHint"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
And this is the .php it calls to make the search
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = $_REQUEST["q"];
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
// Output "no suggestion" if no hint was found or output correct values
echo $descrip === "" ? "no suggestion" : $descrip;
?>
Is there any way to accomplish this?
EDIT: This is to make an AJAX calls to return various values into spans with just 1 AJAX call
<script src="../js/jquery.js" type="text/javascript"></script>
<script>
function showHint(str)
{
// If there is nothing on the textbox, there is nothing in the spans
if (str.length === 0)
{
$('#Span Name').html("");
$('#Telephone').html("");
return;
}
$.ajax
({
//Here goes the file which contains the SQL call
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
// Here goes the data that goes into the spans
success: function (data, status, jqXhr)
{
$("#Span Name").html(data["Array Name"]);
$("#Telephone").html(data["Telephone"]);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
}
</script>
// This is the text input that will be sent to your query file
<input type="text" onkeyup="showHint(this.value)">
<span id="Span Name"></span>
<span id="Telephone"></span>
proveedores.php:
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL, this is what you have posted
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
if (isset($q) && $q !== "")
{
// THIS IS PRONE TO SQL INJECTION! USE INTERNALLY!
$sql = "SELECT * FROM PROVIDERS WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$Variable = $row['Column Name'];
$Telf = $row['Telef'];
$Direc = $row['Direc1'];
}
// This is the array to be encoded to AJAX
$values = array();
// Output "no suggestion" if no hint was found or output correct values
$values["ArrayName"] = ($Variable === "") ? "no suggestion" : $Variable;
$values["Telephone"] = ($Telf === "") ? "" : $Telf;
// Output the json data
print_r(json_encode($values));
?>
To start, you should use a javascript library like jQuery to handle all the tough AJAX lifting. It will make your life sooo much easier. If you want to use regular javascript, you can return a comma-separated string and then parse each value separated by a comma but that can get messy. With that being said, you can use jQuery AJAX and return your data in a JSON encoded data object.
.php
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
$values = array();
// Output "no suggestion" if no hint was found or output correct values
// NOTE: we're using the same "txtHint" here for the key as we do in the javascript function
$values["txtHint"] = ($descrip === "") ? "no suggestion" : $descrip;
// Set these to something useful
$values["txtPhone"] = "";
$values["txtAddress"] = "";
// Output the json data
print_r(json_encode($values));
?>
Now, for the jQuery implementation. The first thing you'll have to do is download the jQuery library from jQuery's website. I would recommend getting the most recent version (currently jQuery 2.x).
.html
<script src="/script/jquery.js" type="text/javascript"></script>
<script>
function showHint(str) {
if (str.length === 0) {
$('#txtHint').html("");
return;
}
$.ajax({
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr) {
$("#txtHint").html(data["txtHint"]);
// You can do this same thing for the other data returned
$("#txtPhone").html(data["txtPhone"]);
$("#txtAddress").html(data["txtAddress"]);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}
});
// Not sure where this is defined. It might throw an error
console.log(telfValor);
}
</script>
<span id="txtHint"></span>
<span id="txtPhone"></span>
<span id="txtAddress"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
The obvious change is the call to $.ajax() instead of using the XmlHttpRequest() object. It is in and of itself fairly self-explanatory. One thing I would like to mention is that since we set the "type" to "GET", the key-value pairs in "data" will be appended to the url as a querystring in the form: "url?key1=value1&key2=value2&etc...". So the resulting url, in our case, would be "../include/proveedores.php?q=[VALUE_OF_STR]" where [VALUE_OF_STR] is the value of the str variable.
The other change worth noting is that jQuery has a very helpful way of selecting elements. If you want to get an element by an ID you can just use the syntax: $('#txtHint').
Where the '#' symbol denotes that we're looking for an element based on the ID and 'txtHint' is the ID of the element you're looking for. You can read more about jQuery selectors in the docs.

How do you input javascript variable into php script?

I'm trying to get a function called that calls a php function with an input.
javascript function (picNum is an integer):
function hello(picNum) {
var pictureNumber = picNum;
var phpFunc = "<?php
include 'otherfile.php';
otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
?>";
echo phpFunc;
}
otherfile.php
<?php
function otherFileFunc($i) {
$final = $i + 1;
echo $final;
}
?>
this code pretty much says if you do onclick="hello(1)" then the output or phpFunc should be 2 because you add one in the otherfile.php, but no matter the input the output is always 1 so I'm guessing the input at where I marked just isn't going through.
DONT TELL ME IT DOESNT WORK BECAUSE IT DOES.
if i put an integer instead of " + pictureNumber + " it works perfectly!
any help is appreciated :)
Unfortunately you won't be able to call php from javascript.
Php is run from the server and javascript is run on a client (usually, the exception being node.js. However even in the instance of node.js, php is not used as javascript has replaced its functionality)
If you need to have javascript "call" a server function you will need to look into ajax requests so that the server can then run a function and return it to the client.
You have to use Ajax bro:
Javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
}
PHP otherfile.php:
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
Note: Untested
EDIT, tested:
javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
pictureNumber = output_string['picturenumber'];
alert(pictureNumber);
}
});
}
hello(1); //sample
PHP otherfile.php:
$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);
echo json_encode($array);

Categories

Resources