Undefined Index : PHP variables passing by AJAX - javascript

I would like to send my php variables and input file by AJAX with something like this ..
$(document).ready(function(){
$("#submit").click(function(){
//var formData = new FormData($('form#data')[0]);
var chaID = "<?php echo $chaID; ?>";
var row_number = "<?php echo $row_number; ?>";
var tag = "<?php echo $tag; ?>";
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
//Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "ajax_challenge.php",
data : data,
cache: false,
success: function(result){
$('#level').modal('show');
},
contentType: false,
processData: false
});
return false;
});
});
My formData is working fine so let's focus on var data. When I run this function the ajax_challenge.php response "undefined index" but in request part it shown &chaID=7&row_number=2&tag=6 so it should work.
Maybe I did something wrong with php?
$chaID = $_POST['chaID'];
$row_number = $_POST['row_number'];
$tag = $_POST['tag'];
Additionally, is there anyway to mix formData + data correctly?
EDIT . the screenshots of browser's console
response screenshot
request
EDIT2 -----------------------------------------------------------
The thing is, it's gonna work if I remove
contentType: false,
processData: false
but the problem is If I deleted it also can't pass var formData input:file through URL. What do I suppose to do ?

I think I see what is going on, you're passing the GET parameters wrong to the data variable.
From my understanding of how jQuery appends GET parameters, the fix would be
'?chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag
If this doesn't solve it, try checking the console for errors or try to console.log the values. Also make sure you're encodeURI the values before putting them in the URL.
Also, it's better practice to make an array with the GET values and pass them instead to the data variable of the jQuery.ajax() function, as it does the string conversion for you automatically, try doing that instead, it might just solve the problem. ;)
You can find the documentation for the AJAX functions of jQuery and EncodeURI here:
http://api.jquery.com/jquery.ajax/
http://www.w3schools.com/jsref/jsref_encodeURI.asp
EDIT: I noticed you're using the POST method, in that case then pass the array of posted values to the data parameter and it should work. Only include the variable values however. Example array:
data = [chaID, row_number, tag];
Pass an array to the data parameter, and it should post the values just fine. Also, try to include in your question a screenshot of the console network tab, which tells us if something is going wrong. Also a console screenshot.
EDIT2: Okay, here are my observations: ProcessData will process the object, therefore it makes sense formData won't work. Try appending the other array:
data = [chaID, row_number, tag];
for (var i = 0; i < formData.length; i++) {
data.append('formData[]', formData[i]);
}
EDIT3: This should work. Just modify your PHP and JS this way:
var data = formData;
var params = $.param({"chaID": chaID, "row_number": row_number, "tag": tag});
//Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "ajax_challenge.php?" + params,
data : data ,
and PHP:
$chaID = $_GET['chaID'];
$row_number = $_GET['row_number'];
$tag = $_GET['tag'];

Because you put your php variable to your script. And php compile your code first your javascript run:
var chaID = "<?php echo $chaID; ?>";
var row_number = "<?php echo $row_number; ?>";
var tag = "<?php echo $tag; ?>";
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
And so, you have not click, $_POST['chaID'] and another $_POST variable is not defined.

If you are using $_POST method in ajax no need to start param data with &
var data = '&chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
Replace with:
var data = 'chaID=' + chaID + '&row_number=' + row_number + '&tag=' + tag;
Also check values in php what are you getting by using print_r($_POST);

Related

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

Joomla & JS; Sending data from form to Controller

I am having trouble with a form I created and trying to redirect the data someplace else by a JavaScript method that I call whenever the submit button is clicked.
The first thing that is happening, is that the form is created and filled in, then the user will click on the HTML generated button with this action in it:
onclick="javascript:saveEssayScore(<?php echo $key . "," . $pid; ?>);"
Secondly the script file is read and performed. The code is below:
<script type="text/javascript" language="javascript">
document.body.className = document.body.className.replace("modal", "");
function saveEssayScore(key, pid){
var user_id = document.getElementById("user-"+key).value;
console.log("user " + user_id);
var grade = document.getElementById("grade-"+key).value;
console.log("grade " + grade);
var teacher_answer = document.getElementById("feedback-"+key).value;
console.log("teacher_answer " + teacher_answer);
var question_id = document.getElementById("question-"+key).value;
console.log("question_id " + question_id);
var quiz_id = document.getElementById("quiz-"+key).value;
console.log("quiz_id " + quiz_id);
var req = new Request.HTML({
method: 'post',
url: "<?php echo JURI::base();?>index.php?option=com_guru&controller=guruAuthor&task=saveFeedback&tmpl=component&format=raw",
data: { 'pid' : pid, 'user_id' : user_id, 'grade' : grade, 'teacher_answer' : teacher_answer, 'question_id' : question_id, 'quiz_id' : quiz_id},
onSuccess: function(response, responseElements, responseHTML){
alert('yeyy');
}
}).send();
}
Now in the URL, it is read to run the method (task) saveFeedback() in the controller guruAuthor which is in the component com_guru.
The problem I am having is, how do I read the data that I just send through the HTML request? I am trying stuff like $user_id = JRequest::getVar("user_id"); But whenever I'm trying to echo or dump, it is returned to me but empty. Not the values that I am dumping in JavaScript console.log(user_id);
JRequest is deprecated
Use JInput instead. Read - Retrieving request data using JInput
In your mentioned code - if the controller function is being called, try this code-
$jinput = JFactory::getApplication()->input;
$user_id = $jinput->get('user_id', '', 'INT');
I hope this helps.

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

Passing session variable through AJAX to PHP file

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;

Categories