WordPress AJAX live search without jQuery - javascript

I'm trying to make ajax live search on WP website without usage of jQuery cause I don't want to load additional 80kb for this feature. I already made it work with jQuery, but when I try to rewrite script to work with Vanilla jS, I always got the issue
wp-admin/admin-ajax.php 400 (Bad Request)
working code
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
VANILLA JS CODE that doesn't work
var request = new XMLHttpRequest();
request.open('POST', '<?php echo admin_url("admin-ajax.php"); ?>', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
console.log('if');
} else {
console.log('else');
}
};
request.onerror = function() {
console.log('onerror');
};
var data = document.getElementById('keyword').value;
request.send(data);

The obvious problem I see without knowing your problem is that request.send(data); does not equal to { action: 'data_fetch', keyword: jQuery('#keyword').val() } instead you should be writing something like this request.send('action=data_fetch&keyword='+data);
Also, depending on the data value you are passing you may need to encode it. Again, it is somewhat hard to help you without knowing exactly the problem you are having.

Related

XMLHttpRequest different response vs. jQuery AJAX

I've made three requests to the same URL which should return the same response- but guess what, they don't.
First, the working one is with jQuery:
$.ajax({
dataType: "json",
url: "https://www.speedrun.com/api/v1/games?name=mkdd&callback=?",
type: "GET",
success: function(data){
console.log("Succes with AJAX - ?", data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The second one is also with jQuery, but I changed the callback=? to callback=foo. I really can't figure out why this isn't working.
$.ajax({
dataType: "json",
url: "https://www.speedrun.com/api/v1/games?name=mkdd&callback=foo",
type: "GET",
success: function(data){
console.log("Succes with AJAX - foo", data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Third one is just plain JavaScript - which I was planning on using. It's not working with whatever callback I'm using.
var request = new XMLHttpRequest();
request.open('GET', "https://www.speedrun.com/api/v1/games?name=mkdd&callback=?", true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = this.response;
console.log("Succes with JS", resp);
}
};
request.setRequestHeader('Content-Type', 'application/json');
request.send();
Can anybody help me with this problem? Am I missing something in my XMLHttpRequest? Why does the callback=? vs callback=foo matter so much?
Fiddle: https://jsfiddle.net/bobtrol/2okpebvn/2/

php can not get the data send by ajax

this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;
$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);
send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^
Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});

Convert jQuery to JavaScript code equivalent

I know how to use jQuery well, but I don't know so much pure JavaScript.
This is my jQuery code:
$(document).ready(function() {
$.get('http://jsonip.com/', function(r){
var ip_address = r.ip;
my_function(ip_address);
});
function my_function(ip_address){
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");}});}
});
What it does: it is pasted in any website, then it picks any visitors ip address and send that as JSON to my server as variable data.
Problem: the code is working perfectly okay in some sites but not all the sites due to jQuery dependency. And I want to remove this and use pure JavaScript.
I am getting great answers but CORS is not working, there failing them. I am using different domains since the site we are sending data to is hosted on another server.
As mentioned in my commment above, you do not need the first ajax request as you can get this information from the request headers (PHP Example below) from your AJAX request.
To make sure that your website(s) have jQuery loaded you can run a check in your script and load it in dynamically. Using some code from this answer. See below for an example:
// Anonymous "self-invoking" function
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");
});
});
})();
To get the IP Address from your ajax request: (PHP) Source
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
The annoying part is that you need to do a cross-domain POST to send your data. There's a W3C standard for this called Cross-Origin Resource Sharing (CORS). Check out this tutorial for more info.
You'll want to put this at the bottom of the page. Different browsers handle ready state change events differently, so let's just avoid them.
<script>
// Once the JSONP script loads, it will call this function with its payload.
function getip(ipJson) {
var method = 'POST';
var url = 'URL of your server';
// The XMLHTTPRequest is the standard way to do AJAX. Try to use CORS.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
// Create your request body. It has to be form encoded. I'm not sure
// where you get `number` from, so I've hard-coded it.
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send('number=1286&ip=' + ipJson.ip);
}
</script>
<!-- Get the IP using JSONP so we can skip implementing that. -->
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
This probably only works in modern browsers, but it should work in most modern browsers.
Replace $.ready(function...) with document.addEventListener('DOMContentLoaded', function..., false).
Replace $.ajax with XMLHttpRequest:
var xhr = new XMLHttpRequest();
//var data = {number:"1286", ip: ip_address};
var data = new FormData();
data.append("number", "1286");
data.append("ip", ip_address); // As stated by Scriptable in the question comments, your server should be able to get it from the request headers.
xhr.onload = function() { console.log(JSON.stringify(this.response)); };
xhr.onerror = function() { console.log("There was an error and data was not posted.") };
xhr.open("POST", "URL to your server");
xhr.send(data);

Get data from external link of JSON by jQuery

I am trying to read data from a JSON data by jQuery. Bus for some reasons it deosnt work.
Here is my JSON file: http://goo.gl/PCy2th
and this is my code to get data:
$.getJSON("http://goo.gl/PCy2th", function(data){
$.each(data.PlayListArray, function(key, val){
alert(val.URL);
});
});
Here is the demo:http://jsfiddle.net/SVk77/
Any idea to fix it?
you can create web service for getting all music urls
PHP code:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$array = array("https://soundcloud.com/danial-sabagh/mane", "https://soundcloud.com/ajamband/gole-iran", "https://soundcloud.com/bibakofficial/kooch", "https://soundcloud.com/bibakofficial/mohammad-bibak-in-niz-bogzarad","https://soundcloud.com/kaishakhay/whine-and-kotch-j-chapri-f","https://soundcloud.com/amirtataloo/merci","https://soundcloud.com/amirtataloo/bikhiyal");// you can also apply your business logic and get url from database
echo json_encode(array("PlayListArray"=>$array));
return;
?>
JQuery code for calling & getting response from php web service
Javascript code:
$.ajax({
url: 'getMusicURL.php',
type: "GET",
dataType:'json',
success:function(data){
console.log(data);//using object data you access all music array
for(var i=0;i<data.PlayListArray.length;i++){
console.log(data.PlayListArray[i]);
}
}
});
You can achieve using Cross-Origin XMLHttpRequest
I.e
$(document).ready(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://goo.gl/PCy2th", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
});
It Seems that your server who is returning the json is not supporting the request.
Demo

Calling finance.yahoo api using jquery

I want to send http request for fetching finance.yahoo stock data with url like : http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp which returns a csv file. I want to read the response data and fill it in a listview using Javascript or JQuery mobile. None of the links I referred helped me.
I tried using the following code:
$.ajax({
type: "GET",
url: "http://finance.yahoo.com/d/quotes.csv",
data: "s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp",
dataType: "text/csv",
success: function(data) {
alert(JSON.stringify('data is :' + data));
}
});
I get blank data as alert.
Any sample code or useful link would be appreciated.
I think that the problem is the request is cross domain. There is another question about this here:
Cross-Domain get CSV file
and another answer here :Yahoo JSONP Ajax Request Wrapped in callback function
and a working example here: Displaying ajax results from yahoo finance using underscore.js
Here is a working jsfiddle which makes a jsonp request to d.yimg.com to get the data http://jsfiddle.net/gp6zL/
YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
alert(JSON.stringify(data));
};
var query;
query = 'Google';
if (query.length > 0) {
$.ajax({
type: "GET",
url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
data: {
query: query
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
});
}
I try to take jQuery out of the equation. The following code will work as long as you whitelist "finance.yahoo.com".
var request = new XMLHttpRequest();
request.open("GET", "http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp", true);
request.onreadystatechange = function() {//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
console.log(request.responseText);
}
}
}
request.send();

Categories