jquery ajax to php script not saving data - javascript

I have the following jQuery ajax call to a php script:
actualHtml = $('div').html(); // could this line be causing an issue?
$.ajax({
type: 'POST',
url: 'save-html-css-action.php',
data: {
'htmlTextToSave': htmlTextToSave,
'actualHtml': actualHtml,
'userId':userId
},
success: function(msg){
alert(msg);
}
});
php:
$htmlCssToSave = $_POST['htmlTextToSave'];
$userId = $_POST['userId'];
$actualHtml = $_POST['actualHtml'];
$mysqli = new mysqli($servername, $sqlusername, $sqlpassword, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
//printf("Connect failed: %s\n", mysqli_connect_error());
echo "Connection failed: ".mysqli_connect_error();
exit();
}
$mysqli->query("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values ('".$htmlCssToSave."',".$userId.",'".$actualHtml."')");
echo "success";
/* close connection */
$mysqli->close();
but when I check the database, the data isn't there. Am I doing something wrong in the jquery/php combo (meaning the ajax call)? I'm getting a javascript "success" alert, so it's hitting the script, but I'm not sure why the info isn't being inserted.
The table datatypes are medium text for both the htmlcsstosave and the actualhtml columns, and int for userid (not the primary key, this is a foreign key to another table)
so I added a an error alert and this is the output
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'margin-0'>
<head>
</head>
<body cl' at line 1

As we discussed, the issue is with escaping and sanitizing data. If you used prepared statements, it will handle it for you. let's have a look at how that would work:
Prepare the statement:
$stmt = $mysqli->prepare("INSERT INTO user_saved_data (user_html_css_code, dd_id, actual_html) values (?,?,?)");
Bind your parameters:
$stmt->bind_param('sis', $htmlCssToSave, $userId, $actualHtml);
Then execute your statement:
$stmt->execute();
Then you should be good to go. The prepared statement should handle the data sanitization for you now.
Resouces:
mysqli prepare
mysqli bind_param
mysqli execute

Can you post the CREATE TABLE statement for the user_saved_data table?
In general, I'd recommend just tracing it through and see where the data gets lost.
For example, can you echo the query you are generating and run in manually in MySQL? You may have a syntax error in the SQL being generated...

Related

javascript when you have to pass in an url as a parameter to mysql using jquery ajax and php how to do this and process return data?

I've got a piece of javascript as follows:
$.ajax({
type:"get",
url:"http://www.orc23.com/get.php",
data: { solution: src },
datatype: "json",
success: function(returndata){
alert(returndata);
}
});
And this is the corresponding php file that interacts with mysql:
<?php
$con = mysqli_connect("orc23com.fwdsfawmsdfaysql.com","ssft","dsfss123","cookies");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db($con, "cookies");
$sql="SELECT SOLUTION FROM requests WHERE theurl = '$_GET[solution]')";
$result=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$returndata=json_encode($row);
echo $returndata;
mysqli_close($con)
?>
The variable "src" I am passing in is a URL (string) , so I believe I should be treating it in a different way b/c of the nature of an URL with all its' special characters ,,,, I am running my code and it errors out as a "null" , but when I run the appropriate sql statement query in mysql DB then the DB returns what I am expecting ..... please advise what I may be doing wrong please ?
the sql I am running is this:
SELECT solution
FROM requests
WHERE theurl = 'https://www.google.com/fskdfalkadsl?=sksdkalsk&soccer=uwiw'
;
I know it will return back to me single row with just one column , and know what to expect as the value , but I can't seem to get the "get.php" page to return anything but "null" it seems ....
You get NULL because PHP does not automatically populate the $_GET when it receives JSON formatted data, so there is nothing in $_GET['solution']. You need to capture and decode the input yourself.
Instead of:
$solution = $_GET['solution'];
You need
$data = json_decode(file_get_contents('php://input'), true);
$solution = $data['solution'];
Or something close to it.

How can I send HTML data to PHP using JSON?

I can't seem to understand how to send data from my Client-side HTML to my Server-side PHP (Which already means their not in the same folder and are not running in the server) and only get a Notice of an unidentified variable and a Fatal error: Cannot access empty property.
I tried the methods in W3Schools and still no luck. And just to be sure I tried to copy paste it. Still the same.
So my question is: How can I send this simple Client-side HTML/JavaScript data:-
<script>
function sender(){
obj = "tblname";
// how to send that data to the php server-side.
}
</script>
To this PHP:-
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM ".$objData);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Using JSON?
If anyone could elaborate and show me a sample it would be great.
Again, I am a noob/newb in using JSON and have no long term background (I just started like a week ago and that had a lot of problems already) and am completely clueless when it comes to this type of client-to-server communication.
I Just need the simple sender code (from the JavaScript) and the receiving code (from the Php) one or two lines will do; with a short description on how they work.
I'm using Windows 7, Wamp3.0.6 and Chrome.
PS: I got that from W3Schools. Yes it didn't work. And please don't be Vague. Thank you!
You can make ajax call form client side to server file and can send data with get method
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "path of your php file",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
})
-_-
Everyone seems to try and over complicate and over think this when the simple answer would have been this code.
function caller(){
myData = "myTbl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "bring.php?q="+myData,true); //sends myData to the php. You can change the GET to POST if ya want to be extra safe but either way, the php won't care anyways.
xmlhttp.send();
}
The above code is from the client server and sends the data of myData to this Server-side php.
<?php
$q = $_REQUEST['q']; //the receiver of the data. You can use explode() to separate them into pieces and turn it into a jigsaw puzzle if ya want.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} // how to connect is not important in my question but it is important for you to be able to connect to the database.
// now for the important stuff
$sql = "SELECT * FROM ".$q." "; // I had to extend it with a space because sometimes it's misunderstood.
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
$outp = array();
while($row=mysqli_fetch_assoc($result))
{
$outp[] = $row;
}
echo json_encode($outp); //sends the data gathered from the database table back to the client as a JSON file, and you are done.
?>
It took me 6 hours worth of studying with a lot of internet surfing and trials and errors.
And like I said; I am a newb at JSON so it's pretty much understood that I don't understand AJAX. Like, AT ALL.
I'm sorry if ya think I sound like an idiot but let's face it, almost all of us were idiots at one point while trying to learn programming. So, I'm surprised why some people are just plain rude here. Thanks. Somehow I'm not really surprised that their also like this here. Makes my internet social life a bit more boring.
So next time, do me a favor and instead of being totally rude, just answer the question if you have one.
You cannot transfer an object via HTTP as it is. You need to transform it into a string you can put into the body of your HTTP-POST Request:
try {
var jsonString = JSON.stringify(anyJsonObject);
//send it to the server
} catch(ex) {
//handle error if anyJsonObject wasn't a valid JSON object. Remember: Not every JS object is a JSON object too.
}
The opposite way is:
try {
var jsonObject = JSON.parse(anyJsonString);
} catch(ex) {
//handle error if anyJsonString was malformed
}

AngularJS JSON not arriving php

i am having the following problem, i have a service that makes a http request, and when i try to get the response throws a parser error, and that is because the response is not ready when it tries to parse the response.
here is the code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
setTimeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
When i console.log the response it prints an empty string, which is odd, that's why it throws this parser error.
My question is how can i do .success function only when the response is ready?
Edit:
in the end the problem is other, i am storing a JSON in a database, but when the JSON has very information it doesn't arrive at php.
here's my php code:
<?php
$id = $_POST["id"];
$id_col = $_POST["id_col"];
$tipo = $_POST["tipo"];
$cliente = $_POST["cliente"];
$info = $_POST["info"];
date_default_timezone_set("Europe/Lisbon");
$data = date("Y-m-d H:i:s");
require 'connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($id!=""){
$sql = "UPDATE `Simulacoes` SET `info`='".$info."' WHERE `id`='".$id."'";
}else{
$sql = "INSERT INTO `Simulacoes`(`id_col`, `tipo`, `data`, `cliente`, `info`) VALUES ('".$id_col."','".$tipo."','".$data."', '".$cliente."', '".$info."')";
}
if ($conn->query($sql) === TRUE) {
echo $info;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
here's the response i get:
{"data":"","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"params":{"id_col":"1","tipo":"Património Reforma","info":{"simuladores":[{"nome":"ii","info":{"prazoReforma":20,"empreendimentos":{"empreendimentos":[{"id":"1","nome":"Oporto Place","localizacao":"Porto","$$hashKey":"object:50"}],"tipologias":{"0":"Loft","19":"T2","37":"T3"},"plantas":{"0":"3.1","1":"6","2":"8","5":"3.2","12":"2.1","13":"7","14":"2.2","15":"5"},"pisos":[{"id":"2","piso":"1","$$hashKey":"object:69"}]},"entrada":"20000","duracao":"35","taxa":"5","montante":82000,"prestacao":"414","prestacao_seguros":"440","renda_liquida":"320","resultado":-120,"patrimonio":134367},"$$hashKey":"object:38","imovel":{"empreendimento":{"id":"1"},"tipologia":"Loft","planta":"3.1","piso":"2","info":{"condominio":"50","renda":"400 ","preco":"102000 ","id":"1"}},"hide":1}],"montanteTotal":134367,"pensao":"569","idadeActual":"45","idadeReforma":"65","pmII":120,"pmTotal":120}},"url":"php/guarda-simulacoes.php","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
As you can see, when i echo $info it returns nothing, an empty string, but in data.config.params i get all params. Anyone knows why is this happening?
Your codes looks ok, which is taking promise from And executing code in its success. I think instead of setTimeout you should use $timeout which will run $digest cycle when timeout complete
Code
simpafAPIservice.getSimulacao($stateParams.id).success(function(response){
console.log(JSON.stringify(response[0].info));
$scope.simuladorInfo.cliente = response[0].cliente;
$scope.simuladorInfo.info = JSON.parse(response[0].info);
console.log(JSON.stringify(response[0].info));
$timeout(function(){
for(var i=0;i<$scope.simuladorInfo.info.simuladores.length;i++){
$scope.addDataGraphic(i);
}
},100);
});
}
According to the docs, $http.success returns data in the first argument, which is converted to JSON only if the active transformResponse can detect is is the appropriate format:
Angular provides the following default transformations:
...
Response transformations
($httpProvider.defaults.transformResponse and
$http.defaults.transformResponse):
If XSRF prefix is detected, strip it (see Security Considerations
section below). If JSON response is detected, deserialize it using a
JSON parser.
If your server is responding with an empty string (which seems the case here)
then it will not be detected as a JSON object and will remain an empty string.
Check your server response, it may be responding with no body and an error status. One thing to watch for if you are requesting data from a different domain (even if it's ultimately the same server) is same-origin policy.

Mysqli query is returning a null value for a simple row of strings from a DB

I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.

Inserting into database using ajax , 500 (Internal Server Error)

In my html I have a simple ajax that's inside a function that gets called on a button press. I want the php script that's called to insert the javascript variable sent into a database.
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {'variable': myval},
});
In my testfile.php I have tried numerous things to insert into the database but with no luck. I know that ajax is working because doing just the bellow works fine with no errors.
<?php
$myval = $_POST['variable'];
echo $myval;
?>
I tried doing this bellow first with global variables. Then even tried putting in the values manually and I kept getting the 500 error even though I have the exact same code in another script (not being called by ajax) and it works fine.
$db = new PDO('mysql:host='. DB_HOST .';dbname='. test_user, DB_USER, DB_PASS);
So I tried opening it a different way.
$con = mysqli_connect('localhost','username,'pass','newdb');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
and that worked fine. However putting in the global variables causes it not to work.
Then I tried to insert to a table.
INSERT INTO send (user_id)
VALUES ($myval);
and I get a 500 error again.
I try accessing the php file directly (testsite.com/testfile.php) and get a blank page. Viewing source gives me nothing.
What am I doing wrong as to keep getting these errors?
PHP:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'dbname'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$myval = $_POST['variable'];
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
$query = $pdo->prepare('INSERT INTO send (user_id) VALUES (?)');
$query->bindValue(1, $myval);
$query->execute();
echo $myval;
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
Javascript:
var myval = 'testuser'; // generated by PHP
$.ajax({
type: 'POST',
url: 'testfile.php',
data: {variable: myval},
});
Don't add quotes around the variable name. I've provided a php script that should work the way you want it to, comment back if you still need help.

Categories