Append() Ajax not working correctly - javascript

I want to load my menu navigation from database. I have this HTML:
<ul id="nav-mobile"></ul>
Now I want to append data on success of ajax request into id="nav-mobile"
I am using this code:
$.ajax({
url:"/findRubriques",
type: "GET",
success: function(rubriques) {
$.each(rubriques, function(i, rubrique) {
$('#nav-mobile').append("<li>" + rubrique.libelle + "</li>");
});
}
})
The problem is when I load my page, the menu is displayed correctly and other times the menu is not displayed. However in both cases when I check my logs in the browser, my ajax request code ajax is 200

What are you trying to pass to $.each? A json string? If yes, you should add dataType to your ajax configs, to specify how to parse the response. Else, you can parse manually rubriques using JSON.parse().
Add an "error" callback too, so you can print the error if ajax can't parse your response.

Related

Load a Page with Ajax and sent Data to the Page

I have a page where I generate a javascript Array and I want to send it to the berechnungsauswertung.php page and load that page. And than I want to use the data at this page in php.
$.ajax({
type : 'post',
url : 'berechnungsauswertung.php',
data : {
marker : JSON.stringify(data),
homemarker : JSON.stringify(datahome)
},
complete : function(data){
$('body').load( "berechnungsauswertung.php" );
}
});
on the next page I want to get the Variables
$marker = json_decode($_POST['marker']);
$homemarker = json_decode($_POST['homemarker']);
but it does not work. How can I load a Page like this?
This is what you are doing:
Make Ajax request with POST data
Ignore the response
Make Ajax request without any data
Include the content in the page
It doesn't work because you don't have the data from 1 when you are loading the new content in 4.
Replace your complete function with a success function. Do something with the data you get (the first argument to the success function) such as passing it to jQuery('something').html(data).
Don't use load at all.

Getting the Error on making ajax call?

I have made an Ajax call to one of my pages sitting in the server. When I am making the Ajax call, I am not getting the data. But instead I am getting status 200 OK with red font-color in the firebug. I am not able to figure out what the problem is.
I am making an ajax call to these api pages:
[{"ID":"001","name":"Naidu","school":"Hyd","hobby":"cricket"}]
My ajax call is like:
$.ajax({ url: 'http://something.com/api/name',
data:{},
type: 'post',
dataType: "json",
success: function(output) {
//alert("SUCCESS");
alert(output);
}});
Make sure API returns a status message when call is made.
Also retured output should be in json format. If you want to see exact output even if that is not json , remove DataType:"json" part from script and you should be able to see exact response.
Chances are that API isnt returning a message in one of the two cases or returned output is not json datatype.
Make sure you are not doing cross-domain ajax.

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

How can I call these urls in jquery to display content on one page?

ok I figured out the jquery part but not the parameters of them all can anyone help figure out the parameters for each url string?
this is the jquery I figured out!
also would this work better then what the below answer?
$.get('adminajax.php', {'action':'getUsers'}, function(data){
$('#users .users').html(data);
});
He sent me this in an email:
You can specify a page by adding: p=[page #] You can specify a file
and it will add a checkbox next to the user which will be checked if
the user has permission to download: file=[file location]
adminajax.php?action=createDirectory&directory=[new directory location]
adminajax.php?action=setAvailability&user=[username]&file=[filelocation]&available=[true or false]
I'm trying to get it to display in these html tags:
<div id="files">
<b>Files:</b>
<ul class="files"></ul>
</div>
<div id="file_options">
<b>Options:</b>
</div>
<div id="users">
<b>Users:</b>
<ul class="users"></ul>
</div>
What you are trying to do is Ajax call. Here's an example:
$.ajax({
type:'GET',
url:'adminajax.php',
data: {action:'getDirectory', directory:'directoryNameHere'},
success: function (response) {
//here the response is the stuff that the server replied with
var json = $.parseJSON(response); //if the server returned JSON you need to parse it
//do stuff with that data
}
});
This is the code for the first example to get files. Adjust accordingly for other examples.
The server response should be available in the success function. Try to console it out to see what you got from it, if it's JSON it needs to be parsed first.
Url seems to be the same for all examples, only the action and other parameters are changing, so for other calls you only need to change the data properety of the ajax call.
For getting users your data object would be just action, there are no other parameters:
data: {action: 'getUsers'}
For creating a directory:
data: {action:'createDirectory', directory: 'nameOfDirectoryHere'}
As charlietfl noted in the comments, you don't need to do $.parseJSON if you put dataType: 'json' in the ajax call. (If the data is JSON of course).

update the div display after jquery post without reloading the page in mvc3

What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/

Categories