how to send data from angularJS controler to PHP using Json - javascript

well i have this problem about sending multi data from JS to PHP, i'm using angularJS. the problem is i can't receive any data, i'm a beginner in this stuff like AngularJS.this my my JS part:
var data = {"name":name, "cin":cin, "job":job};
var config = {
params: data,
headers: { 'Content-Type': 'application/json' }
};
$request = "php/readFromDatabase.php";
$http.post($request, config).then(function (response) {
$scope.collectionData = response.data.records;
});
this should be fine and work i have my data as struct (object) the name and cin and job are variables when i click button using angularJS controller this function should be launched and call an PHP file :
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
$name = $_POST['name'];
i use those information to look for data in database and then i echo them as JSON format for that i want to use $http.get{} so i can call the response.data.records and not to use the $ajax.{}.
the problem is this $_POST['name'] doesn't work;
even this didn't work:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
As i said, i'm new here so plz tell me what i'm doing wrong because i didn't find anything that can help me, i tied everything i have found in internet.
hope if someone can help me and thank you in advance.
Edit :
this is my JS file:
app.controller('shearch_data', function ($scope, $http) {
$scope.ShearchFunction = function () {
var name = " ";
if ($('#toggle_name').prop('checked') == true)
name = $('#inputName').val();
var cin = " ";
if ($('#toggle_cin').prop('checked') == true)
cin = $('#inputCIN').val();
var job = " ";
if ($('#toggle_job').prop('checked') == true)
job = $('#inputJob').val();
var data = {'name': "ffss", 'cin': cin, 'job': job};
var url = "php/readFromDatabase.php";
$http.post(url, data).then(function (response) {
$scope.collectionData = response.data.records;
}).catch(function (err) {
alert('something went wrong')
});
};
});
my PHP :
<?php
header("Access-Control-Allow-Origin: *");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$cin = $request->cin;
$job = $request->job;
$output = "";
$output .='{"Name":"'.$name.'",';
$output .='"Job":"'.$job.'",';
$output .='"Cin":"'.$cin.'"}';
$output = '{"records":[' . $output . ']}';
echo($output);
this is what i'm trying to do for test, send data from JS to PHP using http.post then i receive it as json, it's jsut for test for now.

Arguments and config are wrong for $http.post( url, data, config)
Remove params from config, those are for GET url query string params
EDIT: if all you are setting is the 'Content-Type header you don't need a config....application/json is the default
var config = {
headers: { 'Content-Type': 'application/json' }
};
var url = "php/readFromDatabase.php";
$http.post(url, data, config).then(function (response) {
$scope.collectionData = response.data.records;
}).catch(function(err){
alert('Ooops...something went wrong')
});

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

How to post text variable in angular to mysql trough php

so I have a little bit tricky or rather say odd situation.
I have php and mysql database, for frontend I am using angular.js
So I am creating service, that sends data, via post request to php.
So everything is working properly when I am sending input values via name html attribute.
But problem appears when I am trying to send hardcoded text variable from for loop.
I know it's very hardcoded way for doing it but i don't know how to do it differently.
So here is my php
<?php
$conn = mysqli_connect('localhost','nemkeang','nemkic23','interventure');
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$text = $_POST['first_name'];
$text2 = $_POST['last_name'];
$text3 = $_POST['date'];
$text4 = $_POST['author'];
$text5 = $_POST['note'];
$text6 = $_POST['skill'];
$target = "/assets";
$target = $target . basename( $_FILES['cv_file_name']['name']);
//This gets all the other information from the form
$file_name= $_FILES['cv_file_name']['name'];
$file_name2= $_FILES['cv_file_name']['name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['cv_file_name']['tmp_name'], "./".$file_name)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['cv_file_name']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
}
$sql = "INSERT INTO user (first_name, last_name, skill, date, cv_file_name, cv_url, author, note)
VALUES ('$text','$text2','$text6','$text3','$file_name','$file_name2','$text4','$text5')";
if (!mysqli_query($conn,$sql)) {
die('Error: ' . mysqli_error($conn));
}
else {
echo "success";
}
mysqli_close($con);
?>
The php is working correctly it's sending data, but on the $text6 = $_POST['skill']; problem arrives.
So here is my angular service first
app.service('testpost',['$http',function($http){
this.saveRecipe = function(postdata){
let payload = new FormData();
payload.append("first_name", postdata.first_name);
payload.append('last_name', postdata.last_name);
payload.append('date', postdata.date);
payload.append('cv_file_name', postdata.cv_file_name);
payload.append('author', postdata.author);
payload.append('note', postdata.note);
payload.append('skill', postdata.skill);
return $http.post('login/post.php', payload, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
})
}
}]);
And it's also working correctly, when i log it to console, it shows correct values. Just don't send payload.append('skill', postdata.skill); value to php.
Here is my controller
app.controller('newUser',['$scope','$filter','testpost', function($scope,$filter,testpost) {
$scope.postdata = {}
$scope.arr = [];
let bar = document.getElementsByClassName('md-chip-content');
this.saveRecipe = function(postdata) {
for(var i = 0; i < bar.length; i++) {
$scope.arr.push(bar[i].innerText);
}
let skills = $scope.arr;
postdata.date = $filter('date')(postdata.date, "MM/dd/yyyy").split('/').join('-');
postdata.skill = skills[0];
postdata.skill2 = skills[1];
postdata.skill3 = skills[2];
postdata.skill4 = skills[3];
testpost.saveRecipe(postdata).then((data)=>{
console.log(data);
})
error:(err) =>{ return false};
}
}]);
Just to be clear i just want the value from postadata.skill to be sent to mysql via php. And I think the problem is in php because the value don't come from input type.
I hope that I've explained everything well. Thanks in advance.

Uncaught SyntaxError: Invalid or unexpected token. Google API Translate

I am the beginner, so do not have much experience.
The task is to translate the blocks of text the user writes.
So html-file:
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = JSON.stringify("{$text_without_adv}");
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: $.parseJSON(text_var)
}).done(function(data) {
console.log(data);
});
});
</script>
php-file "gTApi.php" (where the magic happens):
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = file_get_contents('php://input');
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];
another php-file:
$smarty->assign('text_without_adv', htmlspecialchars((implode(' ', $text_array))));
after the page loads I get unexpected token after the first sentence in variable $text_without_adv and can't do the translation, nothing happens when I click the button.
For example:
var text_var = JSON.stringify ("
But she had a sweetheart, and he said he would go and get the ball. ///token/// So he went to the park gate, but 'twas shut; so he climbed the hedge, and when he got to the top of the hedge, an old woman rose up out of the dyke before him, and said, if he wanted to get the ball, he must sleep three nights in the house. He said he would.");
But the main question is that there can be no errors in other posted texts from other users. I can't understand, 3 different texts from 3 different users have unexpected token, then the next 2 have no error, then the next one has the error and so on. Where could be the problem?
In this case you don't need to pass a json instead just pass a post data
To do that
First change this line
// to stored your php variable in a js variable
var text_var = "<?php echo $text_without_adv; ?>";
then
in your ajax
$.ajax({
method: 'post',
url: own_script,
data: {
// just use the declared js variable above which contains your php variable at the first place
text: text_var
}
}).done(function(data) {
console.log(data);
});
and in your php
instead of
$text = file_get_contents('php://input');
change to
$text = $_POST['text'];
so your code would be like this
JS
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = "<?php echo $text_without_adv; ?>";
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: {
text: text_var
}
}).done(function(data) {
console.log(data);
});
});
</script>
PHP
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = $_POST['text'];
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];

Convert form data from json to php mysql

I am new to json, I have tried to post my form values from json to update mysql database. When I submit I have a success alert but when I view my database seems my values are not been passed through infact leaving my most of my fields blank. Need assistance in passing my form data to my database using json and php.
JAVASCRIPT
$('#save').on('click', function () {
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data: {
detailid: id,
titleid: $('#selectmenu').val(),
name: $('#txtname').val(),
surname: $('#txtsurname').val(),
contact_no: $('#txtcontact_no').val(),
email: $('#txtemail').val(),
category:$('#txtcategory').val(),
package: $('#txtpackage').val(),
password: $('#txtpassword').val()
},
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
alert("Your details we not saved");
} else {
//alert a success message
alert("Details Updated");
location.href='profiledetails.html?id='+id;
}
}
});
});
PHP
require_once("database.php");
$mydb = new MySQLDatabase();
//set varables from json data
$id = json_decode($_POST['detailid']);
$titleid = json_decode($_POST['titleid']);
$name = json_decode($_POST['name']);
$surname = json_decode($_POST['surname']);
$contact_no = json_decode($_POST['contact_no']);
$email = json_decode($_POST['email']);
$category = json_decode($_POST['category']);
$package = json_decode($_POST['package']);
$password = json_decode($_POST['password']);
$mydb->query("UPDATE tblprofile SET title_fk = '$titleid',`name` = '$name',surname = '$surname',contact_no ='$contact_no',email = '$email',category_fk = '$category',package_fk = 'package_fk' ,`password` = 'password' WHERE id = '$id' ;");
$mydb->close_connection();
No need to decode the data. They will be posted as normal post data. Access them by simply -
$id = $_POST['detailid'];
you dont need to json_decode the value from the $_POST.
change you code to this
$id = $_POST['detailid'];
$titleid = $_POST['titleid'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$contact_no = $_POST['contact_no'];
$email = $_POST['email'];
$category = $_POST['category'];
$package = $_POST['package'];
$password = $_POST['password'];
Although you are sending json via the ajax call but in doesn't come encoded in the server
Unless you send the data in JSON format from client side, don't use json_decode()
Ex:
In ajax call, instead of the data:{}
if you try to send in this way,
var Jdata = JSON.parse("{'detailid':'"+id+"'");
$.ajax({
type: "POST",
url: "http://localhost/v_warehouse_1/inc/updateprofile.php",
data:Jdata,
datatype: "json",
success: function (status) {
//your stuff..
}
});
then go for using json_decode() in php

Return the uploaded file contents as JSON

I'm using angularjs to upload files. Im using this model that I've found at github:
https://github.com/danialfarid/angular-file-upload
The upload works perfect. However, after I've uploaded the file, I want to return the file contents as JSON, and then iterate of the JSON-object with Angular. But I don't know how to do this.
Here is my code:
$filename = $_FILES['file']['tmp_name'];
$csv = array_map('str_getcsv', file($filename));
foreach($csv as $c)
{
echo str_replace(array('"', ';'), ' ', $c[0]) . "\n";
}
//Return as JSON here? HOW?
Here is my controller:
as.controller('Marketing', function($scope, $http, $upload)
{
$scope.onFileSelect = function($files) {
var file = $files[0];
if (file.type.indexOf('image') == -1) {
$scope.error = 'image extension not allowed, please choose a JPEG or PNG file.'
}
if (file.size > 2097152){
$scope.error ='File size cannot exceed 2 MB';
}
$scope.upload = $upload.upload({
url: 'partials/result.php',
data: {},
file: file,
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
$scope.result = data;
});
}
});
I want the data to be and JSON-object. How can I accomplish this? When I try json_encode with PHP, it does not work.
Anyone who can help me with this?
I believe this is what you're looking for
if(isset($_FILES["file"])){
$fname = $_FILES['file']['tmp_name'];
// ...
if(move_uploaded_file($fname, "uploads/" . $fname)){
// this way
$csv = file_get_contents($fname);
$array = array_map("str_getcsv", explode("\n", $csv));
echo json_encode($array);
// or this way; have in mind delimiter
$row = str_getcsv($csv, "\n");
$length = count($row);
for($i = 0; $i < $length; $i++){
$data = str_getcsv($row[$i], ";");
$array[] = $data;
}
echo json_encode($array);
}
// ...
}

Categories