$.ajax jquery to php script that stores in mysql - php

I have this code in jquery:
$.ajax({
type: "POST",
url: "tosql.php",
data: {textnode: textnode},
success: function(){
alert( "Data Saved: " );
}
});
and this php script:
<?php
$textnode = $_POST['textnode'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("repository", $con);
mysql_query("INSERT INTO paragraphs (paragraphs) VALUES ('$textnode')");
mysql_close($con);
?>
When I go to mysql to view if the array was stored, I see "Array" as the value. What I'm trying to do is store each value in the array into its own row also. Serialize didn't work in this case.

Edited:
if(get_magic_quotes_gpc())
$magic = 1;
else
$magic = 0;
foreach($textnode as $key => $value) {
if($magic == 0){
$value = mysql_real_escape_string($value, $con);
}
else{
$value = stripslashes($value);
$value = mysql_real_escape_string($value, $con);
}
mysql_query("INSERT INTO paragraphs (paragraphs)
VALUES ('$value')");
}

Related

Send GET in Ajax call and PHP script

I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType

Mysql TEXT defined field not read

I have a MYSQL table that has a column defined as TEXT, when i reading the contents into PHP the result is that the data is not being pulled through.
my php code
SELECT establishments.name AS estName,
establishments.address AS estAddr,
establishments.telephone_num AS estTel,
establishments.description AS estDesc,
establishments.Logo AS estLogo,
establishments.title AS estTitle
FROM bucurestideals1.establishments
WHERE establishments.establishment_id ="'.$est_id.'"';
The table row has data so this is not an issue, i am reading the data using php as below:
$.ajax({
type: 'GET',
url: pass_url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
// Assign the returned data to the page
$.each(data, function(i,item)
{
alert(item.estDesc);
});
},
Update: PHP Code
<?php
header('Content-type: application/json');
$est_id = $_GET['id'];
$server = "*";
$username = "*";
$password = "*";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
You can probably remove the quotes from your where statement. If that is not the issue, can you post the php code that you use to execute the sql?

Comparing $.ajax result

I would just like to know how to go about comparing the resulting echo from a $.ajax call in JavaScript. I attempted this and even though I get 1, it doesn't actually compare the results correctly.
jQuery:
$.ajax({
type: "POST",
url: "login.php",
data: user,
dataType: 'html',
success: function(result)
{
alert(result);
if(result == '1')
{
alert("logged in :D");
//document.location.replace('home.php');
}
else
{
alert("not logged in :<");
}
},
failure: function()
{
alert('An Error has occured, please try again.');
}
});
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$password = $jsonobj->password;
$email = $jsonobj->email;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT 1 FROM users WHERE email = '"
. $email . "' AND password = '" . $password . "'");
while($info = mysql_fetch_array( $result ))
{
if($info[0] == 1)
{
echo '1';
}
}
?>
There's probably a space or line break after the '1' that is echoed. Check if there's no space before the opening <?php tag and remove the closing ?> tag (you're allowed to do that, and it will prevent accidental whitespace being outputted.
You should be able to check by changing the javascript to:
alert('X' + result + 'X');
You'll see soon enough if there's any whitespace around result.
try to send json response
php:
echo json_encode(array(
'status' => 'ok',
));
js:
dataType : "json",
success : function(response) {
if (response.status == "ok") {
alert('success');
} else {
alert('error');
}
}

PHP jQuery AJAX

Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.

jQuery and MySQL

I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)

Categories