In php how to post a value which created in javascript - javascript

In a php page ,i created textboxes diynamically in javascript and i want to post these values to another php page how can i get these values ? And these are my codes ;
while (secenek>0){
var textBoxname = document.createElement('input');
textBoxname.name = 'textyetiskinname'+secenek;
textBoxname.id='textyetiskinname'+secenek;
textBoxname.type = 'text';
textBoxname.className='selectTravelInputFieldsCarJS';
document.getElementById("yetiskindiv").appendChild(textBoxname);
secenek--;
}

If that is the entire snippet of script, then you need to build more script to do the ajax function.
If you are just trying to grab value of the dynamically created element, then you can use document.getElementById('textBoxname').value; as this code will grab the value.

set a unique attribute on your input tags:
//at this to your while loop
textBoxname.setAttribute("phpform", "myform");
to be able to find them and then read the form data and send them like this:
function POST_data(callback){
var myinputs = document.querySelectorAll("input[phpform=myform]");
var formData = {};
for(var i=0;i<myinputs.length;i++){
formData[myinputs[i].getAttribute("name")] = myinputs[i].value;
}
req = new XMLHttpRequest();
req.open("POST", "php_url");
req.onreadystatechange = function(){
if(req.readyState==4){
callback(req.response);
}
};
req.send(JSON.stringify(formData));
}
call POST_data and give a callback for your callback scenario, like this:
POST_data(function(response){
//you can check here if it was successful or not and continue your scenario
});
just be careful, this code is using a sample ajax request, in the real world you'd better use jQuery or at least a cross-browser ajax function.

Related

How to sent data to server, remove parameter from url and reload window with new url Javascript, jQuery and PHP

I am currently stuck with a problem I can't seem to find a decent solution for.
Problem:
I have written some code that will send 2 parameters to an action within a PHP script through a url. I need these parameters sent to the action no matter what. However, after the parameters are sent, I need to remove one of said parameters from the URL and then reload the page with said new URL.
I hope I could give you a clear description of my problem. Following is the code I have written so far.
jQuery(document).ready(function() {
// Define array with the dashboard id and title as key => value pairs.
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
// Get arg01 from the server.
var arg01 = <?php echo json_encode($arg01); ?>;
// Prepare URL variable and spike it with arg01 to be sent back to the server.
var url = 'Path/To/action/Index/index&arg01='+arg01;
// Button change and function tied to it. Instead of an ajax request, we reload the page completely.
$("#idDashboards").change(function() {
// Define dashboardIndex. The -1 stands for the option tag that has already been created.
var dashboardIndex = $(this).prop('selectedIndex')-1;
// Sent parameters to actionIndex in Controller and remove dashboardIndex after the request was successful.
if (url.includes(arg01)) {
window.location.href = url+"&dashboardIndex="+dashboardIndex;
console.log("Yes i was here");
}
// window.location.href = url; <---- Here is where the problem begins.
});
});

How to get parameter from URL using javascript

I passed a parameter through an URL using javascript. Here's the code:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username="+cookie_user);
};
</script>
The page that received the parameter is called ChangeInfo
This is what I see in the URL when I get to the ChangeInfo page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
When I'm trying to get the parameter username from the URL, I get this error:
Notice: Undefined index: username in C:\xampp\htdocs\test\ChangeInfo.php on line 5
The way I'm trying to get this parameter is to use $_GET like that: $username = $_GET['username'];
Does anyone know why this makes me a problem?
Thanks in advance
I just solve the problem
I deleted the Page parameter from the URL I created in javascript part.
this is the updated Javascript part:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/test/ChangeInfo.php?username="+cookie_user);
};
</script>
thank you :)
Ignoring the javascript part, needing to focus on PHP.
You are on this page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
And when you use $_GET['username'] you get the error, that it is not assigned.
It seems that your $_GET is not working at all, probably Apache settings.
Also, it is safer to get GET parameters with isset first.
if(isset($_GET['username']) && $_GET['username']] {
$username = $_GET['username'];
}
else {
$username = '';
}
Then you can compare, if username is set or not in your php code:
if($username) {
//Do something
}
Final thought. Is your first parameter page=http://192.168.206.1/test/ChangeInfo.php working? Can you get it through $_GET?
The problem seems to be just in the way you set and get the url parameter though $_GET. If you use some framework, it might be disabled to use $_GET directly and for example in Symfony you need to use:
$request->get('username');

How to refresh a specific part of the HTML Document with Vanilla JavaScript

I am working on an AJAX cart system where the sub total will automatically update when the quantity changes. My solution is every time the input changes, post it to the current page (cart page) then reload the div that displays the sub total. However, I don't know how to do this with pure JavaScript, and I haven't found any reference yet.
This is my function for the above algorithm:
var _rangeInput = document.querySelectorAll('.ranum'), _upAload = document.getElementsByClassName('upAload');
var _frmData = {};
for (var i = 0; i < _rangeInput.length; i ++) {
_rangeInput[i].addEventListener('change', function(){
_frmData[this.name] = this.value;
ajaxFormValidate({
type: 'POST',
url: location.href,
method: true,
sendItem: _frmData,
success: function(response) {
//reload here
}
});
}, false);
}
Code explaination:
First, get the inputs and divs that need to be processed.
Loop through all of the inputs and get their values and names.
I have written an AJAX function for my self, you can look above.
Is there anyway to do this with pure JavaScript?
I can't use JavaScript methods or functions to change the content since I am sending the request to the same page, as a result, response here will have the value of the whole document.
Also, this is how the system works:
First, the user changes the quantity they want
AJAX sends request to the same page
The page changes the information based on the request
AJAX receives the request, and refreshes/reloads the specific div
Simply set the innerHTML of your sub total div with the response data.
document.getElementById("sub-total").innerHTML = response.value; //Whatever value you get in response
It sounds like you're actually asking how to get a single element out of an AJAX response.
You can do that by parsing the response into a temporary element, then finding the element you need within it:
const holder = document.createElement('div');
holder.innerHTML = response;
const myElement = holder.querySelector('some selector');

AJAX and a global variable not working, have I got this wrong?

what I am trying to achieve is to AJAX a load of client's data into a page (this works), I then have a company ID in one of the fields brought in. I need to cross check this with a different company table (same database) to replace the company ID on the page with the name instead.
To get this I have set a global javascript variable to blank then fired off the main AJAX request getting all the initial client data then within that parsing loop (client side) I need to fire off a function which will check against the companies table to get the name. My current problem is that the global variable is not being set to the 2nd AJAX result. Here is my code:
var nameresult = "";
function namecheck(id){
var request = new Ajax().sendRequest
('../company_check.php',
{ method: 'GET',
parameters: 'id=' + id,
callback: namecheckReceived }
);
}
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
}
function client_call(){
var request = new Ajax().sendRequest
('../client_data.php',
{ method: 'GET',
callback: searchReceived }
);
}
function searchReceived(xmlHTTP){
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.length; i++)
{
namecheck(data[i].company_id);
/////spit out all the data in a readable format //////
}
}
Notes:
Only one result will be received from the company_check.php hence no
loop in the namecheckRecieved() function.
No errors in the JS console.
The nameresult variable stays as blank and is never
changed, if I alert(nameresult) within the namecheckRecieved()
function it spits out what I want so why is it not changing the
global variable with each loop of the searchRecieved() function?
I'm going to delete all my previous comment and say that you only need one ajax call. And everything should be done on server side. That means get the company Id, and use that to get the name of the company then pass everything back to the client side. From the look of it you are doing A LOT of call backs to the server to get every company name when you could have just done that on your first visit to the server. This way you do not need to worry about doing two ajax call Although from the look of it your doing more than 2 calls, depending on the length of data
Try this
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
client_call();
}

Periodically autosave form

How to implement a periodical save of a form in the background? Same kinda thing that gmail does.
setInterval(function(){
var form = $('#my-form-id');
var method = form.attr('method').toLowerCase(); // "get" or "post"
var action = form.attr('action'); // url to submit to
$[method](action, form.serialize(), function(data){
// Do something with the server response data
// Or at least let the user know it saved
});
},10000); // do it every 10 seconds
If you don't want to use the method of the form, but always want to use 'post', then use:
$.post(action, form.serialize(), ... );
And, if you want to supply your own action for the autosave that is different from the action for the actual save:
$.post("/autosave/comments", form.serialize(), ... );
You would need a timed loop on the client side that would save the form every x seconds/minutes. A crude way of doing this would be to have a setTimeout javascript function that collects the form's field values and updates the model via an update (PUT in Rails' case) AJAX request.
Example
Here's a crude way of doing it (i.e. there might be a better way):
// repeat every 10 seconds
var repeatTime = 10 * 1000;
function updateModel(){
// get field values (using jQuery, etc.)
// make ajax request using these field values
//(make sure put parameters match model attribute names)
console.log('updated');
setTimeout(updateModel, repeatTime); // start call over again
}
setTimeout(updateModel, repeatTime);
I included the console.log so that you can test this out in Firebug right now and see that the updateModel executes every 10 seconds. I would recommend using jQuery to generate the PUT AJAX requests.
Why not do this purely on the client, using a local database (or whatever)? That should reduce complexity, server load and bandwidth usage.
Permanent or per-session storage -- whatever's appropriate -- and you can save after every keystroke: no need for setTimeout().
Sisyphus.js: Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.
http://sisyphus-js.herokuapp.com
Smashing Magazine article: http://coding.smashingmagazine.com/2011/12/05/sisyphus-js-client-side-drafts-and-more/
Version that works without jquery:
function urlencodeFormData(fd) {
var s = '';
function encode(s) { return encodeURIComponent(s).replace(/%20/g,'+'); }
for (var pair of fd.entries()) {
if(typeof pair[1]=='string') {
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
setInterval(function() {
var form = document.getElementById('my-form-id');
var request = new XMLHttpRequest();
request.open(form.method, form.action);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
request.send(urlencodeFormData(new FormData(form)));
}, 10000);
If you need to do something with the server response see this post: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

Categories