PHP Not passing variables through to ajax - javascript

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);)

Related

Notice Array to string conversion in

Ran into an issue with simply querying and returning the suggestID value.
I keep getting Array to string conversion, so i'm a bit lost. I'm
Javascript
$('#autocomplete').on('typeahead:selected', function (e, data) {
console.log(data);
var dataID = data;
$.ajax({
type: "POST",
url: "get.php",
data: $.param({itemID: dataID }),
success: function(data) {
console.log(data)
}
});
})
Get PHP FILE
<?php
require 'db.php';
if(isset($_POST['itemID'])) {
$db = new DbConnect;
$conn = $db->connect();
$str = $_POST['itemID'];
$stmt = $conn->prepare("SELECT * FROM mytable WHERE id = '$str'");
$stmt->execute();
$result= $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
?>
The itemID parameter is being treated as an array by PHP:
$str = $_POST['itemID'];
If you were to var_dump that you might see that $str is an array.
When the data passed to ajax is an object and one of the property values is an array, param will serialize it using the array bracket syntax, which PHP automatically treats as an array. For example:
$.param({key: [1, 2, 3]}); // "key[]=1&key[]=2&key[]=3"

pass php array to javascript using ajax

I try to get array from sql server using php , and parsing these array to javascript using ajax.
However , I have tried many solution by google , I can't get the array.
This is my php code:
<?php
include 'Connect.php';
$Store_int = $_GET['num'];
$sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;
mysqli_select_db($link, "web");
$link->set_charset("utf8");
$result = mysqli_query($link, $sql);
$arr = array();
while ($row = mysqli_fetch_object($result)) {
$p = (string)$row->Name;
$arr[] = $p;
}
//print_r($arr);
$jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo $jsonArr;
mysqli_free_result($result);
mysqli_close($link);
?>
Array in php will encode and display:
["pen","pencil","apple","cat","dog"]
and the .js file
function getArr(store_int) {
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function (data) {
alert(num);
jsArray = JSON.parse(data.jsonArr);
}, error: function (data) {
alert("123");
}
});
//alert(jsArray.length);
return jsArray;
}
In .js , I will always get empty response(undefined) from php.
Because the ajax will answer "error" function..., and the error status is 200.
Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. and You don't need JSON.parse() as you have defined dataType as json in your ajax call. Pass a function to your getArr() function and use your data in that function.
function getArr(store_int, outputFn){ // what do you use store_int for?
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function(data) {
outputFn(data)
},error: function(data){
alert("123");
}
});
}
Then use it like
getArr('5', function (data) {
console.log(data)
})
Console output
Your problem lies here. You are attempting to access data.jsonArr which is always undefined. The JSON data sent is actually embodied by data variable.
success: function(data) {
alert(num);
jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}
NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. Putting this at the top of your PHP script should solve your problem.
<?php
header('Content-Type: application/json');

ajax post to php and retrieve sql result [duplicate]

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
}

Loop Through json_encoded PHP Array in JavaScript

I am having an issue with looping through an array that was passed from PHP through an Ajax request.
For some reason my javascript thinks that either every character is a part of the array or my response variable is just being passed as a string.
Here is my javascript:
<script>
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
success: function(response) {
console.log(response);
}
});
});
</script>
And here is my PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
echo json_encode($names);
?>
The response that I get looks like this:
["Test Person","Test2 Person"]
However, if I loop through this using javascript or just print out response[0] I get each character as part of the array. The first element would be [, next would be ", etc.
I would like Test Person to be one element and Test2 Person to be another.
Does anybody know what I am doing wrong? Thanks!
You need to use JSON.parse on the response. Wihtout calling that function you are just getting the index of characters in the JavaScript string.
var resultArray = JSON.parse(response);
resultArray[0]; //Should Be "test Person"
The result of the .ajax method is interpreted according to the Content-Type header of the response. If it is incorrect or not specified, the response variable will contain the raw json code as a string.
So one solution is change the PHP code by adding this line:
header("Content-Type: text/json");
Docs:
The type of pre-processing depends by default upon the Content-Type of
the response, but can be set explicitly using the dataType option. If
the dataType option is provided, the Content-Type header of the
response will be disregarded.
You can parse that text to an object, or you can let JQuery do that for you by specifying a datatype in the call. The response parameter will then hold the object instead of the raw json string.
Docs:
If json is specified, the response is parsed using jQuery.parseJSON
before being passed, as an object, to the success handler. The parsed
JSON object is made available through the responseJSON property of the
jqXHR object.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: "json",
success: function(response) {
console.log(response);
}
});
});
In this particular situation, you can use
success: function(response) {
response = eval(response);
console.log(response);
}
But this is bad practice.
Really the best solution here is to modify your ajax call as follow:
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
datatype: 'json',
success: function(response) {
console.log(response);
}
});
});
The specified datatype, will request the returned data to be json, and the jquery will automatically parse it to a javascript object.
You must parse JSON to array. You can do this using the following code:
var arr = $.parseJSON(response);
Now arr[0] should be "Test Person".
You can do it the hard way, or this way:
First, you need to specify the return type for AJAX.
$(function() {
$.ajax({
url: "/dev/editButton/get_names.php",
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Alternatively, you could do it this way:
$(function() {
$.getJSON("/dev/editButton/get_names.php", function(response) {
console.log(response);
});
});
For this to work, you will need to specify the HTML headers accordingly in PHP:
<?php
include '../portfolio/libraries/settings.php';
$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$query = "SELECT * FROM AUTH_User";
$result = mysqli_query($connect, $query);
$names = array();
while ($row = mysqli_fetch_array($result)) {
array_push($names, $row['FirstName']." ".$row['LastName']);
}
header("Content-Type: application/json");
echo json_encode($names);
exit();
?>
The exit(); is just for safety so you wouldn't ruin the valid JSON format.
JSON stands for JavaScript Object Notation, so you should not have to do anything complicated there. Here is a simple loop you could use for example:
for(var i in response) {
console.log(response[i]);
}
Alternatively, if the response is not an array but an object with properties, you could loop through the object properties by getting the right keys first:
var objKeys = Object.keys(response);
for(var i in objKeys) {
var key = objKeys[i];
console.log(response[key]);
}
I hope this helps!

AngularJS can't sent POST request to SLIM Framework

Hello I have this angularjs http.post() request to slim php framework.
'use strict';
soup.factory('loginService',function($http){
return {
login:function(user){
console.log(user);
var $promise = $http.post('api/vendor/slim/slim',user );
return $promise;
};
});
when I debug the $_POST it always return an empty array,
but when I use use json_decode(file_get_contents('php://input')), slim php will return an error.
this is php function that handle the request.
function login(){
$sql = "SELECT * FROM users ORDER by id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
//print_r($users);
$users = json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
var_dump($_POST);
$test = json_decode(file_get_contents('php://input'));
//do something with the post data
}
how can I solve this?
$http api say:
params – {Object.} – Map of strings or objects which
will be turned to ?key1=value1&key2=value2 after the url.
If the value is not a string, it will be JSONified.
Try sending data as a string, something like this:
var $promise = $http({
url: 'api/vendor/slim/slim', method: 'POST',
data: 'user=' + usr + '&password=' + pwd,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
Don't forget to include the Content-Type header.

Categories

Resources