$ajax call producing 'undefined' result - php

I cannot get the data to show up in the page, though it appears in console.log.
Here is my query on api.php, the pages are in the same folder.
$Sub = $_GET['id'];
$stmt = $conn->prepare("SELECT id, name FROM variables WHERE id=:id");
$stmt->bindParam(':id', $Sub, PDO::PARAM_STR);
try {$stmt->execute();} catch(PDOException $e){ echo errorHandle($e);}
$rs2 = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($rs2);
It is working fine and produces
{"id":"1","name":"James"} on api.php
Here is the .js and body
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
</script>
</head>
<body>
<p><div id="shoot">shoot</div>
<div id="output"></div>
< script >
$(document).ready(function() {
$("#shoot").click(function()
{
$.ajax({
type: "GET",
url: 'api.php?id=1',
data: "?id=1",
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
console.log(data);
}
});
});
});
</script>
</body>
</html>
I'm getting back
id: undefined name: undefined
I've tried $ajax and any number of other changes but nothing is showing up in the page.
Help would be appreciated

A couple of things to note
You're statically setting the ID when you set the URL-parameter, yet passing it as an argument in data as well. You should reference the file in the url parameter, and pass all relevant values in the data parameter.
The data-parameter has an invalid ? in front.
Actual issue: You get an associative JSON object returned, not an array, so you'll need to access it as such, with data.id instead of data[0].
The AJAX-call should look something like this.
$.ajax({
type: "GET",
url: 'api.php',
data: {id:1},
dataType: 'json',
success: function(data) {
var id = data.id;
var vname = data.name;
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
console.log(data);
}
});
This assumes that you have set the PHP header to return it as JSON, with
header("Content-Type: application/json");
when you use echo json_encode(..).
The values passed in the data parameter can be formatted in several ways, I've chosen a {id:1} in this example, but "id=1" would be valid as well.

On your $.ajax call do not pass the data: "?id=1". By doing that, you are hard-coding the response. So remove that line. That should fix the response coming back to AJAX.
Also, on success: function(data), the data you get back needs to be accessed in this manner:
data.id and data.vname.

Related

Pass ID from AJAX to PHP back to Modal

I have a PHP CODE:
if(isset($_POST['id'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)){
$message = '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
$message .= '<hr><br>';
$message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
}
echo $message;
}
I need to pass the value from my AJAX code to the aforementioned code:
$('#messageModal').on('show', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:"data-id=" +id ,
success: function(r){
$('#messageBody').html( r );
}
});
});
The link that I am using is using a data-id="73" to pop open a model and populate the information.
My issue is, the value is not being passed and the body of the Modal is not being populated. Can anyone let me know why or what I did incorrect?
Check that your db returns something, so that $result is not null. Otherwise your $message will be empty.
If your query actually returns something and $message is still empty - try changing datatype to json:
JS
$.ajax({
type: 'POST',
url: 'php/server.php',
datatype: 'JSON',
data: {
dataId: someArbitraryId
},
success: function(data) {
var message = JSON.parse(data).message;
$('#message').html(message);
}
});
PHP
if (isset($_POST['dataId'])) {
$message = '';
// Some code
$result = array(
'message' => $message
);
echo json_encode($result);
}
Now even if the $message is empty or null - server should return array with empty string.
in js
data:{dataId : id}, // I'm sure this will work but data:"data-id=" +id, may work as well
in php
$_POST['dataId'] // instead of $_POST['id']
If this not work with you there are some steps you need to do
1- alert(r) on ajax success function and check for errors
2- I don't know what is id and where you get it from so try to alert(id) and see if it output an expected value or not
3- you may need to use shown.bs.modal instead of show take a look at here
4- in js try to get the a data-id by using $(a[data-target="#messageModal"]).data('id') instead of id
so your code should looks like
in js
$('#messageModal').on('shown.bs.modal', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:{ dataId : $(a[data-target="#messageModal"]).data('id')},
success: function(r){
$('#messageBody').html( r );
}
});
});
and also in php use $_POST['dataId'] instead of $_POST['id']
So i figured out the issue, it is now displaying the results, however, $(a[data-target="#messageModal"]).data('id'); will not pass the value, i had to use: var id = $("#messageID").attr("data-id");. This is working, but becuase there are multiple instances of #messageID listed, it is only showing the first result becuase you cannot have duplicate ID tags with the same information.  
​
My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

POST-ing JSON to Laravel 4 with jQuery

I've been struggling with this for a while, I checked everything I could think of and I'm sure this should work.. but it doesn't.
The idea is simple - you have a form input of type "text". When you type a number in the input and click "Click me!", it should POST the data in JSON format to a Route (handled via Closure), which would then check if the input is in JSON format and if yes, make a database request, then return the data.
Here is my view (table.blade.php)
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>json test</title>
</head>
<body>
<form action="#">
<input type="text" name="articleID" id="articleid" placeholder="Enter article id" value=""/>
</form>
Click me!
<script>
$(document).ready(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
$("#trigger").click(function(){
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
});
</script>
</body>
</html>
And my routes.php
Route::get('json',function(){
return View::make('table');
});
Route::post('json',function(){
if (Input::isJson())
{
$request = Input::all();
$article = Article::find($request['id']);
if (!is_null($article))
{
return Response::json($article);
}
else return Response::json(['error' => "Object not found"],404);
}
else return "not json";
});
I've got two problems with this:
console.log(article); prints Object { id=""} so JS doesn't seem
to pick up the value of the input
No matter what, I always receive the response "not json", even if I replace data: article with something like data: {id: 123} in the ajax call
UPDATE
Thanks to milz, the first issue is now fixed, I refactored the $(document).ready() function like so:
$("#trigger").click(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
Now the object is properly set, however the backend still returns only "not json"...
I have no idea what I'm doing wrong here, I will appreciate any help! Thanks in advance!
Input::isJson() actually checks for the Content-Type header of the request. The only thing dataType does is telling jQuery what response to expect.
Try setting contentType
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
contentType: 'application/json',
success: function(data){
alert(data.title);
}
});

Pass GET variable from URL to .js, and from the .js to .php

Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.
My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:
My URL:
www.website.com/index.php?user=Bob
My HTML Code
<script type="text/javascript" src="js/get-data.js"></script>
My JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
My PHP Code
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
You need to specify the data attribute in your ajax call.
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
What this will do is prepare a GET request with the proper data, for example, http://path/to/backend/?key1=value1&key2=value2
I believe you want to do something like this
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
EDIT:
Thanks #Brad and #Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.

pass jquery value to php variable

Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks
You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>
You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().

Categories