简体   繁体   中英

Send data from Javascript to PHP file

I have a checkbox and I need to get data (id) from them and send it to other php file

My code :

 function getValues() { var str = []; var checks = document.getElementsByClassName('justtest'); for(var i=0; i<checks.length; i++){ if(checks[i].checked){ str.push( checks[i].id ); } } for( var x = 0; x < str.length; x++){ alert (str[x]); } }
 <div class="form-group"> <div class="col-md-3"> <div class="checkbox"> <label> <input type="checkbox" value="test1" class="justtest" id="1"> Test1 </label> </div> </div> </div> <div class="form-group"> <div class="col-md-3"> <div class="checkbox"> <label> <input type="checkbox" value="test2" class="justtest" id="2"> test2 </label> </div> </div> </div> <div class="form-group"> <div class="col-md-3"> <div class="checkbox"> <label> <input type="checkbox" value="test3" class="justtest" id="3"> test3 </label> </div> <button onclick="getValues()">Check</button> </div> </div>

So, I need to take Id from checkbox and send it to my PHP file to show result about ID

 function getValues() { var str = []; var checks = document.getElementsByClassName('justtest'); for(var i=0; i<checks.length; i++){ if(checks[i].checked){ str.push( checks[i].id ); } } for( var x = 0; x < str.length; x++){ $.ajax({ url: 'result.php', cache: false, data: str[x], type: 'POST', }); } }

I have other php file named result.php , So, I need to take ID's from this file and send it to result.php

they don't work

Any solution ?

For starters, you have a syntax error that is undoubtedly being reported by your browser console:

$.ajax({
         url: 'result.php',
         cache: false,
         data: str[x],
         type: 'POST' // <--- You had an extra comma
}); // <--- You forgot to close the object and the function call

Aside from that, what is in str[x] ? Form data would need to be in the form of key/value pairs or a JSON object. If str[x] is just a single value then you'd need to provide a key for that value. Something like this:

data: 'someKey=' + str[x]

(If the value is complex, you might enclose it in encodeURIComponent() to URL-encode it.)

Then in the server-side code you would access the value using that key:

$_POST['someKey']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM