access javascript array from a php file - javascript

How can I pass a a javascript array vArray to File.php , and retrieve the two values from vArray.
I tried:
<input type="button" id="button" onClick = "send_V();" >
<script>
// Creat Array with Values from checkboxes
$('input[type=checkbox]:checked').each(function() {
vArray.push($(this).val());
});
// Set array to only 2 values ( disable checkboxes)
var n = $('input[type=checkbox]:checked').length >= 2;
$('input[type=checkbox]').not(':checked').attr('disabled',n);
// Send array to File.php where I can manipulate its value1, and value2 to query db
function send_V(vArray)
{
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: "vArray="+vArray,
success: function(msg){
$("#result").html(msg);
}
});
}
</script>
and on the php side ( File.php)
$value = $_POST['vArray'];
var_dump(vArray);
but I am not able and sure how to manipulate a javascript variable. can someone show me a simple and effective method ?
What is wrong in this logic?
Thanks

Use json. Encode array in js (How do I encode a javascript object as JSON?), decode it in php (http://php.net/manual/ro/function.json-decode.php).

If you set up the ajax call with an object for the "data" parameter:
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: { vArray: vArray }, // here
success: function(msg){
$("#result").html(msg);
}
});
Then jQuery will create HTTP request parameters like this:
vArray[]=first value
vArray[]=second value
etc. On the server side, when you access
$vArray = $_POST['vArray'];
you'll get the array back. You don't have to explicitly mess with JSON if you don't want to, in other words.

Pure javascript for modern browser (needs support for formData & xhr2)(chrome,safari,ios,android,ie10)
js
var vArray=['a','b','c'],
json=JSON.stringify(vArray);//this converts the array to a json string
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('json posted',this.response)
}
ajax('page.php',whatever,'post',{'json':json});
page.php
<?php
print_r(json_decode($_POST['json']));//converts the json string to a php array
?>
Another solution is to post the whole form
html
<form>
<input name="a" value="x">
<input type="radio" name="b" value="x">
//and many other input & text fields
</form>
js
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('form posted',this.response)
}
var form=document.getElementsByTagName('form')[0],
fd=new FormData(form);
ajax('page.php',whatever,'post',fd);
php
<?php
print_r($_POST);
?>
xhr2
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
formData
https://developer.mozilla.org/en-US/docs/Web/API/FormData

I have tried the following that seems to work fine :
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
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("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
It is working really well for me. Code taken from http://www.developphp.com/view.php?tid=1185
Answers by #Pointy and #Cocco might be correct, I could not manage to implement it right with Jquery, neither wanted to use a Form.. Hope this helps someone

Related

How can I send data use post by javascript without form?

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);

How to refresh particular div when onclick without losing dynamic data

I want to fetch data when onclick is invoked. I have four div in my form and I want only a particular div to be reloaded and fetch data. while loading it should not discard the form data. Anyone help. Thanks in advance for people who are going to help me in this.
my code looks something like this
<div id="fetch">
<?php
//query to fetch data
?>
</div>
<div id="data4">
//dynamic data
//Want to retain this data even after fetch
</div>
In this case you should use AJAX.
Onclick you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as string / JSON), and insert it into your website with JS.
Example:
function test()
{
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
result = xhr.responseText;
document.getElementById("test_field").innerHTML = result;
}
}
xhr.open("GET","your_ajax_file.php",true);
xhr.send();
}
your_ajax_file.php returns the data you want to insert.
You mentioned you have a problem with function call, but you did not give more information. so i will give you an example how to write an ajax request, then you can maybe give me more detailed info on where your problem is.
$.ajax({
url: 'ajax_file.php',
type: 'post',
data: {var1: 'value1', var2: 'value2'},
success: function( data ){
console.log('ajax request successful! data: '+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
And in your ajax_file.php do something like this:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
echo $var1.', '$var2;
edit: typo, changed val2 to var2 in ajax request

get html result of php in html file

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/

Can I call function by JavaScript?

Hi I want to to run function for searching word in database. The function is in this location: media/search, up to now it was possible to run this function with this JS by "search_query":
final_transcript = capitalize(final_transcript);
var queryTextField = document.getElementById("search_query");
queryTextField.value = final_transcript;
....
"search_query" is id in this input:
<form class="input-group navbar-form" action="<?php echo base_url();?>media/search" method="post"></li>
<li style="margin-top:8px;"><input type="text" class="form-control" placeholder="Search subtitles..." id="search_query" name="string" /></li>
<li style="margin:8px><button type="submit" class="btn btn-info" name="btn_search"><i class="search "></i></button>
I want to change it so I don't want to use this HTML code. I want to implement "calling" function media/search in JS instead of:
var queryTextField = document.getElementById("search_query");
Let me know if I misunderstood you, but if I understand you correctly, you want to trigger the search with javascript?
And it looks like you want to do this without jQuery?
//get search string inputted by user
var queryTextField = document.getElementById("search_query");
var query = queryTextField.value
//pass base url to javascript
var base_url = '<?php echo base_url();?>'
//create new request
var request = new XMLHttpRequest();
//set up what you want to do with returned data
request.onreadystatechange=function()
{
//if call was successful
if (request.readyState==4 && request.status==200)
{
//response will be in here
//request.responseText;
}
}
//set as post, the url, send asynchronously
request.open('POST', base_url+'media/search', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(query);
With jQuery:
$.ajax({
type: 'POST',
url: base_url+'media/search',
data: query,
success: function(data_return) {
//do something with returned data
}
});
See:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
and
http://api.jquery.com/jquery.ajax/
I have not tested the above code, but it should put you on the right path.

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

Categories