I've a code like this:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
I want to update the data returned by ajax using some global method
the code for updating a data will be loaded from the different file, so it can't be stored inside the current $.get function.
once data is updated by some global function, $.get should receive an updated code, not the original one
data should be updated for the HTML data only, not json or any other type of data
I know there's a global function available to handle success on ajax calls:
$(document).ajaxSuccess(function() {
$( ".log" ).text( "Triggered ajaxSuccess handler." );
});
The problem is, this function just receives data, I'm not sure how the data can be updated through this function.
Any ideas?
I guess you can use ajaxSetup function and set filter here like this:
$.ajaxSetup({
converters: {
'text html': function (data) {
console.log('haha! I\'ve stolen your data!');
console.log(data.substring(0,100));
return 'no data :)';
}
}
});
$.get('http://fiddle.jshell.net')
.success(function(data) {
console.log('I got:' + data);
});
In this DEMO only html data will be changed.
EDIT:
I used filter for text html (contains 2 identifiers: from type and to type) because it is mentioned in jQuery docs:
{"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
As I see it defines covertion from text to html. Usually there is no conversion, but you can add your own, which can modify data as you want.
EDIT2
If you want you can use the following "durty hack":
var originalFunc = $.get;
$.get = function() {
return originalFunc.apply(window, arguments)
.then(function(data) {
return 'no data again :)';
});
};
One more DEMO.
Or, dataFilter as follows:
$.ajaxSetup({
dataFilter: function(data) {
//console.log(data);
return 'sorry, guys, I lost data again';
}
});
$.get('http://fiddle.jshell.net')
.success(function(data) {
console.log('I got:' + data);
});
Next Demo.
Related
How do I display the response of a call to a Spring MVC Controller returning HTML? In my Javascript code I make a (GET) call to my Spring Controller. From what I can make is that the response from the call is HTML. I guess I need to replace 'alert(response)' with Javascript to display the html.
My Javascript code:
$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
alert(response)
}
});
} );
My controller code in Spring:
#GetMapping("/showFormForUpdate")
public String showFormForUpdate(#RequestParam("parcelId") int theId, Model theModel) {
Parcel theParcel = parcelService.findById(theId);
theModel.addAttribute("theParcel", theParcel);
return "parcel-form";
}
Here "parcel-form" is the name of a template.
$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
$.get(response.html, function(data, status){
$("#ID").html(data);
});
}
});
} );
response.html is the page you want to show on the success of get request. Just make a get request to the response.html file or any template file and put this file in any div where you want to show it.
Hope that it works
That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.
I'm noob, and i recently knew about Ajax, so dont worry if my question seems idiot.
I tried to do that, but i had no success, but i will explain what i tried to do:
I have one draggble box with some words, and everytime that i drag some elements to a certain place, i want to record this transition into my database.
So, i did that in Ajax:
UPDATE
$(document).ready(function() {
$(".event").draggable();
$(".drop").droppable({
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var targetid = event.target.id ;
$.ajax( {
type: 'post',
url: "new.php",
data : { 'day' : '3' },
success: function( response ) {
alert( response );
}
});
}
});
});
New file:
function eventTransition($day){
$day = $_POST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
eventTransition($day);
I tried to automatically put a value to the day variable.
Please try this in php file and reply if this helps you
function eventTransition($day){
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
$day = $_POST['day'];
eventTransition($day);
You cannot call a PHP function directly using Ajax. A(n over-)simplified new.php file may look like the following:
$day = $_REQUEST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
In your ajax call you must specify:
dataType: 'json'
As #baxri advises, add an error handler.
I had a json file results.json Which shown below. And I had a html file contain some script. This is for retrieve data data. When I am enter into the html page which call a script function get_machFollow(que_script) this function is for receive json file data. The function is works fine and which alert correct output, But after this function return some data to my HTML page.
My JSON file
{"mach_fol_4": {"match_l":
["7","8","99"],"attempts":"0","feedback_true":"You are right!",
"feedback_false":"Sorry! wrong answer."}}
This is my script function. This function is works fine but I can't alert the return value from HTML page. That shows undefined.
function get_machFollow(que_script)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
return return_var;
});
}
This is my html file
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(document).ready(function(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
alert(mach_follow_js);//Wrong output
});
</head>
<body>
<p>Hello world</p>
</body>
</html>
are you intending return return_var; to be inside the get_machFollow scope, because right now its inside the jquery function scope and will not return value to the main page
Here below JSON data fetched by AJAX. It passing JSON Data Object in Alert.
You can use it as you want. also can Iterate data using for loop or $.each function.
$(document).ready(function(){
var mach_follow_js;
// mach_follow_js=get_machFollow('mach_fol_4');
//JSON Data Fetched by AJAX
$.ajax('results.json',{
type:'GET',
dataType: "json",
jsonCallback: 'successCallback',
async: true,
beforeSend: function () {
//if you want to show loader
},
complete: function () {
//hide loader after download data
},
success: function (resultJSON) {
mach_follow_js = resultJSON; // assigning to Global variable ProductResult
alert(mach_follow_js);
console.log(mach_follow_js);
},
error: function (request, error) {
alert('Network error has occurred please try again!');//error
}
})
});
There are multiple ways by which you can do it. One of them is pass a callback handler to your method which will be called when you get the response. Try this:
function get_machFollow(que_script, sCallback)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
sCallback.call(null /* context */, return_var);
});
}
$(document).ready(function(){
var mach_follow_js;
get_machFollow('mach_fol_4', function(output) {
alert(output);
match_follow_js = output;
});
});
Use ajax callback function $.getJSON() is actually an ajax function. So you need to apply callback to perform this action.
I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.