passing variable back from the server to ajax success - javascript

User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function ()
{
var html='$res1 from the server should be here instead of this string';//var html=$res1.
$.fancybox(
{
content: html,//fancybox with content will be displayed on success resul of ajax
padding:15,
}
);
}
});
=========================
OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:
PHP:
<?php
$res1="hello";... // handle logic here
echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>
AJAX
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
$.fancybox(
{
content: html,//returns hello+page in the fancybox
//if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
// content: console.log(html)
padding:15,
}
});
=============
New update:
Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed.
That's why.
Fixed.
Thank you.
Everybody.

Assuming you're using PHP:
PHP:
<?php
... // handle logic here
echo $res1; // print $res1 value
?>
AJAX:
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
// given that you print $res1 in the backend file,
// html will contain $res1, so use var html to handle
// your fancybox operation
console.log(html);
}
});
Enjoy and good luck!

$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function(html){ // <------- you need an argument for this function
// html will contain all data returned from your backend.
console.log(html);
}
});

Related

Transfer to another page in AJAX call

Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}

Getting Alert from ajax request

I have editable html table of user Information. There are some columns such as user_ID, branch_ID etc. when I am going to change the branch_ID of the user I want to check the particular user has tasked assigned to him or not. If he has tasks then update is not allowed. for that I am using the following java script part.
if(field=='branch_ID'){
$.ajax({
type: 'post',
url: 'check_user.php',
data: {udata: user_id},
success: function (data) {
// message_status.text(data);
}
})
}
In check_user.php
$user_id= $_POST['udata'];
$sql1="SELECT * FROM assign_task WHERE user_ID=$user_id";
$query1=mysqli_query($con,$sql1);
if(mysqli_num_rows($query1)>0){
echo"you can't update";
return false;
}
else{
echo"ok with it".$sql1;
}
The thing is I want the respond from check_user.php as an alert and return false to stop updating the content. As I am new to jQuery please help me.
You can use JSON to pass more complex data:
PHP :
if(mysqli_num_rows($query1)>0){
echo json_encode(array("success" => false));
}
else{
echo json_encode(array("success" => true,
"message" => "ok with it".$sql1));
}
Javascript:
success: function (data) {
var jsonData = JSON.parse(data);
if(jsonData.success){
alert(jsonData.message);
}
}
Remember to do more advanced checking on your variables and types first!

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

jquery function not redirecting url

I am working with codeigniter and jquery. I am using ajax to send some info to a codeigniter function to perform a db operation , in order to update the page. After the operation is complete I am trying to refresh the page. However the refresh works inconsistently and usually I have to reload the page manually. I see no errors in firebug:
var message = $('#send_message').val()
if ((searchIDs).length>0){
alert("searchIDs "+searchIDs );
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
success: function(){
alert("OK");
},
complete: function() {
location.href = "pan_controller/my_detail";
}
})
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("OK");
location.href = "pan_controller/my_detail";
});
} else { alert("nothing checked") }
break;
How can I fix this?
addendum: I tried changing to ;
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "pan_controller/my_detail";
});
}
})
This is just defaulting to the website homepage. again, no errors in firebug
Add the window object on location.href like this:
window.location.href = "pan_controller/my_detail";
Try to use full path like
$.ajax({a
type: "POST",
url: "YOURBASEPATH/AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "YOURBASEPATH/pan_controller/my_detail";
});
}
})
BASEPATH should be like this "http://www.example.com"
Try disabling the csrf_enabled (config/config.php) and trying it. If that works, then re-enable the protection and, instead of compiling data yourself, serialize the form; or, at least include the csrf hidden field codeigniter automatically adds. You can also use GET to avoid the CSRF protection, but that's least advisable of of the solutions.

pass jQuery modal variable to PHP script

I do believe am over-complicating this, but I have a jQuery modal that talks with a PHP file. The file has all the form and validation, but it's included in the modal. The event is triggered on right-click (so a user right clicks the folder to edit, selects "Edit", the action below triggers. It's supposed to send the folder id to the modal, so the modal displays the edit form with the correct folder. Right now, it doesn't send anything.)
So I have the jquery (script.js):
"action": function(obj) {
var data = {'pid': obj.attr("id")};
$.post("/folder/edit.php", data, function (response) {
$('#modalEditFolder').modal('show');
});
}
// also tried this:
$.post("/folder/edit.php", data, function (response) {
$('#modalEditFolder').data('pid', obj.attr("id")).modal('show');
});
// and this
$.ajax({
type: "POST",
url: "/view/folder/edit.php",
data: {pid: obj.attr("id")},
success: function(html) {
$('body').append(html);
$('#modalEditFolder').modal('show');
}
});
The modal (modal.php):
<div class="modal-body">
<?php include_once("/folder/edit.php"); ?>
</div>
The PHP file (edit.php):
<?php echo $_POST['pid']; ?>
How can I get both the modal and php form to get the PID variable?
try this :
$.ajax({
type: "POST",
url: "/view/folder/edit.php",
cache: false,
data: {'pid': obj.attr("id")}
}).done(function(html) {
$('body').append(html);
$('#modalEditFolder').modal('show');
});

Categories

Resources