I am trying to use Ajax to reload data from a database. However, the Ajax doesn't call the controller action that I specified in the url:. Here is my Ajax code:
function selectFieldChanged(id){
$.ajax({
type: "POST",
url: Routing.generate('demo_ajax'),
data: id,
success: function(){
alert("Success");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
$(document).ready(function(){
var id = $(this).val();
$('#form_patient').change(function(){selectFieldChanged(id)});
});
The routing.xml :
demo_ajax:
pattern: /ajax/patient
defaults: { _controller: DemoBundle:Default:index}
options:
expose: true
So, I tried to simply echo the value out in the indexAction to see whether it is called or not.
public function indexAction(Request $request)
{
if($request->isXmlHttpRequest()){
echo "xmlHttpRequest is called";
}
if($request->getMethod()=='POST'){
echo 'POST is called';
}
}
However, I didn't get anything from the indexAction but I got the alert message, `Success, from my Ajax What did I do wrong?
The success callback receives data from your server so a variable must be declared to capture it:
success: function(data){ // <-----
console.log(data);
alert("Success");
},
Related
I want to call PHP page using AJAX but I don't want to reload PHP classes each time, for example, on first time running AJAX, PHP page load and set data, but on second time running AJAX, php get the same data from first time.
function test() {
$.ajax({
url: "./test.php",
method: "post",
success: function(data) {
$(document).find("body").append(`<p>${data}</p>`);
}
});
}
<button type="button" onclick="test()">Click Me!</button>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
//test.php
class Test{
private $name = null;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$class = new Test;
if( $class->getName() == null ){
echo "oops";
$class->setName("pong");
} else {
echo $class->getName();
}
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// if the request failed or succeeded
request.always(function () {
//add your logic
});
Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);
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'];
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>";
}
I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};