How to put response of an AJAX in SPAN? - javascript

i want to post an input and select to an php site using ajax and get the result displayed in a span using the success function.
After searching, I can't get it really done, below is my code so far:
<span id="span_to_post_response"></span>
$(document).on("click", "#btn_to_click", function () {
var form_to_send_in_var = $("#form_to_serialize").serialize();
$.post('<?php echo base_url();?>api/mySite',form_to_send_in_var);
});
Where do I put my success function?

Instead of using .post function,Try using something like this
jQuery.ajax({
url: '<?php echo base_url();?>api/mySite',
type: 'POST',
data: {
// Send the data you want
// email: jQuery('.address').val()
},
success: function(data){
jQuery('#span_to_post_response').text(data);
},
error: function() {
jQuery('#span_to_post_response').text('Sorry, an error occurred.');
}
});

Related

Passing JavaScript variables to PHP function using AJAX

In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}
you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}
Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.

Ajax select list

I want to retrive the result of this kind of data list with CakePHP 3
<?= $this->Form->select('notif_message',
[ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?>
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?>
The goal is when a user chosse a value, an Ajax call to this controller be done
public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui
{
if ($this->request->is('ajax')) {
$notifmessage = $this->request->data('notifmessage');
if($notifmessage == 'oui')
{
$new_notif_message = 'non';
}
else
{
$new_notif_message = 'oui';
}
$query = $this->Settings->query()
->update()
->set(['notif_message' => $new_notif_message])
->where(['user_id' => $this->Auth->user('username') ])
->execute();
$this->response->body($new_notif_message);
return $this->response;
}
}
And i would like to do this call in Ajax without reloading , i have this script
<script type="text/javascript">
$(document).ready(function() {
$('.notif_message').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: 'select.notif_message' + val,
success: function(data) {
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
});
</script>
he doesn't work, nothing happend but i don't know why, i don't have any message in log, i can't debug without indication what doesn't not work
Thanks
In yout javascript you should use $('#notifmess').change(… or $('[notif_message]').change(… instead of $('.notif_message').change(….
In CakePHP the first argument of the select method will be used as the name attribute of the select tag.
Update:
In your controller you are retrieving the value of $_POST['notifmessage'], which is the name of the hidden input field.
To get the user's choice you either should use $this->request->data('notif_message'); in the controller, or setting up the ajax request to send the data with notifmessage like so:
$('[name="notif_message"]').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: {'notifmessage' : this.value},
success: function(data) {
// To change selected value to the one got from the server
$('#notifmess').val(data);
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
(Where in this case this is referring to <select> tag.)
i'm close to success: my ajax call is working, database update is working , i juste need to put the 'selected' to the other , i'm trying with this jquery code
<script type="text/javascript">
$(document).ready(function() {
$('#notifmess').change(function(){
var id = $('#notifmess').val();
$.ajax({
type: 'POST',
url: '/instatux/settings-notif_message',
data: {'id' : id},
success: function(data){
$('#notifmess option[value="'+data.id+'"]').prop('selected', true);
},
error: function(data)
{
alert('fail');
}
});
});
});

jQuery Ajax not sending Post data to PHP file

I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];

checking returned data from PHP script through jquery

I have written a php script
cch.php
$stmtcheck = $mysqli->prepare("SELECT id FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id);
$stmtcheck->fetch();
$stmtcheck->close();
And jquery for submitting form is
recover.php
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function()
{
alert("unlocked");
}
});
});
Now what I want to check whether $id has some value or not! How would I fetch the $id variable to my main script?
In cch.php, if you want to pass only an id to the javascript, you can print id
echo $id;
What ever data is received on ajax response will be passed as parameter to the success callback function. Either you have to execute the success actions inside the succes call back OR You have to write a function to be executed on ajax success and call that function and pass the params
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function(responseData)
{
if (responseData == '' )
{
alert("Sorry failed");
}
else
{
alert("Success");
}
}
});
});

unable to get value in controller from jquery, ajax in php code igniter

AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}

Categories