Ajax calling PHP and getting Return value - javascript

Not used Javascript -> Ajax -> PHP -> Javascript before and I am struggling to pick-up the return value. Ajax is calling the PHP, but all I am getting back is the HTML for the web page. Can anyone see what I am doing wrong?
Javascript: -
onChange: function(value, text, $selectedItem) {
jQuery.ajax({ url : 'index.php', type : 'post', data : { action: 'getTest', param : text },
success: function(result){
console.log('Sucess',result);
},
failure: function(result){ console.log('Failed'); }
});
}
PHP: -
$_action = isset($_Post['action']) ? $_Post['action'] : '0';
if ($_action == 'getTest') {
$test = $_Post['param'];
echo $test;
exit;
}
As I said, RESULT just seems to contain the page's HTML and not the expected string value.
Thanks

Your post variable is with small caps letters. However the Variable should be full caps ($_POST). So your php is not going into the if statement.
https://www.php.net/manual/en/reserved.variables.post.php
To debug these kind of issues start logging variables like $_action and check if their value is what you expect it to be. Then check if the if statement actually fires, etc. until you find the error.

Related

Error by passing variable from JS to PHP

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.

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

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();

Echo PHP message after AJAX success

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.

using returned json values in calls not working

Trying to use the values I return from my php yet there are not working properly.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
// fade out the deleted comp
$("#c"+response.computer_id+"").fadeOut("slow");
// remove from the drop down
$("#comp_selection option[value='#c"+response.computer_id+"']").remove();
} else {
alert('Some error occurred.');
}
});
});
});
</script>
I am returning from the php file :
echo json_encode($ajax_result);
which is returning :
{"computer_id":1,"success":"success"}
EDIT: I found a small error in code outside of this where I was returning a different value than expected. All is well and the above was indeed correct to start with.
You should debug using firebug or whatever developer tools you have in your browser - firebug in Firefox is very good for this as you can see the JSON data passed back from the AJAX call.
That said, your issue is that the data is probably under response.d - so look at response.d.success and response.d.computer_id
Maybe the content you are receiving from your PHP server is sent as simple text, and must be sent with the headers set for JSON content:
header('Content-Type: application/json');

Categories