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
Related
I'm posting a variable via ajax however when I use it in PHP, I get NAN why is that? it's supposed to be a number
//in js
var variableToSend = 1;
$.post('ajax.php', {variable: variableToSend});
//in php
<?php echo $_POST['variable']?>;
This code won't work,
Because AJAX is something that works in the background, So there is no way the "echo " in PHP will display the data, Because the data returns back to the success:function and then that can be consoled or printed on the HTML
Here is an example code of how it works:
var variableToSend = 1;
$.ajax({
url:"ajax.php",
method:"POST",
data: {
variable:variableToSend
},
success:function(data){
console.log(data);
}
})
Hope you understood how AJAX works
I know this question was already answered one million times but I'm becoming desperate with this code.
I have two files php files and I want to send a variable from a part written in JS to the other PHP file. So here's the code:
carga_datos.php
<script>
function MyAlert() {
var radio1 = $("input[name='inputTipoActividad']:checked").val();
$.ajax({
url : 'post.php',
type : "POST",
data: {'radio1' : radio1},
dataType:'json',
success : function(data) {
alert(data);
},
});
}
</script>
I'm calling to MyAlert() in a radio button form
post.php
<?php
$radio1 = $_POST['radio1'];
echo $radio1;
?>
And I call post.php into carga_datos.php like this:
And this is the error I'm retrieving:
Notice: > Undefined index: radio1 in C:\xampp\htdocs\gis\post.php on line 2
Edit:
It seems you have used dataType "json" so it will expect a "json", if none is returned you will get undefined or an empty response.
If you remove dataType: "json" you should be able to retrieve the data just fine.
function MyAlert() {
var radio1 = $("input[name='inputTipoActividad']:checked").val();
$.ajax({
url : 'post.php',
method : "POST",
data: {"radio1" : radio1},
success : function(data) {
console.log(data);
}
});
}
If you want to check with "dataType: 'json'" still in your code, you need to return your PHP code like the following:
<?php echo json_encode($_POST); ?>
This will then either return your $_POST data or just an empty [] array.
// Old Answer for just true/false values
If you just want to see if the checkbox was checked or not to retrieve a boolean, please try the following:
var radio1 = $("input[name='inputTipoActividad']").prop("checked");
This will return TRUE or FALSE. If not wrong, if you use
$("input[name='inputTipoActividad']:checked").val()
it'll return "on" or nothing (might be wrong here though).
Tested it with the ".prop("checked")" and it worked for me.
I am trying to define id# of a choice and declaring it as variable send to "action.php", the file that connects to DB and inserts values.
Div-block with 5 id's in HTML:
<div class="rate">
<div id="1" class="b-1 rate-btn"></div>
<div id="2" class="b-2 rate-btn"></div>
<div id="3" class="b-3 rate-btn"></div>
<div id="4" class="b-4 rate-btn"></div>
<div id="5" class="b-5 rate-btn"></div>
</div>
anim.js intercepts the click event and declares the variable "therate" as clicked "id":
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.b-'+i).addClass('rate-btn-active');
$.ajax({
type : "POST",
url : "action.php",
data : therate,
success:function(){alert(therate)}
});
};
});
Second part of above code sends "therate" var to an "action.php". But unfortunately id doesn't=( success:function(){alert(therate)} shows me the id# on every choice no problem. "action.php" is in the same folder as "anim.js". I have also tried "/action.php" - no luck. The problem is anim.js does not send "therate" to "action.php". I'm sure this is really stupid and newbie problem but I don't recognize it=( Please, show me the problem! Thanks.
Knowing the php part of the script will help a lot. It is where you decide what data is returned to the client. Typically it goes something like this:
php
$therate = $_POST['therate'];
$response = array();
if(isset($therate)){
$response['status'] = 'success';
$response['therate'] = $therate;
} else {
$response['status'] = 'failure';
$response['message'] = 'Variable therate is not set.'
}
echo json_encode($response);
jQuery
$.ajax({
type : "POST",
url : "action.php",
data : {'therate': therate},
success:function(data){
var o = $.parseJSON(data);
if(o.status == 'success'){
alert(o.therate);
} else {
alert(o.message);
}
}
});
Notice the addition of adding a key identifier to the data we are sending to the server. This allows us to pull the post data serverside easily. Also notice the 'data' in the success function argument. This is the actual data returned from the server. Which you will notice below we can easily parse as json due to using json_encode to the array we passed back to the client.
I hope this helps! Let me know if you have any questions.
I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.
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