I'm trying to INSERT INTO a database using ajax. The table is updated by the php file, but I always get an error in ajax and the page could not be redirected to the results page.
My 'POST' function, in the html page is (it returns always the error alert):
function enviaFormDetalhes() {
if (confirm("Tem a certeza que quer gravar os dados?")){
$.ajax( {
type: 'post',
url: 'php/f_propostas.php?tipo_acao=grava_nova_proposta&id_consulta='+getUrlVars()['id_consulta']+'&id_fornecedor='+getUrlVars()['id_fornecedor'],
data: $("#form_detalhes_proposta").serialize(),
success: function(data) {
alert("Dados gravados com sucesso");
location.href = 'f_editproposal.html?id_proposta='+data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
} );
} else {
return false;
}
}
The part of php file is: (This is working good, if I call i directly in the browser it returns me the lastinsertID):
case "grava_nova_proposta":
$ID_Fornecedor = $_GET['id_fornecedor'];
$ID_Consulta = $_GET['id_consulta'];
$DataRececao = $_POST['dt_proposta'];
$RefProposta = $_POST['ref_proposta'];
$DtValidade = $_POST['dt_validade'];
$DtCriacao_loop = gmdate('Y-m-d');
try {
$sql = "INSERT INTO fornecedores_propostas (
id_fornecedor,
id_contacto,
id_consultaloop,
datarecepcao,
ref_proposta,
validadeproposta)
VALUES (?, ?, ?, ?, ?, ?)";
$q = $conn->prepare($sql);
$q->execute(array($ID_Fornecedor, $ID_Contacto, $ID_ConsultaLoop, $DataRececao, $RefProposta, $DtValidade));
$Ultimo_ID = $conn->lastInsertId('id_proposta');
echo $Ultimo_ID;
break;
try
url: 'php/f_propostas.php,
data: tipo_acao=grava_nova_proposta&id_consulta='+getUrlVars()['id_consulta']+'&id_fornecedor='+getUrlVars()['id_fornecedor']+$("#form_detalhes_proposta").serialize(),
Related
I submit a php form using jquery ajax, but when receive a parameter value of callback function success, the parameter value contains enter key in front of the value returned from the server.
The work around, I use includes method.
Does anyone know why the enter key inserted in front of the value returned from the server?
$.ajax({
type: "POST",
url: "_action.php",
data: dataString,
success: function(result) {
n = result.includes("success");
if (n) {
grecaptcha.reset();
$("#spinner-contact").remove();
$('#success_msg').html("<img class='img-fluid aligncenter mb-3' id='checkmark' src='media/img/form_submitted.jpg' />");
}
else {
grecaptcha.reset();
$("#spinner-contact").remove();
$('#success_msg').html("<div class='mt-3'><strong><h1 class='alert alert-warning'>Contact failed!</strong> Please submit again.</h1></div>");
}
}
});
$statement = runQPs("INSERT INTO my_guestbook(title, url, path, pos, content, isactive, date) VALUES(
?, ?, ?, ?, ?, ?, ?
)",[$name, $email_from, $address, $telephone, $comments, 0, $now]);
// Insert contact success or fail
if($statement->affected_rows === 0) {
$result = "fail";
}
else {
$result = "success";
}
echo $result;
In PHP code you can return value like that:
return json_encode(result);
In JS file:
success: function(result) {
// this will be your response from PHP code
// add you'r IF statement here
console.log(result);
}
i think, u can change your "echo" in php file to return "json"
and in your ajax code:
n = result.includes("success");
to
var response = result.message(name of return json);
After echo the result variable you can die the statement something like that.
echo $result;die;
or
die($result);
Within my application I have an Ajax function that adds information to a database. Everything worked perfectly until I added in 2 more parameters which was location and username.
It still works with everything else but it doesn't add those last 2 into the database. The names of within the database is location and username. assignedUsername and storeLocation are set else where in the code.
Ajax:
$("#send").click(function(){
$.ajax({
type: 'POST',
contentType: "application/json",
data: orderFood(),
url: rootURL + "/orderFood",
dataType: "json",
success: function(data)
{
alert(assignedUsername);
alert("Data Added");
$.mobile.changePage("#mainMenu");
},
error: function(data)
{
alert(assignedUsername);
alert("Data NOT Added");
$.mobile.changePage("#mainMenu");
}
});
});
function orderFood()
{
alert(storeLocation + ", " + assignedUsername);
return JSON.stringify({
"food1": food1,
"food2": food2,
"food3": food3,
"food4": food4,
"food5": food5,
"food6": food6,
"food7": food7,
"food8": food8,
"food9": food9,
"location": storeLocation,
"username": assignedUsername
});
}
PHP:
$app->post('/orderFood/', 'orderFood');
function orderFood()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "INSERT INTO subsordered(food1, food2, food3, food4, food5, food6, food7, food8, food9, location, username) VALUES (:food1, :food2, :food3, :food4, :food5, :food6, :food7, :food8, :food9, :location, :username)";
try
{
$db = getConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("food1",$q->food1);
$stmt->bindParam("food2",$q->food2);
$stmt->bindParam("food3",$q->food3);
$stmt->bindParam("food4",$q->food4);
$stmt->bindParam("food5",$q->food5);
$stmt->bindParam("food6",$q->food6);
$stmt->bindParam("food7",$q->food7);
$stmt->bindParam("food8",$q->food8);
$stmt->bindParam("food9",$q->food9);
$stmt->bindParam("location",$q->location);
$stmt->bindParam("username",$q->username);
$stmt->execute();
$db = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
I know the PHP is correct though testing with cURL but I thought I'd include it just to get the whole picture
I am extremely stuck with this, from what I can see it SHOULD work but it just doesn't
I want to store an image as a blob into my database(MySQL) while using PHP Rest service, but I dont know how to do it. Here is my PHP code (I'm using Slim framework for PHP)
function addProblem() {
global $app;
$postdata = file_get_contents("php://input");
$req = json_decode($postdata); // Getting parameter with names
$paramName = $req->station; // Getting parameter with names
$paramAdres = $req->address; // Getting parameter with names
$paramCity = $req->city;// Getting parameter with names
$parampostal = $req->postalcode;
$parampic = $req->pictureOfDamage;
$paramdescrip= $req->description;
$sql = "INSERT INTO problems (Station,Address,Postalcode,City,PictureOfDamage,Description) VALUES (:station,:address,:postalcode,:city,:pictureOfDamage,:description)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':station', $paramName);
$stmt->bindParam(':address', $paramAdres);
$stmt->bindParam(':city', $paramCity);
$stmt->bindParam(':postalcode', $parampostal);
$stmt->bindParam(':pictureOfDamage', $parampic);
$stmt->bindParam(':description', $paramdescrip);
$stmt->execute();
$dbCon = null;
echo json_encode("toegevoegd ");
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this is my angular code (i'm using fileuploader right now.)
.controller('MeldingController', function ($scope, $upload, $rootScope, $state, $http) {
$scope.station = $rootScope.station;
$scope.PictureOfDamage;
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var pictureOfDamage = files[i];
return pictureOfDamage;
}
}
}
$scope.submit = function () {
console.log($scope.PictureOfDamage);
var data = {
station: $scope.station.name,
address: $scope.station.streetName,
postalcode: $scope.station.postalCode,
city: $scope.station.city,
pictureOfDamage: $scope.upload($scope.files) /* picture*/,
description: document.getElementById("Description").value
}
console.log('NOJSN ', data);
data = JSON.stringify(data);
console.log('JSON', data)
$http({
method: "POST",
url: 'http://localhost/Dats24/problem/add/',
data: data})
.success(function (data, status, headers, config) {
$state.go('GoogleMaps');
}).error(function (data, status, headers, config) {
console.log(data);
});
};
})
For your angular application, you can use the upload method of the $upload service like this:
file_upload: function(file) {
return $upload.upload({
url: 'http://your-upload-url/',
file: file
});
}
as described in here : https://github.com/danialfarid/ng-file-upload
Then on your service in PHP, you can get the file using
move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
It will store the file on the path of your choice, then you can use PHP to do whatever you want with the file data.
I have a small problem, which is that when I add my prepared statement into the PHP file, the Ajax stops working and gives me a 500- error, but when I remove the statement, it works like a charm.
This is my PHP file:
<?php
include ('db_connect.php');
include ('functions.php');
$datad = $_POST['superstr'];
$id = 1;
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
echo $datad;
?>
and my Ajax looks like this:
$.ajax({
url: 'includes/sendlyrics.php',
type: 'POST',
data: {superstr: 'pelle'},
success: function(data) {
//called when successful
var hello = data;
//prompt(data);
console.log("The data is:");
console.log(data);
console.log("The variable which should keep the data has this content:");
console.log(hello);
},
error: function(e) {
//called when there is an error
console.log(e.message);
prompt(e.message);
//alert(e.message);
}
});
What's the problem?
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();
Is wrong. Amend this to:
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$stmt->execute();
If you are looking for confirmation of the query executing successfully you can test this by:
if($stmt->execute()){
//returned true - statement executed successfully
} else{
//returned false
}
Also you should modify your Ajax call to something similar to:
$.ajax({
url : "your/url/here.php"
type : "POST",
data : {superstr: 'pelle'},
dataType : "json",
success : function(data){
//do something with the response
},
error : function(jqXHR, textStatus, errorThrown){
//handle the error
}
});
By adding a dataType of json, you should then ammend the echo statement of your .php file to read:
$response = Array();
array_push($response, $datad);
echo json_encode($response);
I'm sure you've read the documentation online already, but Ajax can be found here, and prepared statements here.
This is all written with the caveat that your DB connection is valid...which it would appear to be given the wording of your question, and your previous attempts at solving the issue.
I am trying to write some data to a MySQL Table however the .post call is returning with a 500 server error. Any help in the right direction would be great.
I think it's something to do with the _POST variables not sending right.
Here is the code:
JS:
function write_table(response) {
var data = {
'user_id' : response.id,
'user_email' : response.email,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!');
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$host = 'localhost';
$un = 'root';
$pw = 'root';
$db = 'bikelouis';
$user_id = $_POST['user_id'];
$user_email = $_POST['user_email'];
$user_first = $_POST['user_first'];
$user_last = $_POST['user_last'];
$conn = mysql_connect($host, $un, $pw) or die(mysql_error());
if ($conn) {
echo '<script> alert("connected!");</script>';
mysql_select_db($db) or die(mysql_error());
$sql = "INSERT INTO users (user_id, user_email, user_first, user_last) VALUES ($user_id, $user_email, $user_first, $user_last)";
} else {
echo 'Connection failed.';
}
?>
I am using facebook connect, that is where 'response' is coming from. That works perfectly.
jQuery Side
$.post() is simply a wrapper for $.ajax() so if you want a little more control and visibility into what's going on, I'd highly suggest using $.ajax() instead.
The data argument for $.post() should be an object of key/value pairs and not a list. That said, I'm not sure what throwing the data object into the user_info list accomplishes, and this may be the root of your problem.
Try this and let me know how it works out for you:
function write_table(response) {
var data = { // This is the format $.post() expects.
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.post('./includes/php/login_facebook.php', data, function(result, status, xhr) {
console.log(status, result);
});
}
The same request, performed through $.ajax():
function write_table(response) {
var data = {
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!',
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP Side
First off, I'd highly recommend opening PHP with <?php rather than <?, as the later is not enabled on all set ups.
Secondly, instead of receiving an Internal Server Error, actually displaying the errors in the browser is so much cleaner. At the beginning of any PHP script you wish to display potential errors on, include the following:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
As for the 500 Internal Server Error you're receiving, it's most likely because you're missing a $ in front of $_POST on line 8.
Instead of:
$user_id = _POST['user_id'];
It should read:
$user_id = $_POST['user_id'];
Inserting
All variables should be encapsulated in ticks / apostrophes.
It's also a great idea to escape the values, to prevent SQL injection attacks:
Try this:
$sql = "
INSERT INTO users
(user_id, user_email, user_first, user_last) VALUES (
'" . mysql_real_escape_string($user_id) . "',
'" . mysql_real_escape_string($user_email) . "',
'" . mysql_real_escape_string($user_first) . "',
'" . mysql_real_escape_string($user_last) . "'
)
";