This is my xmlhttprequest so after i some text in the search bar. the ajax works fine. it gives back the information that i want.
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "SavingsAddSearch.php";
var sb = document.getElementById("searchWord").value;
var vars = "search="+sb;
if(sb == ""){
hr.open("GET", url, true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function (){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
hr.send();
document.getElementById("demo").innerHTML = "processing...";
}
else{
hr.open("POST", url, true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function (){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("demo").innerHTML = "processing...";
}
}
but after the data was fetch from the database. the problem is the jquery effects like hide and slideToggle can't load. but i know my effects works fine. can someone help me how to load the data using ajax with the jquery effects. my jquery target html is in the php side.
Related
I'm using WordPress & trying to add some AJAX.
I have a file in [template]/js/ajax.js
function readSearch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
alert(xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "ajax_info.php", true);
xhttp.send();
}
I've put ajax_info.php everywhere and I still get a xhttp.status == 404 when the button is clicked
<p class="submit"><input type="submit" name="submit" id="submit"
class="button button-primary" value="Leave it to chance" onclick="readSearch()" /></p>
I have test for the file to be displayed in
I'm not sure what I'm missing to get the call to work.
Note : You need to add the full path to your php file as :
There are two ways to do it :
1) Mentioning Path Manually :
function readSearch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
alert(xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "wp-content/themes/template_name/ajax_info.php", true);
xhttp.send();
}
2) Using WordPress Functions To Add Path (Which Works In Dynamic Way) :
function readSearch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
alert(xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", <?php echo get_template_directory_uri()."/ajax_info.php"; ?>, true);
xhttp.send();
}
I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>
I earlier asked a question about a xmlHttp.send() code that wasn't working. I thought I had fixed all of it, but now I've got another problem.
In the handleServerResponse() function, the code errors out in the if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200). Why is it doing that? An example php code is under the JavaScript.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cant create that object hos");
}else{
return xmlHttp;
}
}
function newuser() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
name = encodeURIComponent(document.getElementById("name").value);
queryString = "name=" + name;
xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerRespons;
xmlHttp.send();
}else{
setTimeout('newuser()', 1000)
}
}
function handleServerRespons(){
if (xmlHttp.readyState == 4){
if (xmlHttp.readyState == 200){
alert('1234545');
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
}
}
}
php code:
$name = $_GET['name'];
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo $name;
echo '</response>';
instead of using a variable (xmlHttp) you must use this in an onreadystatechange event callback
so your function will be:
function handleServerRespons() {
if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
xmlResponse = this.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert( message );
}
}
or wrap your code with (function(){...})(); like below
(function() {
// all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();
xmlHttp.readyState can't be 200. you should use xmlHttp.status.
xmlHttp.readyState has status of the XMLHttpRequest The XMLHttpRequest Object
xmlHttp.status will be available when xmlHttp.readyState is 3 or 4. When available xmlHttp.status should represent the HTTP status code.
I have a textarea where I put some C++ code, then I get that code with javascript and send it to a PHP script via AJAX to be processed. The problem is that the code gets corrupted in the way.
Here is my code:
function showResult()
{
var code = document.getElementById('code').value;
var input = document.getElementById('input').value;
if (code != '') {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ideone.php?code=' + code + '&input=' + input, true);
xmlhttp.send();
}
}
PHP:
<?php
echo 'Code: '.$_GET['code']; // Empty string
?>
You need to quote your query string:
xmlhttp.open('GET', 'ideone.php?code=' + encodeURIComponent(code) + '&input=' + encodeURIComponent(input), true);
This is the code I have. I'm trying to insert a image to show that ajax is loading but I just can't get this right; I tried a lot of possible ways but it just isn't working. Any suggestions on what to do?
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);
You can approach this in a couple of different ways, you can either
Preload image and create the element when the request is sent and destroy it after it's done
Create it along with the document and then hide it until the request is sent, and then hide it again when it's done
A combination of the two: Preload and create element in javascript, and from there just hide/show the element at each request/completion.
#1 Is probably most preferred when the request is rarely sent, since it doesn't interfere with the document's load, but rather loads after everything else is done. Since creating/destroying an element takes up more processing time than simply hiding/showing the element, this is not a recommended approach.
#2 Is preferred when the request is sent frequently, since you'll be using the loader image often, there is no need to create/destroy it and just have it available from the start. I recommend this approach.
#3 Is preferred when you want to play it safe. This doesn't load the image until the page is done loading and requires very little processing time.
Example #1 | Code
HTML
<div id='content'></div>
Javascript
var PreloadIt = new Image(441,291);
PreloadIt.src="loader.gif";
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('content').removeChild(document.getElementById('ajaxloader'));
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
var eLoader = document.createElement("img");
eLoader.src = "loader.gif";
eLoader.alt = "";
eLoader.id = "ajaxloader";
document.getElementById('content').appendChild(eLoader);
http.send(params);
}
BeginLoading();
Example #2 | Code
HTML
<div id='content'>
<div id='ajaxloader'><img src="loader.gif" style="display: none"/></div>
</div>
Javascript
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('ajaxloader').style.display = "none";
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
document.getElementById('ajaxloader').style.display = "block";
http.send(params);
}
BeginLoading();
Example #3 | Code
HTML
<div id='content'></div>
Javascript
function CreateLoader(){
var img = document.createElement("img");
img.id = "ajaxloader";
img.src = "loader.gif";
img.alt = "";
document.getElementById("content").appendChild(img);
img.show = function(){ img.style.display = "block"; }
img.hide = function(){ img.style.display = "none"; }
img.hide();
return img;
}
var eLoader = CreateLoader();
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
eLoader.hide();
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
eLoader.show();
http.send(params);
}
BeginLoading();
Misc
I would recommend keeping track of the returned status. When a request fails, your code will return an error, since you're not handling it. Make sure that the request was a success and handle your errors.
You should also consider using encodeURIComponent(), if you've got data with special characters, like spaces and such.
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var url = "main_search_special.php"
var parameters = "section=special&category=" + encodeURIComponent(category) + "&brand=" + encodeURIComponent(brand) + "&item=" + encodeURIComponent(item);
ajaxRequest.open("GET", url+"?"+parameters, true);
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && http.status == 200){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}else{
console.log("Request for \""+url+ "\" failed.");
}
}
ajaxRequest.send();
Just add the image to your display area before you send the request. The results will overwrite it when the request completes.
...
var ajaxDisplay = document.getElementById("main_result");
ajaxDisplay.innerHTML = "<img src='loading.gif' />"
ajaxRequest.send(null);
I'd recommend putting the return action into its own function to make it look a little cleaner
But all you have to do to add an image is:
Before you do your send (basically anywhere in the function), create the image element and append to whatever element in your html you like
When you get a return from your ajax call, delete the image element.
this is what you can do-
set an image at your favorite position.make it's visibility to hidden.before making a call to php make it's visibility to visible and again after response from php file you can make your image's visibility to hidden.
This is one of the way you can do this,there are also other ways.
search.onclick = function()
{
var ajaxRequest;
document.getElementById("image_loading").style.visibility = "visible";
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("image_loading").style.visibility = "hidden";
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);
}