How to handle multiple checkboxes whit PHP sent by jquery.ajax? - php

I'm sending a form in async with jquery.ajax method. On the PHP side it receive the right array (I think), but for some reason it shows me an error message when I try to extract the checkboxes values with a normal cicle. What can I do to fix it?
This is the Warning message I see:
Warning: Invalid argument supplied for foreach() in /home/mybestfa/public_html/ajax/verifica.php on line 206
If I try to echo the given array, I see this below. I suppose that this string it's creating the issue because actually it doesn't seem to be like a normal array. It's like a GET string:
categoria%5B%5D=bellezza&categoria%5B%5D=educazione
So the final question is, how can I extract the checkboxes values from the array?
HTML:
<form id="form_step1" action="ajax/verify.php" method="POST">
<?php
$query="SELECT name FROM category";
$result=mysqli_query($connessione, $query);
$num_check=0;
while ($row=mysqli_fetch_array($result)) {
$category_name=$row['name'];
$num_check=$num_check+1;
?>
<label for="check[<?php echo $num_check; ?>]">
<input type="checkbox" id="check[<?php echo $num_check; ?>]" name="category[]" value="<?php echo $category_name; ?>">
<?php echo $category_name; ?></label>
<?php
}
?>
<p id="result_step1"><ul></ul></p>
<input type="submit" id="button_step1" name="button_step1" class="form_button" value="Continue">
</form>
JS:
$(document).ready(function() {
$("#form_step1").submit(function(event) {
event.preventDefault();
var fields_step1=$('#form_step1').serialize();
var submit_step1=$("#button_step1").val();
$.ajax({
url: "ajax/verify.php",
method: "POST",
data: {fields_step1: fields_step1,
submit_step1: submit_step1},
dataType: "text",
success: function(risposta,status){
console.log(risposta);
if(status=="success") {
$("#risultato_step1").html(risposta);
if (risposta == "prosegui") {
$("#risultato").html("");
}
}
})
}
PHP:
if(isset($_POST['submit_step1']))
{
$errorForm=false;
$categories=$_POST['fields_step1'];
foreach ($categories as $category)
{
echo "Founded: $category<br>";
}
}
PS: I pasted the code translating the italian variables in english. So I apologize if I forgot to translate something along the road.

Related

Try to using ajax form instead of form action (solve)

I would like to improve user experience at my website. So I try to change the form action ajax, and I has been try some tutorial but I still getting stuck.
I am using a php forum program/source code call !Discuz and it was from China. Below is my coding now.
In html.
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn">submit</button>
</form>
in PHP, file name plugin.php
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
showmessage('message here','redirectlink');//this is !Discuz program function and it is fine.
}
}
?>
The above script is working fine while using form action, and redirect to my output page. If I would like to change to ajax, how do I adjust the below source code?
<script type="text/javascript">
function login() {
$.ajax({
type: "POST",
dataType: "json",//? is it can use json? since my form data can get as array
url: "plugin.php?id=cc&do=shop" ,//url
data: $('#jnfarm_pop').serialize(),
success: function (result) {
console.log(result);
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("ERROR");
}
});
}
</script>
<form method="post" id="jnfarm_pop" action="plugin.php?id=cc&do=shop">
<input type="hidden" name="shopsubmit" value="yes">
<!--first item-->
<input type="checkbox" name="jsid[1]" value="1">
<input type="number" style="width:3em;" name="qty[1]">
<!--second item-->
<input type="checkbox" name="jsid[2]" value="1">
<input type="number" style="width:3em;" name="qty[2]">
...continue 50 item
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login()">submit</button>
</form>
And is it have to adjust the plugin.php source code?
Updated, below is work for me, thanks fayis003.
html change the <script></script>
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
alert(result.final);//alert message here
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
PHP
<?php
if($_GET['id'] == 'cc'){
if(submitcheck('shopsubmit')){ //core function in !Discuz
for($x=1;$x<=50;$x++){
if($_GET['jsid'][$x] == '1'){
$qty[$x] = intval($_GET['qty'][$x]);
//process....
}
}
$final = 'message here';
echo json_encode(['final' => $final]);
}
}
?>
You can not initiate a direct browser redirect using server-side code on ajax request like you do with synchronous requests. instead, you have to return a URL to which you want to get redirected to and then do something like location.href = result.link in the result callback.
for ajax request, the simplest option is using as follows
$.get('plugin.php?id=cc&do=shop', $('#jnfarm_pop').serialize(), result => {
//alert('success');
console.log(result); // check the result in console and if you can see it as a JS object you don't need to parse
result = JSON.parse(result); // Parse is required if you return the result as plain text otherwise you can omit this step in case you are returning the result as content type json
let final = result.final;
location.href = result.link;// if you need to get redirected
}).fail(result => {
alert('fail');
});
now in the server-side code instead of creating a redirect from PHP return something like
return json_encode(['link' => 'somlink']);
of just return success message as usual.

A quizz show if the answer is correct or incorrect in the same page after submiting the answer not refresh

"I am working in a quizz I want it to let me know if the answer is correct or incorrect. My issue is that it does that but it tell me that is correct or not correct in the next page with the next question because it is refreshing the page everytime I submit the answer." I want it to tell the student if it is correct or incorrect in the same page before moving to the next page.
If I eliminate the ajax It will display if the answer was correct or not correct but in the next page where the new question is displayed. All the codes are in the same Php/html page. Thanks in advance.
<?php while($row5 = mysqli_fetch_assoc($res)): ;{ ?>
<h1 align="center" ><?php echo $row5['Question'] ?></h1>
<?php
$id = $row5['QuizzId'];
$question = $row5['Question'];
$correctAnswer=$row5['correctAnswer'];
$ans_array = array($row5['notCorrect1'],$row5['notCorrect2'], $row5['correctAnswer']);
shuffle($ans_array);
?>
<label>A<input type="radio" value="<?php echo $ans_array[0]; ?>" name="name"> <?php echo $ans_array[0]; ?></label>
<br/>
<br/>
<label>B<input type="radio" value="<?php echo $ans_array[1]; ?>" name="name"> <?php echo $ans_array[1]; ?></label>
<br/>
<br/>
<label>C <input type="radio" value="<?php echo $ans_array[2]; ?>" name="name"> <?php echo $ans_array[2]; ?></label>
<input type="hidden" name="correctAn" value="<?php echo $correctAnswer; ?>">
<?php } ?>
<br />
<br />
<input type="submit" value="Submit" name="correct">
<script>
$('#correct').click(function() {
$.ajax({
type: 'POST',
url: 'questions_1.php',
data: 'correctAnswer1',
success: function(php) {
alert('yes');
}
});
});
</script>
<?php
if($_GET["correctAnswer1"]){
$mianswer = $_POST["name"];
$correctAn = $_POST["correctAn"];
if($mianswer==$correctAn) {
echo "<h1>Great Job</h1>";
echo '<br>';
echo "<h1>The correct answer was $correctAn</h1>";
} else {
echo '<h1>Not correct</h1>';
echo "<h1>The correct answer was $correctAn</h1>";
}
}
?>
First of all in your ajax request you have defined type:'POST' but you have used $_GET in php , change that i.e : if($_POST['something'])
Then you need to take value of radio button which is selected by user and correct answer value .i.e:
$("input[name='correct']").click(function(e) {
e.preventDefault();
//getting selected radio button value
var name=$("input[name='name']:checked").val();
//getting value of correct answer
var correctAn=$("input[name='correctAn']").val();
$.ajax({
type: 'POST',
url: 'questions_1.php',
data: {'correctAn': correctAn,'name':name },//<-passing value to php
success: function(php) {
alert(php);
}
});
});
And in your php script , do like below :
if(isset($_POST['correctAn']) && isset($_POST['name'])){
//getting values
$mianswer=$_POST["name"];
$correctAn=$_POST["correctAn"];
//do something
}
Since you are passing the correct answer as a hidden field there is no need to make an ajax call, you can manage what you want client-side. Is questionable if this is the right approach, since inspecting the page will reveal the correct answer, but based on what you are currently doing, this is a possibility.
$('form').on('submit', function(ev) {
ev.preventDefault(); // This prevents form submission
let answer = $("input[name='name']:checked").val();
let correct = $("input[name='correctAn']").val();
if (answer == correct) { // Check if selected option is the correct one
alert('Congratulations!');
}
});

Trying to get value from option on selected tag with jQuery and post to php page

I'm trying to get value from the selected option and post on a Php. But I also have a form to Post data as well. I'm trying to combine the two but now when I try to run the code I get a blank query page.
message.php
<form id="messageEmployeeForm" class="form table-striped" method="POST" action="core/query.php">
<select id='toEmployee' class='form-control formBlock' name='toEmployee_id' value='' type='text' class='form-control formBlock'>
<option value="">To...</option>
<?php
$employeesQuery = $db->query("SELECT * FROM employees");
while ($employee = mysqli_fetch_assoc( $employeesQuery)) {
?>
<option id='toEmployees_id' name='toEmployees_id' value="<?php echo $employee['employee_id'] ;?>">
<?php echo $employee['first_name'] ;?> <?php echo $employee['last_name'] ;?></option>
<?php } ;?>
</select>
//other inputs here...
<input name="sendMessage" id="submit" type="submit" class="formBlock btn btn-success" value="Send Message"/>
</form>
jquery
<script>
$(document).ready(function () {
$("#toEmployee").bind("change", function (e) {
$.ajax({
type: "POST",
data: { data: $("#toEmployee").val() }
});
});
});
</script>
query.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sendMessage']) && isset($_POST['data'])){
$var = $_POST['data'];
//other data to be posted and bind here using prepared statements...
]
Your query.php file is expecting two post keys to be present during the request, without these it won't run the inner code.
isset($_POST['sendMessage']) && isset($_POST['data'])
Therefore inside your jQuery, you need to additionally send the sendMessage key like so:
$.ajax({
type: "POST",
data: {
data: $("#toEmployee").val(),
sendMessage: 'your value'
},
success: function(data) {
// do something with output (data)
}
});

Display MySQL queries on the same page

I've been searching for a while but nothing I've found match what I need.
I've got a form with 2 variables (dropdownlist) to query a DB (PHP and SQL).
Names of my variables are : "province" and "candidat".
My result page is action.php with all the sql/php code for the results.
Everything is going very fine except that after clicking on the submit button, a new page is opening : action.php with the results of my request.
Now, I wish to display this results on the same page as my form (id = form). The id of the div to display results is"success" (<div id="success">). There is an action on my form : action="action.php", should I remove it ?
I know that I have to use AJAX method but nothing that I've found match my needs. The other point is that I wish to be able to make another query and display the new results in this area.
If you know the solution or a tutorial that fit my needs... MANY THANKS of your help !
Start here: http://api.jquery.com/jQuery.ajax/
And do something along the lines of this:
$.ajax({
url: "action.php",
cache: false
}).done(function( response ) {
alert( response );
$("#success").html(response); //put the response into a DIV with id="success"
});
I'd recommend being more specific with your HTML id's that you are using.
$(document).ready(function(){
var datastring = "your data that is pass for php file";
$.ajax({
url: "action.php",
data: datastring,
type: "post",
success: function(response) {
alert(response);
}
});
});
Here's the code :
PROVINCE
">
<?php
}
?>
</select>
CANDIDAT
<?php
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
?>
<option value="<?php echo $data['id_candidat']; ?>">
<?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>
<?php
$id = $data['id_candidat'];
if ($id === $id)
{break;}
}
?>
</select>
<br/>
<input type="submit" class="submit" name="submit" value="ok" />
</form>
Content of action.php :

Codeigniter, getting ajax to run on button press

My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});

Categories