First, sorry for my English, you can correct me in that area too :)
I know that i can replace text in html with <?=$var?> for example. Also, i can do it through ajax. I use $.ajax to get data in JSON format, than inside jquery i'm changing appearance of my web app.
This is example of getting data, and inside this function i'm calling $.View function where apperance is changing.
$.Model = function(route, data){
$.ajax({
url: "php/books.php?"+route,
type: "POST",
data: {data: data}
}).done(function(response){
var resp = JSON.parse(response);
$.View(route, resp, data);
}).fail(function(msg){
console.log('something is wrong');
});
});
};
Example of $.View function
$.View = function(route, response, data){
if(route==='menuItem'){
var studio='';
$.each(response, function(index, value){
studio += '<button id='+value['STUDIJI_ID']+' class="btn btn-primary studio_button">'+value['STUDIO']+'</button>';
});
$(studio).appendTo(".here");
}
};
So, my question is, what is the best approach for such things? Embed PHP variable to html or do it through jQuery on described way? Or, something third?
Thank you for your time and help.
It depends on your requirements.
If you know everything on page creation, insert the values with php.
If you wnat to update only parts of your page after page is loaded, do it with ajax.
Related
So i am trying to learn Ajax with jQuery, to retrieve some information. At the moment, I have problem to get the information. My code is very simple at the moment, just because I want to learn how it works. This is my HTML code.
<h2>Hello world</h2>
<p id="response"></p>
My jQuery code:
$(function(){
$('h2').on('click', function() {
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
error: function(data){
console.log("tjohejsan");
}
})
});
});
So when I click on h2 it should retrieve data. What I want is to make a call from my database to get information about the users.
So my php code looks like this:
$sql = "SELECT * FROM moment2";
$result = mysqli_query($db,$sql) or die("Fel vid SQL-fråga");
$array = array();
while($row = $result->fetch_assoc())
{
$array[] = $row;
}
echo json_encode($array);
At this point, this is where it fails. I don't know really where the problem is. Because I want an associative array.
I would appreciate it if you could assist me, because as I mentioned, I don't really know how to solve it from here.
Thanks in advance!
EDIT: I realised I had a typo while writing this. changing data['name'] to key['name']
You have issue in the jquery each function. Replace the success function as
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
It is because jquery each function has key and value as argument, so only replace "data" by "key" in your this line: $("#response").html(data['name'])
There are a couple places that you are going to run into trouble with this. Here is a JSFiddle for you to reference with my tips below:
https://jsfiddle.net/MrProvolone/zgw9ymv3/2/
There are a few things to consider...
1). Your returned data needs to be converted using parseJSON(), which is a built in jQuery function. This will convert your JSON string into a JavaScript object.
2). When you are looping through your object, you need to include the number (i) that you are trying to access
3). Because we are making a new object variable, we don't need the "key" designator in your $.each() function call... so it becomes $.each(data, function(i){}); instead of $.each(data, function(i, key){});
3). When you are trying to write out your html, you must grab what is already in the container, then add your new html to it, and finally write it all back out to the container.
Here is a step by step:
Instead of:
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
}
We need to add the parsing (and remove the "key" variable per #3 above) so it becomes this:
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(data, function(i){
$("#response").html(key['name']);
});
}
Now we have a new variable to work off of (parsed) so we need to change both the $.each line, and the .html() line to make sure it uses that new variable....
So this:
$.each(data, function(i, key){
$("#response").html(key['name']);
});
Becomes this:
$.each(parsed, function(i){
$("#response").html(parsed['name']);
});
But that still won't work. We are looping through the object, so when we try to access a value, we have to specify which element in the object we are trying to get to. So anywhere in your loop that looks like this:
parsed['keyname']
becomes this:
parsed[i]['keyname']
So now we have:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
At this point you should be getting some html in your container. However, you will notice that you are only getting the value of the last row of your data. That is because you are overwriting ALL of your html in the container in each loop, instead of adding to what is already there. We need to make a new variable to fix this. So this:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
Becomes this:
$.each(parsed, function(i){
var oldhtml = $("#response").html();
$("#response").html(oldhtml + '<br>' + parsed[i]['name']);
});
Now you will see each result, with a html line break between each one.
Hope this helps!
In your js, on the success callback, you are using the wrong data, and not appending the data retrieved to the html Tag
Here is an essai
success: function(data){
if(typeof data != "object"){
data = JSON.parse(data);
}
$.each(data, function(i, key){
$("#response").append(key['name'])
});
}
I have a problem with my JQuery script. I am making a 2d chat where people have their own figure like Habbo hotel, but the JQuery script that is suppose to move the figures is bugging.
I think it is easier to show the problem:
Click here to see the problem
I am using the following script to update the figures:
function UpdateRoom() {
var data = 'roomId='+roomId;
$.ajax({
type: "GET",
url: "chatfunctions/updateroom.php",
dataType: 'json',
data: data,
success: function(data){
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
}
});
}
The #f+temp is the id of the field that the figure should be places at. The charId is the id of the figure.
And then I am calling the script every 500 miliseconds:
window.setInterval(function() {
UpdateRoom();
}, 500 );
Im not sure if this is enough code and example for you guys to help me. If not please tell me if I need to provide more for you to help me. My guess is that it is the .append(); function that is used wrong, but I'm no expert in JQuery.
You are only continuing to append but not replacing anything.
Try to either use .html() or .empty().
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).html('<div class="user" id="'+charId+'" />');
});
or
$.each(data, function(i, data) {
var temp = parseInt(data.field);
$('#f' + temp).empty(); // clear out all content
$('#f' + temp).append('<div class="user" id="'+charId+'" />');
});
not knowing your code you might need to move the call to .empty() outside your each loop.
First I want to show you guys what I am trying to do.
I am trying to create a search functionality in my application using AJAX, jquery and php
and as for the framework I am using Codeigniter, but it's not necessary to be CI, this could be similar to all(well I suppose).
I have this piece of code to observe a focus and blur event.
$("#searchbox").on({
keyup : debounce(function(){
MSI.Interface.search();
},350,false),
blur : function(){
$("#search_results").hide();
}
});
I have not finished it yet that is why the blur event has only .hide() . I can't think of what other else to include, maybe reset the html of the #search_results to make it blank, but I don't know if that is reasonable.
1st question: What do you think is a more reasonable solution for that?
As you can see in the previous code, i have the debounce function, just to prevent per character request on the server, I wonder if that is correct.
Then I have this search function
search : function() {
var keyword = $("#searchbox").val();
if (keyword == '') {
} else {
$.ajax({
url : MSI.variables.base_url + 'search',
type: 'POST',
data: {
keyword : keyword
},
dataType : 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
$("#search_results").show().prepend("<p>"+value+"</p>");
});
});
}
});
}
}
With that code, the script will be able to add contents to the #search_results div.
2nd Question: What do you think is a better solution for this?
I had a question before about implementing datepicker with jqgrid. I think that question was too specific. I would like to know, has anyone been able to implement a datepicker with a dynamic jqGrid? The colModel, colNames, and in my case, data are generated server-side via an ajax request, then displayed locally. On the server, in PHP, I create an array with the colModel structure, then JSON encode it before sending it back to client. Valid JSON puts quotes around the keys, but according to examples here, here, and (importantly) here, I'm not supposed to do that.
I tried to use regex to remove the quotes, but that just results in a javascript error because it can no longer parse the now-invalid JSON.
Is datepicker with dynamic colModel possible?
Here is the AJAX request:
$(document).ready(function(){
$.ajax({
type: "GET",
datatype: "json",
success: function(result){
try{
//alert(result);
result = jQuery.parseJSON(result);
}catch(err){
alert("error in success json " + err);
return;
}
var colN = result.colNames;
var colM = result.colModelList;
var colD = result.colDataList;
grid.jqGrid({
datatype: 'local',
colNames:colN, //column names
colModel:colM, //column options
data:colD, //table data
editurl: 'clientArray',//changes are not sent to server
cellEdit: true,
cellsubmit: 'clientArray',
});
}
});
});
and an example colModel:
{
"editable":true,
"name":"date",
"index":"date",
"sorttype":"date",
"editrules":{"date":true},
"editoptions":{"dataInit":"initDateEdit"}
}
Look at this answers. It should solve your problem.
I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.