I am working first time on php. I want to pass my parameters from angularJs to a php file then those parameters are supposed to be used in INSERT query. I have used XmlHttpRequest to call php file (addsubscriber.php?par1=val1&par2=val2) through AngularJs Function (vm.addSub). Now I dont know how to catch those parameters in my php file.
AngularJs
vm.addSub = function(){
var params = "name="+vm.selectedNameAdd+"&number="+vm.selectedPhoneAdd+"&status="+vm.selectedStatusAdd;
var oReq = new XMLHttpRequest();
oReq.onload = function(){
vm.msg = JSON.parse(this.responseText);
};
oReq.open("get", "addSubscriber.php?"+params, true);
console.log("addSubscriber.php?"+params);
oReq.send();
};
});
addSubscriber.php (What have I tried so far is commented in my php file)
<?php
include('connectionString.php');
$dbObj = new connectionString();
$conn = $dbObj->getdbconnect();
// $request = json_decode( file_get_contents('php://input') );
// $name -> name;
// $number -> number;
// $status -> status;
// $name = filter_input( INPUT_GET, 'name', FILTER_SANITIZE_URL ); // $_GET['name'];
// $number = filter_input( INPUT_GET, 'number', FILTER_SANITIZE_URL ); // $_GET['number'];
// $status = filter_input( INPUT_GET, 'status', FILTER_SANITIZE_URL ); // $_GET['status'];
// parse_str($_SERVER['QUERY_STRING']);
$date = date("Y-m-d");
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES($name,$number,$date,$status)";
if(mysqli_query($GLOBALS['conn'], $query)){
$msg = "Inserted Successfully";
}
else{
$msg = "Insertion Failed";
}
print json_encode($msg);
Actually the problem was with Query
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES('$name','$number','$date','$status')";
Note the single quotes in VALUES part.
After adding single quotes it worked as desired.
Related
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
Here is my situation:
I have a JS function that creates an XMLHttpRequest object. The request is opened, and I'm calling the "GET" method on a specified url. The request works, as in it gets to the url destination and executes the code in the destination, but I'm not sure how to access a variable in the destination code.
Here's what I've got:
JS:
function fillTestsTable()
{
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open("GET", "./db-queries/get-tests.php");
xhr.send(null);
}
PHP destination file:
<?php
$conn = mysqli_connect("localhost:3306" , "exampre2_tplugin" , ",Vyml.F!#(}{" , "exampre2_totaltoefltimeplugin");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$sql = "SELECT * FROM TOEFLTESTS";
$result = mysqli_query($conn, $sql);
//return $result;
?>
What I am trying to do is return the data in the $result variable in the php. Is there a way of doing this?
In PHP, return is used to return a value from the current function to where that function was called.
To output data in the HTTP response use echo or print.
Note that mysqli_query returns a mysqli_result object so you will need to extact the data you want from that (e.g. with fetch_array) and then convert it to a suitable text format (e.g. with json_encode).
For example: if you wanted to return JSON formatted data for your Ajax callback function to play with you might do something like this:
<?php
$conn = mysqli_connect("localhost:3306" , "exampre2_tplugin" , ",Vyml.F!#(}{" , "exampre2_totaltoefltimeplugin");
$data=[]; //store recordset here
$sql = "SELECT * FROM TOEFLTESTS";
$result = mysqli_query($conn, $sql);
if( $result ){ /* iterate through the recordset, add each row to output data */
while( $rs=$result->fetch_object() ){
$data[]=$rs;
}
}
/* send data back to the ajax callback function */
exit( json_encode( $data ) );
?>
There are many ways you could proceed with this but it helps to clearly define the purpose and identify how your app is to work. The callback will then manipulate the response data to add new rows to your HTML table. Knowing what the callback is to do will generally ( or can ) affect the format of data you return - in your case if it is simply to be new rows in an HTML table it would be better to format the data server-side as HTML and send back raw html text.
Using Ajax allows your app to request data of whatever sort without the need to reload the page ( usually a traditional form submission )
As a basic example of populating an HTML table following a basic ajax request ( POST rather than GET but would work the same )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'maps';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
ob_clean();
$sql='select `name`,`address`,`lat`,`lng` from `maps` limit 10';
$res=$db->query( $sql );
while( $rs=$res->fetch_object() ){
printf('
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>',
$rs->name,
$rs->address,
$rs->lat,
$rs->lng
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Ajax: fetch data from db - add to table</title>
<script>
const ajax=function(url,params,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
};
</script>
</head>
<body>
<input type='button' value='Fetch Data' />
<table></table>
</body>
<script>
document.querySelector('input[type="button"]').onclick=function(e){
ajax( location.href, false, function(r){
this.innerHTML=r
}.bind( e.target.nextElementSibling ))
}
</script>
</html>
I'm using prestashop 1.6, I have an ajax function where I encode some data which I successfully retrieved on console withecho. Now I have to decode this json data in another ajax function to get a value for a specific variable. Sorry I'm a newbie with prestashop 1.6.
My first ajax function :
public function ajaxProcessAddQrVideo(){
$target_dir = _PS_IMG_DIR_.DS.'video_qr';
$id_product = Tools::getValue('id_product');
$stamp = strtotime('now');
$filename = 'video_qr_'.$id_product.'_'.$stamp.'.jpg';
$target_file = $target_dir.DS.$filename;
$upload = $_FILES['video_qr_attachment_file'];
$err = array();
$uploaded = false;
if($upload['type'] !='image/jpeg'){
array_push($err,"Veuillez entrer un fichier JPG");
}
if(empty($err)){
$uploaded = #move_uploaded_file($upload['tmp_name'], $target_file);
$this->context->smarty->assign('uploaded', $uploaded);
$this->context->smarty->assign('filename', $filename);
}
$this->json =array(
'uploaded'=>$uploaded,
'err'=>$err,
'id_product'=>$id_product,
'stamp'=>$stamp,
'file_name'=>$filename,
);
echo json_encode($this->json);
exit;
}
And I want to get the value of 'file_name' in my second ajax function:
public function ajaxProcessAddVideo(){
$img_path = json_decode($this->json,true);
$filename = $img_path['file_name'];
$id_lang = Context::getContext()->language->id;
$script = Tools::getValue('script');
$id_product = Tools::getValue('id_product');
$id_group_vid = Tools::getValue('cust_group');
//add qr_code video
$qr_code =$filename;
$err = true;
$insert = false;
$videos = array();
$vid = new MpsVideo();
$vid->id_product = $id_product;
$vid->url = $script;
$vid->cust_group = $id_group_vid;
$vid->date_add = date('Y-m-d H:i:s');
$vid->active = 1;
$vid->qrcode = $qr_code;
$is_existing = Db::getInstance()->getValue("SELECT COUNT(id_mps_video) FROM `ps_mps_video` WHERE id_product=$id_product AND url = '$script'");
if($is_existing==0){
$insert = $vid->save();
$id_group = explode(',',$id_group_vid);
$group_name = array();
foreach($id_group as $k){
$group = new Group($k);
$group_name[] = $group->name[$id_lang];
}
$vid->group_names = implode('<br/>',$group_name);
}
echo json_encode(array(
'err'=>$err,
'video_exists'=>$is_existing,
'insert'=>$insert,
'vid'=>$vid,
));
exit;
}
I don't know how to achieve this but I know its possible. If someone can help understand this, I would be very grateful.
the result of the first function is a json, that result must be read from another file and then passed to your second function. Or else the same function should read that json:
$data = file_get_contents("file/file_json_result.php");
$img_path = json_decode($data, true);
I have a form, the form has text fields and a canvas in it that preforms as a signiture pad.
link to the form
I use ajax in order to send the form.
What I have troubles doing is to confirm that the form is inserted to the database.
I think that there is a collision between the ajax and the php I use in order to insert the form data to the mysql db
how can I do it?
This is the content of the js file
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
alert(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
This is the content of the upload_data.php file:
<?php
require 'inc/inc.php';
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$idNo = $_POST['idno'];
$name = $_POST['fname'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() ."-" . $idNo . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
$suc = new Form;
$suc->insert_data($name, $file, $idNo);
?>
This is the insert_data() php function content
public function insert_data($name, $file, $idNo){
$query = $this->dbh->prepare("INSERT INTO signitures (name, file, idno) VALUES(?, ?, ?)");
$query->bindparam(1, $name);
$query->bindparam(2, $file);
$query->bindparam(3, $idNo);
try {
$query->execute();
if ($query) {
echo "success!! ";
} else {
echo "Failure conncting db!";
}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
I know that if $query->execute(); returns true than the data was inserted.
How can I notify the user that the data was really inserted to the database?
Even pass the user to a new page is an option.
Actualy, redirect the user to a new page will be great!
Hi you need to add in the function insert_data on the try{ at the end} a echo of your success to send to ajax script as response so a simple.
$success['success'] = "You request just sending to the server ...";
echo json_encode($success);
In your fonction ajax
xhr.onload = function(data) {
console.log(data);
console.log(data.success);
};
You need to adapt, this method show you how send data PHP to JS regards.
You can also send the response inside a "body" key-value pair, and put the success/error indication inside the HTTP status code:
$success["body"] = "You request just sending to the server ...";
header("HTTP/1.1 200 OK", true, 200);
And receive it in js:
xhr.onload = function(data) {
console.log(data.status);
console.log(data.body);
};
see:
Set Response Status Code
or:
http://php.net/manual/de/function.http-response-code.php
explanation of codes:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I have this javascript file that is calling a php file to return a JSON string. Chrome dev tools is throwing the error at line 10 in the javascript code. I know the error relates to a missing bracket but for the life of my and 3 other people who have looked at it the syntax is correct.
var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
json = JSON.parse(request.responseText);
for(var x = 0; x < json.length; x++){
var list = new listingInfo();
list.category = json[x].category;
list.date = json[x].dateListed;
list.description = json[x].description;
list.id = json[x].listingID;
list.title = json[x].title;
list.userID = json[x].userID;
listings.push(list);
}
}
console.log(listings);
}
here is the php file
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("GregsList", $con)
or die("Unable to select database:" . mysql_error());
$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");
#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
#If you want to see if correct json is printing use ---> print json_encode($rows);
return json_encode($rows);
?>
request.readyState == 4 is not enough you should add request.status== 200
In your php script replace return json_encode($rows); with print json_encode($rows);