The jquery is going to a .php to retrive data, and it is successfully retriving information, but the information is returning as undefined when placed on a page.
var userId = $("#userid").val();
$(function()
{
$.ajax({
url: "../apipages/getprofilecomment.php?userId=${userId}",
method: "GET",
type: "json",
cache: false,
success: function(comment){
$('#usercommentdiv').append("<li>" + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + "</li>");
}
});
});
This is the .php page that is returning the data:
<?php
include ("../db/database.php");
include ("../classes/profilecommentclass.php");
include ("../classes/userclass.php");
session_start();
$userId = $_SESSION['user_id'];
$userClassHandler = new User($db, $userId);
$profileCommentHandler = new ProfileComment($db);
$userNameData = $userClassHandler->getUserName();
$profileComment = $profileCommentHandler->getAllFromComment(34);
$profileCommentArray = array(
"userName" => $_SESSION["user_name"],
"user_profile_comment" => $profileComment["profile_comment"],
"time_added" => $profileComment["time_added"],
"time_updated" => $profileComment["time_updated"]
);
echo json_encode($profileCommentArray);
?>
This is what is being returned at: apipages/getprofilecomment.php?userId=${userId}
{"userName":"Acidify","user_profile_comment":"Working to get this app running!!!","time_added":"2019-12-14 00:51:04","time_updated":"15:00:00"}
Note: No particular concerned with the user_name being null.
Change type: "json" to dataType: "json" in the ajax setup and the parse will occur automatically
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
This JavaScript code uses POST method to send data from form to PHP where PHP checks in database if data is true. But I don't know how to send response from PHP back to JS that fetching was successful. Can someone explain?
JS:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(){
//check if what response is
}
});
ajaxsubmit.php:
<?php
session_start();
//connect
$username =$_POST['username'];
$password =$_POST['password'];
$sql = "SELECT * FROM user WHERE email ='$username' OR username ='$username' AND password = '$password'";
$result = mysqli_query($conn, $sql);
if(!$row = mysqli_fetch_assoc($result)){
//response error
} else{
//response success
}
?>
Whatever you echo out in the php will be sent back to the ajax.
if(!$row = mysqli_fetch_assoc($result)){
echo 0;
}
else{
echo 1;
}
success: function(response){
//check if what response is
console.log( response );
}
You have to echo something in your PHP to get something returned:
if(!$row = mysqli_fetch_assoc($result)){
//response error
echo 'there is a problem';
} else {
//response success
echo 'yippee!';
}
Then you can log the return as follows:
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(data){ // 'data' is the variable holding the return from PHP's echo
//check if what response is
console.log(data);
}
});
Make sure to watch the AJAX request / response in the browser's developer tools. Make sure you included the jQuery library in the project. The console will reveal errors. AJAX requires a web server.
WARNING Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
DANGER Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
You can exit method with response parameters. like:
ajaxsubmit.php
if(!$row = mysqli_fetch_assoc($result)){
exit('error'); //exit with response 'error'
} else{
exit('success'); //exit with response 'success'
}
JS
$('#submit-btn').on('click', function() {
var dataString = 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value + '&rememberMe=' + document.getElementById('rememberMe').value;
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(response){
//check if what response is
console.log(response);
}
});
I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');
in order to set two dependent drop downs i'm using jQuery.ajax, but i have some troubles and i think the url of the controller action i set on my $.ajax is not accessible.
this is my controller action code :
public function fillIncidentsAction()
{
$request = $this->getRequest();
if ($request->isPost())
{
$code_categ = (int) $request->getPost('code_categ',0);
$data = new JsonModel(array(
'success' => true,
'results' => $this->getTableInstance('TypeIncidentTable')
->getListTypeIncident($code_categ),
));
return $data;
}
}
and this is the main part of my js function
$('#'+source).change(function() {
if($('#'+source).val() != '')
{
$.ajax({
type: 'POST',
async: false,
url: url,
cache: true,
dataType: 'json',
data: { code_categ: $('#'+source).val() },
success: function(data){
alert(data.success);//<------ i added this to test if this function is executed or not
if(data.success)
{
$('#'+target).prop('disabled', true);
if(data.results != ""){
var options = new Array();
$.each(data.results, function(key, value){
options[((key) ? key : 0)] = '<option value="' + key + '">' + value + '</option>';
});
$("#"+target).html(options.join(''));
$('#'+target).prop('disabled', false);;
}
}
},
});
I don't know where i'm wrong. Any suggestions?
Thanks for help !
Sorry, this is how i set my url :
<script type="text/javascript">
$(document).ready(function() {
var url = "<?php echo $var =$this->url('gims/default', array('controller' => 'evenement', 'action' => 'fill_incidents')); ?>";
// initialize the js function
dependentDropDown('firstList','secondList',url);
});
</script>
Hope this will give you more details.
The problem was in my moodule.config.php, i haven't enabled the Json strategy.
'view_manager' => array(
//...
'strategies' => array(
'ViewJsonStrategy',
),
),