undefined index error in jquery ajax request - javascript

Please check my code in the following:
PHP & HTML Code(file1.php):
<?php
$conn = //connected to db successfully.
$sql = "SELECT t1.column1 AS Column_1 FROM table1 t1";
$rs = mysqli_query($conn,$sql);
$rows= mysqli_fetch_assoc($rs);
do{
?>
<button data-id="<?php echo $rows['Column_1']; ?>" type="button" onclick="handle_item('id')">Click Me</button> <br>
<?php }while($rows = mysqli_fetch_assoc($rs)); ?>
jQuery AJAX code(file1.php):
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data: {
'button_id': c
},
success: function (data) {
alert(data);
}
});
}
</script>
PHP Code(handle_input.php):
<?php
echo "Button with id ".$_POST['item_id]." clicked!";
?>
Now the problems is (as you might expect) the infamous error in this case, "undefined index: button_id" error. I receive it as an alert error when I click on one of the buttons. I've already read the duplicate questions on SO but unfortunately none of those I read could resolve my problem. I appreciate your guiding me with this.
Besides, as you see from my codes, I'm fetching several button from database and while displaying, I assign each one a data-id and use that data-id in ajax to use in 'handle_input.php' and I want to receive each button id which I've clicked on. Thanks in advance.
UPDATE:
It's been a while since I've asked this question but I've been curios about something in my question:
Why doesn't the array mode(data: {"button_id":c}) work for me in the $.ajax function(which leads to undefined index error for the $_POST variable) whereas the string mode(data: "usg_id="+c) does?

You're sending:
button_id:..
but you're using, also with a missing '
$_POST['item_id]
change to:
$_POST["button_id"]
UPDATE
Add this as first parameter:
onclick="handle_item(this, 'id')"
Then, changehandle_item function as this:
function handle_item(obj,item_id) {
var c = $(obj).data(item_id);

<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data:"item_id="+c,
success: function (data) {
alert(data);
}
});
}
</script>
There is no button_id defined in you function hence the error.
Also in handle_input you are fetching item_id

Related

PHP says Undefined even when it is clearly defined in AJAX call?

I'm working on some function which needs to call php using ajax and get some values. How ever I'll post my JS function part below.
JavaScript
$.ajax({
type: "POST",
url: 'php/getAccountJobs.php',
ContentType:"application/json",
dataType:'json',
data:{email:$.cookie("email")},
success : function(arr)
{
for(var i=0 ; i<parseInt(response); i++) // number of jobs are the response we use there
{
var jobmsg = arr[2*i] ;
var imgurl = arr[2*i+1];
$.ajax({
type: "POST",
url: "php/addDivAccountJobs.php",
dataType:'json',
data: {imgURL:imgurl,message:jobmsg},
}).done(function( html ){ alert(html);});
}
}
});
So I checked the console log and saw this following error.
Notice: Undefined index:imgURL
So what I thought was to use isset function to test whether imgURL value is being set or not.
PHP
<?php
session_start();
if(isset($_POST["imgURL"]) && isset($_POST["message"]))
{
$username = $_SESSION["firstname"]." ".$_SESSION["lastname"];
$imgurl = $_POST["imgURL"];
$msg = $_POST["message"];
$fullecho = '<div class="col-md-4">
<div class="profile-card text-center">
<img class="img-responsive"src="'.$imgurl.'">
<div class="profile-info">
<h2 class="hvr-underline-from-center" id="jobOwnerName">'.$username.'</h2>
<div id="jobMessage">'.$msg.'.</div>
</div>
</div>
</div>';
echo json_encode($fullecho);
die();
}
else
echo json_encode("error");
?>
As I expected what I received was error message in alert box.
My Problem
I went through every stackexchange question and tried to find the reason behind it and fix it. but none of those solutions gave me a proper answer. Please can someone help me to find the problem?
when your json property has undefined value its completely disapear from json. so it because arr[2*i] or arr[2*i+1] somewhere get undefined value in the loop

load() function won't allow scripts on page to execute

I have a php script which has a select box which allows user to filter some data.And I have used change event on select box to trigger jquery's load function to load a div of another page which will show that filtered data.Now the problem is I have a javascript function which is being called from that page upon some check in php , and this is resulting in that javascript function not getting called at all.Is there any work around in this scenario?I tried using $.get() but I'm not sure if it will allow me to load only part of page.
This is the load() function's call
$('document').ready(function() {
$('#topic-filter-select').on('change' , function(e) {
$.ajax({
type: 'GET',
url: templateUrl+"/ajax/custom_ajax_functions.php",
data : {
functionName : 'load_topic_filter',
topic_id : e.target.value
},
success: function(result) {
for(var i=0;i<result.length;i++)
result[i] = parseInt(result[i]);
result = JSON.stringify(result);
$('#activity-container').empty();
$('#activity-container').load("/topic-filter-template?result="+result+" #topic-page");
},
error: function(error) {
$('#post-0').empty();
$('#post-0').append("<div id='filtered-activities'><h4>Something went wrong , please try again.</h4></div>");
}
});
});
});
And the php check which gives call to javascript function is
<?php $result = has_user_voted($poll_id , $current_user_id);?>
<?php if($result[0] == true) :?>
<?php echo '<script type="text/javascript">animatePollEffect('.json_encode($result).','.$poll->ID.')</script>';?>
<?php endif; ?>
there your question and code snippet creating a lots of confusion. Please, correct it properly to understand what you want exactly.

Send php request onclick via ajax

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here
First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..
Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)

why I can't get the value when make a jquery/ajax call on link click?

In my website I have a link where user id is store like this :
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :
Undefined index: id
Can you tell me how can I solve it ?
Here is the JS offUser function
function ofUser(id, event){
id = $(id);
event.preventDefault();
var formData = id;
$.ajax({
url : <?php echo "'ofUser.php'"; ?>,
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend : function () {
$("#ofUser_message").val("Searching...");
},
success : function (data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
offUser.php
echo $uid = (int) $_POST['id'];
id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])
Also note, your data being sent over server should be an object.
Try this:
function ofUser(id, event) {
event.preventDefault();
$.ajax({
url: 'ofUser.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function() {
$("#ofUser_message").val("Searching...");
},
success: function(data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: {
id: id
},
cache: false
});
}
Edit: Remove processData : true as it will send data as DOMDocument
Just try to pass id = id; instead id = $(id); because $(id) means you are trying to get any DOM element values using jQuery, I hope it will work, also tell me that, what HTML is generated for your this code
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
To solve this problem, SIMPLIFY to make sure you are correctly passing the ID value. In your AJAX success function, ALERT the value you send back so you can immediately see what you received in PHP.
Try setting it up this way instead:
html:
<p>by <a id="uid_<?php echo $uid; ?>" href="#" ><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</a></p>
javascript:
$('[id^=uid_]').click(function(event){
event.preventDefault();
var formData = this.id.split('_')[1];
$("#ofUser_message").val("Searching...");
$.ajax({
type : 'POST',
url : 'ofUser.php',
data : id=formData,
success : function (data) {
alert(data);
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
}
});
});
ofUser.php
$uid = $_POST['id']; //REMOVE the (int) for now, to verify what PHP is receiving - then add it back.
echo 'Received $uid';
Notes:
(1) Note that you misspelled ofUser.php and offUser.php (not sure which is correct - I went with ofUser.php)
(2) Try not to use inline javascript. jQuery is easiest to use when you break out the javascript from the HTML, as per above example.
(3) In above example, the jQuery selector starts with is used:
$('[id^=uid_]').click(function(event){
That code is fired by any element whose ID begins with uid_, as we configured the <a> tag's ID to appear. That makes it easy to see in your HTML.
(4) This line:
var formData = this.id.split('_')[1];
uses pure javascript to get the ID, because it's faster - and simpler to type. The code splits off the 2nd part of the ID, at the _ char, resulting in just the ID number. That ID number is then assigned to the variable formData
(5) In the AJAX code block, make sure the url is spelled correctly:
url : 'ofUser.php',
Here are some other SIMPLE AJAX examples that might help. Don't just look at them - reproduce them on your server and play with them. They are simple, but you may learn a lot:
AJAX request callback using jQuery
When click over any hyperlink then start redirecting to provided URL. so you need to prevent its default action using below code inside your click event handler
event.preventDefault();

Using ajax to display what is being typed not working, PHP, AJAX, JAVASCRIPT

Using ajax, I'm trying to display what is being typed in the text box, but it's not displaying anything at all for some reason. I know the ajax function itself got called, by using alert inside the function, and I think the real problem is actually in test2.php, but I'm not sure what I did wrong. Please take a look:
test1.php
<?php
include('ajax.php');
echo "<input type = 'text' name = 'select' onkeyup = 'ajax(\"test2.php\",\"select\",\"output\")'>";
echo "<div id = 'output'/>";
?>
test2
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,select,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $('select[name="select"]').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
function ajax(url,unused,id) {
$.post(url,{select: $('input[name="select"]').val()})
.error(function(e){
alert(e);
})
.success(function(d){
$("#"+id).text(d);
});
}
The problem is here:
data: {select: $('select[name="select"]').val()},
There is no select element. And if you meant to get the id named element, then you need to change it to:
data: {select: $('#select[name="select"]').val()},
or in your case:
data: {select: $('input[name="select"]').val()},

Categories