This code will send request to post parameters to php file:
var param = //some parameters;
var url = file.php;
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
I got the response but the php file produce some output like <td><tr>.....
How to get this result of php in some div of my html?
Thanks,
You use onreadystatechange to get the response:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#mydiv').html(xhttp.responseText);
}
};
XHR is pretty complicated without using a Framework. Just use jQuery it will make this 1000x easier.
$.ajax({
url: "myfile.php",
type: "POST",
data: {
/* Params */
},
success: function(response){
/* Use your response here */
}
});
http://api.jquery.com/jquery.ajax/
Related
I try like this :
window.location = '/admin/product?name='+name+'&category='+category+'&createdAt='+createdAt;
If the statement executed, the result url to be like this :
http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09
From the url, it can use get to get the value of parameter
But I want to change it use post. I don't want the value exist in the url
How can I do it without form tag by javascript?
jQuery.ajax({
url: '/admin/product',
type: "post",
data: { name, category, createdAt },
dataType: "json",
success:function(response)
{
if(response.result)
{
}
else
{
}
}
});
fetch(URL, {
method: 'POST',
body: JSON.stringify({
name: 'asif',
email: 'asif#gmail.com'
})
}).then((response) => {
return response.json();
}).then((response) => {
Console.log(response)
}).catch((err) => {
Console.log(err)
});
When you put the data in URL you can either use $_GET or $_REQUEST to get the data. In case you want to get the data using the $_POST method, you need to pass is using the post method itself. In case you are using JQuery. I'll suggest you to go for $.ajax method to send data to the page you want. But you will not be redirected to that page with it.
If in case you want to send the data to the page and also want to get redirected to the page for further processing of data on the same page, you should choose for putting the data into $_SESSION variables and then redirecting to the page and using the $_SESSION variable over there.
I'll provide a simple example
AJAX to be used on your main page
$.ajax({
method:'post',
url:'createSessionVariable.php',
data:{data1:'dataOne', data2:'dataTwo'},
success:function(){
window.location.href='pageYouWantToGetRedirected.php';
}
});
The above will send data to a page createSessionVariable.php where you will create session variables using php and then on success you will be redirected to pageYouWantToGetRedirected.php
Code on createSessionVariable.php
$_SESSION['data1'] = $_GET['data1'];
$_SESSION['data2'] = $_GET['data2'];
echo "Done";
Now you can use the session variables on the page you want. It will help you passing the variable to the page and redirecting to the page as well without using a form tag.
But this is not considered a good way of writing code, as it can make your website vulnerable. Still you can use it.
You can use Asynchrone Http request, commonly known as Ajax request. There a few way to do this :
Using plain Javascript :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09", true);
xmlhttp.send();
Or using Ajax
$.ajax({
url: "http://my-app.test/admin/product?name=chelsea&category=47&createdAt=2018-04-09",
cache: false,
success: function(html){
$("#results").append(html);
}
});
I have linked question with good explaination on how each method works.
#CertainPerformance's answer is better, but here's my answer.
Using the form tag in the background is always an option.
document.getElementById("name").value="Chelsea";
document.querySelectorAll("form")[0].submit();
<div style="display:none;">
<form action="product.php" method="post">
<input name="name" id="name">
<!--DO OTHER PARAMETERS-->
</form>
</div>
See here, jQuery's ajax can POST and serialize your query parameters for you:
$.ajax({
url: '/admin/product',
data: { name, category, createdAt },
type: "POST",
use javascript's XMLHttpRequest to send a POST request ( no jQuery )
var http = new XMLHttpRequest();
var url = "/admin/product";
var params = 'name='+name+'&category='+category+'&createdAt='+createdAt;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Having trouble showing the JSON response using window.alert or alert in JavaScript. I'm not a native JS coder, I apologize for the noobness. Below are a few examples I've tried based on examples I found online.
My goal is to have the JSON response appear in an alert popup window.
# example 1
<script type="text/javascript">
var client = new HttpClient();
client.get('https://website.com/json/', function(response) {
window.alert(response);
});
</script>
# example 2
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
# example 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
</script>
# example 4
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://website.com/json/", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
}
The first problem that I can see is that the url https://website.com/json does not have a correct response.
you can for example try these links: https://jsonplaceholder.typicode.com/posts/1
or https://ipinfo.io/json
I prove your example 4 and it work perfectly.
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
var response=JSON.stringify(e);
alert(response);
}
you can notice that I put the alert in the processRequest function and before display it. I used JSON.stringify to change the object e to a string. Let me knoe if that work for you.
When trying to display object in alert it will say [Object object]. Your response is a JSON. Stringify it, so that alert can display it.
$.get('https://website.com/json/', function(responseText) {
alert(JSON.stringify(responseText));
});
I have created a sample code on jsfiddle for your scenario:
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1/comments",
type: "GET",
dataType: "json",
success: function(data){
alert(JSON.stringify(data));
}
});
https://jsfiddle.net/ashvinimaurya/kn3yv7Lh/7/
I'm making an ajax call and then alerting the response data after stringifying.
I think you are getting cors error, (cross origin error). You should set your request headers correctly according to the third party (https://website.com/json/) server headers.
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/
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
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();