Update Span Element with Ajax and php - javascript

Hello again stack overflow
I have a simple PHP file (countsomething.php) that looks up a number and echo's it.
How do I get ajax to update a simple span element on my HTML page.
I've tried triggering the ajax on page load with : <body class="skin-blue" onload="updateCDNonts();">
The JS
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php=", function(result){
$("#countonts").html(result)};
}
The HTML
<span id="countonts" class="info-box-number">0</span>
Can someone point me in the right direction ?

You have a few issues with your code i have tried to point them all out below for you:
function updateCDNonts() {
$.get("x.x.x.x:8080/getliveontscdn.php", function(result){ //removed equals from url
$("#countonts").html(result); //removed curly brace that shouldn't be there
}); //added missing bracket and semicolon
Also as someone else noted watchout for cors if your url is different.

I managed to get it working. I changed my php script to return a json, here is the json: {"cdnonts":"144","eagonts":"0","stamonts":null,"foxonts":null,"pentonts":null,"topponts":null,"wickhamonts":null}
And in the html I did the following
<script language="javascript">
window.onload = function() {
$.ajax({
type: 'GET',
url: 'countallonts.php',
dataType: "json",
data: { get_param: 'cdnonts' },
success: function(data){
$('span#cdnonts').html( data.cdnonts);
$('span#eagonts').html( data.eagonts);
}});}
</script>
Although I am not sure why it works, because I expected data variable to return just the "cdnonts" object, but I suspect it parses all of the objects instead?
Thank you for you help.

Related

Assign value to Paragraph or P tag through jQuery for the data obtained from PHP

I need to set the text of Paragraph or P tag to the value obtained though AJAX.
So I have the HTML page somewhat like this where I have declared the paragraph tab.
<p class="card-text">Client Type<p id="Client_Type" name = "Client_Type"></p></p>
Onclick of the button I am making the AJAX call to HOME_CARD.PHP page.
The PHP is working properly and its returning me the data to jQuery. When I use console.log(data); it displays me all the data correctly.
$.ajax({
url: "Home_Card.php",
method: "POST",
data: {
search_client_id: search_client_id
},
success: function(data) {
console.log(data);
$('#Client_Type').val(data.CLIENT_MNEMONIC);
//$('#Client_Type').text("HELLO");
//$('#Client_Type').attr(data.CLIENT_MNEMONIC);
//$('#card').show();
//$('#Client_Type').("HELLOE");
}
});
So I tried using val function to assign the value in CLIENT_TYPE to p tag in HTML page but its not assigning. When I use $('#Client_Type').text("HELLO"); it assigns the value "HELLO" properly so I am guessing nothing wrong with my program.
I wanted to know is there any other way of assigning the value to paragraph tag in jQuery?
How to assign the specific value obtained from PHP in JSON format to paragraph p tag using jQuery.
Paragraph does not take any value i think.
So you should use one of these methods
$('#Client_Type').text(data.CLIENT_MNEMONIC);
or
$('#Client_Type').append(data.CLIENT_MNEMONIC);
Use text method or html method instead:
$('#Client_Type').text(data.CLIENT_MNEMONIC)
Use html or append method
$('#Client_Type').html(data.CLIENT_MNEMONIC);
Thank you for your time and answers but I found my mistake.
During the AJAX call I did not mention the type of data I getting in return
datatype: "json",
Hope fully it will help someone who is also trying.
$.ajax({
url: "Home_Card.php",
method: "POST",
datatype: "json",
data: {
search_client_id: search_client_id
},
success: function(data) {
console.log(data);
$('#Client_Type').val(data.CLIENT_MNEMONIC);
//$('#Client_Type').text("HELLO");
//$('#Client_Type').attr(data.CLIENT_MNEMONIC);
//$('#card').show();
//$('#Client_Type').("HELLOE");
}
});

script doesn't load after ajax response

I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}

Ajax's data parameter not making it to the server

Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});

How to get the CSS-Code and save in a String?

I am trying to get the code of a CSS-File and save it into a String for later use. I already found something which could do the trick in another post, but nothing I tried was working.
$.ajax({
url: "css/style.css",
dataType: "text",
success: function(cssText) {
}
});
Can anyone help and tell me how to get and save the CSS-Code?
Thanks
Read thejQuery.get() API. Tells you right there.
var myData;
$.get( "your_css.css", function( data ) {
console.log(data);
myData = data;
});
console.log(myData);
Just a warning, due to JavaScript's nature, line 6 may fire off before line 3. Just food for thought.
EDIT
I know the console.log(myData); responds null. I meant it to. I was teaching him that if he does this, make sure that if the data is being manipulated anymore, either force it sync or put it in the callback. A better choice would be to put it in the callback.
If you are getting proper css as response then try using below function :
$.ajax({
url: "css/style.css",
dataType: "text",
success: function(cssText) {
// paste styles to head
$('<style type="text/css"></style>').html(cssText).appendTo("head");
}
});
You can add stylesheet, and disable it with attribute.
var href = "style.css";
$("head").append("<link id='Iwait' type='text/css' href='"+href+"' attribute>");
When you want to use your stylesheet, remove disabled attribute :
$("#Iwait").prop('disabled', false);

JQuery Form No reload : how to pass the $_POST info after success?

First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.

Categories

Resources