Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
hey i want to crawl data from the site with this code (js)
var i = 0
var oldValue = -1
var interval = setInterval(get, 3000);
function get(){
var x= $($('.table-body')[1]).find('.h-col-1')
if(i!=5){
if(oldValue != x){
oldValue = $(x[1]).text()
console.log($(x[1]).text())
++i
sendPost($(x[1]).text())
}
}else clearInterval(interval)
}
function sendPost(par) {
var te= $.ajax({
type: "POST",
dataType: 'jsonp',
url: 'http://localhost/sa.php',
data: {json:JSON.stringify({
num : par
}) },
}).done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(xhr.responseText);textStatus
});
console.log(te)
send data from localhost and save on my sql and this php code
sa.php
<?php
header('Access-Control-Allow-Origin: *');
$sitename = "http://localhost/";
$hostname = "localhost";
$username = "root";
$password = "";
$database = "db";
$connect = mysqli_connect($hostname, $username, $password, $database);
$insert = "INSERT INTO main(number, time, date) VALUES ('%s','%s','%s','')";
$data = json_decode(file_get_contents("php://input"), true);
$result = mysqli_query($connect,sprintf($insert,$data['num'] ,date("H:i:s"),date("Y-m-d")));
?>
and then
success send from js request from local server why dosen't save on the my sql ??
I think the answer lies into your insert query:
$insert = "INSERT INTO main(number, time, date) VALUES ('%s','%s','%s','')";
Please count the number of columns defined and the number of values you're trying to insert. These two should, obviously, match.
If you wish to figure out why a MySQL query failed, just print or log the error:
http://php.net/manual/en/mysqli.error.php
You should check the value of file_get_contents("php://input").
As you are sending a key-value pair:
data: {json:JSON.stringify({
num : par
}) },
you should get the data using $_POST['json'].
So:
$data = json_decode($_POST['json'], true);
The alternative, change the javascript instead of the php, would be something like:
data: JSON.stringify({
num : par
}),
But to be honest, I don't know how jQuery will handle that data so it might need some tweaking.
Apart from that, you have an sql injection problem; you should use prepared statements with bound parameters instead.
Related
I have a global variable that I want to pass into Ajax. Ajax is very new to me and I've done some research and testing but I am stuck. I don't know if the variable is being passed into the Ajax function for my first question.
I'm not really interested in Json, however I did also make an attempt with that and it's not correct either.
I am not looking to get a response from the php back to the page, the page is updating using the existing js and html.
My second dilemma is that my php file is being activated when it should, however it's posting 0 into the database field. Another problem here too is that it's updating all users money to this same 0 entry so some how it's isset is not set correctly yet. I believe my bindValue is coded correctly, I am really unsure if I need to break down the POST to the php page and if so if I have to use the value, how would I do that? Also when I add WHERE userid = userid to UPDATE the game stalls completely.
Any help even a small fix would be greatly appreciated.
Here are the files. Thank you in advance for helping me get my head around Ajax.
game.js
money = 2000;
function updateMoney() {
if ( pot <= 0 ){
if ( money <= 0 ){
document.getElementById("aaa").innerHTML = "Lost? Here's A Loan !!!";
money = 1000 ;}
}
document.getElementById("money").innerHTML = money;
}
function enterWager(){ // doMath function inside here
var x=parseInt(document.getElementById('textbox').value,10); // Displays the textbox for placing a
wager
if (money <= 0) {
x = 0 ; }
document.getElementById("bet").innerHTML = parseInt(x,10);
if(isNaN(x)||x < 1 || x > 250)
{
document.getElementById("aaa").innerHTML = "You're Out Of Money!!!";
}
document.getElementById("textbox").style.display = 'none';
document.getElementById("button").style.display = 'none';
function doMath() { // PVPCoinTransaction() and
transferCoins() are off right now. Plus 4 tests failed
and
are also off at end of function.
if (pot == 0){
countWagers = 0;
}
if (money <= 0) {
money = 0 ; }
if (x > money) {
x = money ; }
money = money - x;
pot = pot + x;
}
doMath()
function updateDatabase() {
// POST test not working
// $.ajax({
// url: 'php/credits/credit.php', //
// type: "POST",
// dataType:'json', // add json datatype to get json
// data: ({money: 145}), Do I put div here and how?
// success: function(data){
// I dont need to return anything, just update db field!
// }
//});
// this section reaches php but posts 0 into database field
//data = money // I don't think this is working.
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.open("POST", "../php/credits/credit.php", true);
xml.setRequestHeader("Content-type", "application/x-
www-form-urlencoded");
xml.send(money);
}
updateMoney()
updateDatabase()
credit.php
<?php
session_start();
if(empty($_SESSION['userid'])) // check user login
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid'])) {
// $money = null;
// $money = $_POST['money'];
try {
$db = DB();
header("Content-Type: application/json");
$stmt = $db->prepare("UPDATE usersystem SET money=:money");
$stmt->bindValue(':money', $_POST['money'], PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>
Your server expects a key called money in your $_POST array. This means that in order to receive the data properly you need to send the data with a key as well. In PHP this data looks like an associative array and in JavaScript as an object, both having keys and values.
The easiest way to accomplish a key-value structure is to create a string with a key=value structure. This is similar to how forms send their data to servers and requires no modification on the backend for receiving the data.
var package = `money=${money}`;
There is nothing wrong with XMLHttpRequest (there is with ActiveXObject ;) ), I would recommend to learn the Fetch API. It is an updated and simplified specification of making HTTP requests to and from the server. You've indicated that you don't need to receive a response, that means that a basic POST request with sending data looks like the example below.
fetch('../php/credits/credit.php', {
method: 'POST',
body: package
});
The first parameter is the URL, the second an options object. The method property speaks for itself. The body property is the data you're sending (comparable to xml.send(package);).
Now if your URL is correct then an HTTP request with the correct data should be send to your server.
// $_POST should have received data, and because you've send it as a
// key-value it will be represented as an associative array with,
// you guessed it, keys and values.
$money = $_POST[ 'money' ];
// $money will always be a string in this form, so you'll
// need to convert it if you need it to be a number.
$money_as_number = intval( $money );
To test if this works open the network tab in the developer tools of your browser. You can check if an HTTP request occurs and checkout if the correct payload has been sent.
Okay so this is what works in the console ...
function updateDatabase() {
var package = money;
console.log(package);
fetch('../php/credits/credit.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(package)
});
}
console log = 1975 game.js:1608:9
I just need the 1975 value to post to the database via my php now. it's still posting 0 into my database.
I solved it. Thank you for setting me on the right path!
<?php
session_start();
if (isset($_SESSION['userid'])) {
$money = json_decode(file_get_contents('php://input'), true);
$money_as_number = intval( $money );
$userid = $_SESSION['userid'];
try {
$db = DB();
$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>
This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.
This question already has answers here:
How to pass parameters in $ajax POST?
(12 answers)
Closed 6 years ago.
im using ajax and php on my android app to query my database.
i am able to retrive all the results but dont know how to send a variable to my php so that i can use it as a custom query and retrive the results... something like this :
$id = $_POST['id'];
$sql = "SELECT * FROM mobile_app WHERE nome LIKE '{%id%}'";
but cant make my ajax post the variable and retrive the result...
this is my code :
my mobile app:
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON", // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.setItem('myData', JSON.stringify(data));
}
});
my php:
$sql = "SELECT * FROM mobile_app";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$output[] = array (
"nome" => $row['nome'],
"status" => $row['status'],
"hentrada" => $row['hentrada'],
"evento" => $row['evento']
);
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($output);
ajax() have a parameter
data:
by using this you can send as many param you want lik:
data:{
param1 : value1,
param2 : value2,
// and so on
}
In your case it is like:
data:{
id : value
}
and you can get this param in your php code like:
$id = $_POST['id'];
You need to add the following additional options to your $.ajax object:
type: 'post'
and
data: {
id: whateverVariableHasID
}
I am passing through The continent to the PHP file from a js file. Basically I need to insert the data to the database (put the continent in) and get the ID of it, but no matter what I do, it returns either an empty string or a 500 Internal Service Error.
Here is the PHP Code:
$continent = $_POST['continent'];
$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";
if(!$result = mysqli_query($con, $sql)){
die('There was an error running the query [' . $db->error . ']');
}
$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;
Here is the JS Code:
$.ajax({
url: 'process.php?section=continent',
type: 'POST',
data: 'continent='+key,
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
The Key that is passed through would be something like Africa.
I have tried the following in the php file:
return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);
I have struggled for around 2 hours now. I cannot seem to find the error.
Note
Please note that the information is being inserted to the database just fine, just that I cannot get the ID.
In ajax you need to print/echo output for return data rather return statement so try to replace
return $result2->num_rows;
to
echo $result2->num_rows;
also you can send your query string like:-
$.ajax({
url: 'process.php',
type: 'POST',
data: {'section':'continent','continent':key},
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
Then check your post data by echo if correct something wrong with query executing can't find $con and $db defined on posted code
You are returning but you are not in a function, so try echoing instead (echo mysqli_insert_id($conn);)
I have two problems. One is totally in PHP the other in Javascript. But both are equal in what I'm trying to get.
index.php
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
success: function(data) {
alert(data);
// Returns: {'status':1}
// I want to get "1"
// data[0] -> doesn't work
}
});
insert_info.php
// Connects to another file
include_once('verify_info.php');
$verify = new verify_info();
$arr = array("status:" => 1);
$extension = $verify->verify_file($_REQUEST['array'][9]);
if($extension[0] == 0){
$arr = array("status:" => 0);
}
echo json_encode($arr);
verify_info.php
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
$arr = array();
if(!in_array($info['extension'], $extensions)){
$arr = array("status:" => 0);
}else{
$arr = array("status:" => 1);
}
return $arr;
}
In insert_info.php, I would like to get by $extension[0] the status retrieved from the function verify_file();
After that I output as json_encode the value to Javascript and I would like, again, to parse the info.
What am I doing wrong? Thanks.
Edit 1: alert(data.status); doesn't work either.
Edit 2: alert(data.status); would never work since I echo {'status:', 1} (problem with that two points in the middle)
Correct way for solving the issue of javascript:
var obj = jQuery.parseJSON(data);
alert(data.status);
I'm still trying to get fixed the php.
Edit 3: All solved. Thank you guys.
public function verify_file($file){
$extensions = array('jpg', 'png', 'jpeg', 'bmp');
$info = pathinfo($file);
if(!in_array($info['extension'], $extensions)){
return false;
}
return true;
}
As I said in my comment, your setting your key in PHP to "status:" is the trailing colon necessary on the end of your key? I don't think it's necessary, PHP arrays already offer mechanisms for fetching them and your JSON will contain the string without processing it so your key once you hit your JS code will still be "status:" where most likely you intended for "status".
Regardless of whether you will make this change or not that doesn't break anything. In your Javascript code, as #charlietfl pointed out, you should be setting the dataType of the return to "json" so you're JS Ajax call would look like:
$.ajax({
type: "post",
url: "insert_info.php?type=info",
data: { array : all },
dataType: "json",
success: function(data) {
// Assuming no change on the backend
alert(data["status:"]);
}
});
If, however, you altered the string to remove the colon then accessing the status element of data would be data.status as #A.Wolff pointed out in his comment. This doesn't work because of the trailing colon in the key - but accessing the data with a string key will still work.