i'm trying to understand this error but i dont how to solve it
this is my JS code:
$.ajax({
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
type: "POST",
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
complete:function(data)
{
resposta = data;
console.log(resposta);
}
});
this is my php code:
$serverName = $server;
$uid = $uid;
$pwd = $pass;
$connectionInfo = array( "UID" => $uid, "PWD" => $pwd,"Database"=>"Portal");
//$connectionInfo = array("Database"=>"Portal");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$Pname = $_POST["Pname"];
$Uname = $_POST["Uname"];
$email = $_POST["email"];
$Ename = $_POST["Ename"];
$Sigla = $_POST["Sigla"];
if( $conn )
{
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla)";
if (mysqli_query($conn, $sqlCliente)) {
echo "New record created successfully";
} else {
echo "Error: " . $sqlCliente . "<br>" . mysqli_error($conn);
}
}
when i do console.log of data, give me this:
what is wrong with my code?
Try to change into $sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ('$Ename', '$Sigla')";
I think problem with your sql insert statement.
$sqlCliente = "INSERT INTO Portal.dbo.Empresa(Ename,Sigla) VALUES ($Ename, $Sigla)";
OR
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla,..... Add all parameters to here)";
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
This line is incorrect.
PHP files need a server to get executed. By the looks of your path, it looks like you have hosted in IIS. IIS doesn't suppport PHP by default - so assuming you have installed PHP and configured properly, read below.
You don't post to the physical path of the PHP file, rather URL of the PHP.
Therefore, it should look something similar to:
url: localhost/VisionwareHelp/php/CriaUserEempresa.php',
Until you fix the URL to the correct one, none of your posting code will work correctly.
If you have not installed PHP on IIS, then you need to download and install a PHP-enabled server like 'WampServer' and host your PHP in that.
Also, read below articles - it will help to improve your knowledge.
Installing and Testing Wampserver
Beginner’s Guide to Ajax Development with PHP
In Ajax, The correct syntax of sending multiple data is: http://api.jquery.com/jQuery.ajax/
So, Replace
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
with
data: {'Pname':Pname, 'Uname':'Uname', 'email':email, 'Ename':Ename, 'Sigla':Sigla },
And this line url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php', is also incorrect.
replace
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
with
url: 'Php/CriaUserEempresa.php',
Hope it will help you..
Related
I tried to store a JavaScript array into MySQL table using PHP, see the following script below.
I first converted the string using JSON.stringify and passed it into a PHP file via AJAX request.
I then converted it to a PHP array, and after after I inserted those arrays using serialize();.
Finally, it properly stored using localhost but it does not work on my live server.
sample.Js
$.ajax(
{
type: "POST",
url: "save_plan_ajax.php",
data: {plan: plan,totalInvesment: totalInvesment, location: JSON.stringify(locationsArr), cost: JSON.stringify(cost), personalised: JSON.stringify(personalised)},
success: function(data){
//alert(data);
}
}
)
In this above script I passed the JavaScript array into save_plan_ajax.php using JSON.stringify.
save_plan_ajax.php
<?php
session_start();
include 'config.php';
if(isset($_POST)){
$planname = $_POST['plan'];
$cost = json_decode($_POST['cost'], true);
$personalised = json_decode($_POST['personalised'], true);
$locations = json_decode($_POST['location'], true);
$userid = $_SESSION['BIID'];
$constriant = $_SESSION['CONSTRAINT'];
$created_date = date("Y-m-d H:i:s");
$total_invs = $_POST['totalInvesment'];
$query = "INSERT INTO `plans` (
`refid` ,
`userid` ,
`plan_name` ,
`cost` ,
`locations`,
`personalised` ,
`total_invs`,
`constriant` ,
`created_date` ,
`stat`
)
VALUES (
NULL , '$userid', '$planname', '".serialize($cost) ."', '".serialize($locations)."','".serialize($personalised)."', '$total_invs', '$constriant', '$created_date', 'A'
)";
$res = $GLOBALS['Db']->Insert($query);
if($res){
echo $res;
}
else{
echo "Error";
}
}
?>
In the above script, the record stores correctly at local server, but in this same script insert N; in server.. how do I fix this error, is the above way correct?
In the MySQL database table I have set the cost, location and personalized fields datatype as LONGTEXT.
I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}
I'm using ajax to send a search string to a php script that executes a mysql like function to find all related entries with the username like the string being sent for friend searching. I have two current entries in the database zukeru and zukeru2. when i search z i only get zukeru returned in my console output. When i search 2 i still get zukeru and im really not sure why.
Also how to i remove a specific field from a php nested tupple. I don't want to include the password field for obvious reason. Sorry im new to php learning as i go so far its not as bad as I thought it would be kinda similar to python.
returned object when searching the number 2, but i get zukeru and not zukeru2 doesn't make sense.
Object {0: "2", 1: "you wish you could see", 2: "zukeru", 3: "deleted for security", 4: "grant", id: "2", email: "deleted for security", username: "zukeru", password: "deleted for security", name: "grant"}
this is the search string i used for the above result. You can see i searched 2 and got back zukeru and not zukeru2
profile.php:92 searchstring=2
<?php
$db = new mysqli(security reasons removed.);
extract($_POST);
//I think i can remove this session start ?
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=mysqli_fetch_array($fetch);
//echo $search_string
echo json_encode($friends);
?>
Here is my jquery incase you wanted to see
function search(){
var url = "search_friends.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_friends").serialize(), // serializes the form's elements.
success: function(data)
{
//console.log(data);
var returned_friends = JSON.parse(data);
var html_built = '<br>';
console.log(returned_friends);
console.log($("#search_friends").serialize());
if (returned_friends){
$.each( returned_friends, function( key, value ) {
if (key =="username"){
html_built += '<li><a href="#"><button class="btn btn-primary" style="width:100%;" id="'+value+'" onClick="add_friend(this.id)"> Send '+value+' A Friend Request</button></li>';
}
});
}
html_built += ""
document.getElementById("list_friends").innerHTML = html_built;
}
});
return false;
}
this is what im currently using and I get undefined method. It cant find fetch_all(); and im using php 5.4
here is the console error returned.
<br />
<b>Fatal error</b>: Call to undefined method mysqli_result::fetch_all() in <b>/home/gzukel/public_html/search_friends.php</b> on line <b>7</b><br />
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends=$fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
?>
so something like this?
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=[]
while($row = $fetch->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
array_push($friends,$row['username']);
}
//echo $search_string
echo json_encode($friends);
?>
You Could use fetch all:
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends= $fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.
I'm a student who is doing an app with jQueryMobile and gonna be compiled with Phonegap. I want to posting data to a server using jQuery but I have problems loading my .php file in the server.
I have the last version of jQuery.
Here I put my script for post the data from a form:
$(document).ready(function() {
var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
$.ajax({
type: 'post',
data: postData,
url: 'http://www.smartweb.cat/app/Habana/user_register.php',
success: function(data) {
alert('Usuari registrat correctament.');
},
error: function() {
alert('Hi ha algun problema amb el registre.');
}
});
return false;
});
});
Thanks a lot and sorry for my english wrinting.
Your post data are empty. You retrieve them directly when the DOM is loaded and not when the form is submit. You should move your var postData.
$(document).ready(function() {
//var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
var postData = $('#registerForm').serialize(); // here
$.ajax({
//...
});
});
});
First of all I want to say that you should use prepared statements.
Althought you sanitize user input(GOOD) its still recommended using prepared statements.
Not only does it help with readability its also more secure.
Make sure your form sends following postdata:
{name:"YourName", surname:"Yoursurname",date:"<dateobject>",email:"sample#mail.com",user:"username",password:"password}
== THIS LOOKS OK ==
$name = mysql_real_escape_string($_POST["name"]);
$surname = mysql_real_escape_string($_POST["surname"]);
$date = $_POST["date"];
$email = mysql_real_escape_string($_POST["email"]);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
enter code here
If the conditions above are the same the server should receive all your data. I do see a problem in your query that may be the problem.
What you are doing is inserting everything as string in the database. You have to make sure when you try to execute a query given values for a table that the given values correspond with the database.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
('$name', '$surname', '$date', '$email', '$user', '$pass')"); //insert
Make sure everything is correct for example your date column in the database is it a string or a mysql date TYPE. Try to lose the '.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
($name, $surname, $date, $email, $user, $pass)");