When alerting PHP echo i see "<html>" in the message - php

Strange things happen often.
The code works fine but when I alert the PHP echo from javascript it displays like this:
"< html > Login başarılı. < /html >"
click to view the screenshot
How can I get rid of that html tag in the message?
This is my javascript:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
success: function(mesaj) {
alert(mesaj);
}
});
and this is the PHP:
<?php
$con=mysqli_connect("pantuff.com","ttoykoc","*******","db_pantuff");
if (mysqli_connect_errno($con))
{
echo "MySQL Bağlantısı yapılamıyor." . mysqli_connect_error();
} else
{
$result = mysqli_query($con,"SELECT * FROM member");
while($row = mysqli_fetch_array($result))
{
if ($row['user_eposta'] == $_POST['user_eposta'] && $row['user_sifre'] ==
$_POST['user_sifre'])
{
$adsoyad = $row['user_ad'] . " " . $row['user_soyad'];
$_SESSION['username']= $adsoyad;
setcookie("currentuser", $adsoyad, time()+(84600*30));
echo "Login başarılı.";
} else
{
echo "Kullanıcı adı ya da şifre hatalı!";
}
}
}
mysqli_close($con);
?>

alert($(mesaj).text());
alert($(mesaj).html());
$(mesaj) builds a jQuery object from html. Then text or html function fetches the message, where html gets the message with html entities in it, while text contains no entities.
A different solution, as proposed above in the comments:
Add header("Content-Type: text/plain"); in line 2 of the file outputting the text, and:
var dataString = 'user_eposta='+ eposta + '&user_sifre=' + sifre;
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString,
dataType: 'text',
success: function(mesaj) {
alert(mesaj);
}
});

Related

While loop Mysql updating checkboxes where to start

I have a question how can I update the database if person unchecks or check a checkbox and update the boolean field
in mysql? For days stuck with this problem, because problem I don't know how to make a form or check if
it is validate inside of a while loop here is my code:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)) {
echo '<tr>
<td>' . $counter++ . '</td>
<td><input type="checkbox"';
if ($row['show'] == true) {
echo 'checked></td>';
} else {
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'],
" € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
p.s. I am aware of the mysql to mysqli or pdo but it is a HUGE script...
Oh! No issue here is the solution:
Try using jquery and ajax. For example.
if ( $("#chkbx").prop('checked') == true) {
// do ajax call to update the database
} else {
// do anything if check box is unchecked
}
I am not writing the ajax call just see the jquery ajax manual. If you face any problem come back.
See the above code will create a event listener in the DOM so that when the check box is checked a event should fire.
Now I am extending my code to show you a ajax call.
if ( $("#chkbx").prop('checked') == true) {
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
Now in the php file do the updating part of database or anything you want. The done function will show the msg you returned if the php file execute properly. There are numerous functions in ajax that you can use.Also try to use jquery it's handy and easy to use.
Thank you so much, now I only have to focus on how database works in Ajax
This is what I added and with this I can echo out that it does work now what rest is change the boolean value row['show']
<script type="text/javascript">
function change_checkbox(el){
if(el.checked){
alert("On");
}else{
alert("Off");
}
}
I got pretty far that all is working except for 1 particulair thing.
The problem what I now face is that I cannot send the DATA ID's from the checkbox to the test.php page how can I do this correct this is what I came up with so far:
<?
$result= mysql_query("SELECT * FROM cars");
$counter = 1;
while($row = mysql_fetch_array($result)){
echo '<tr>
<td>' . $counter++ . '</td>
<td><input id="'.$row['cars_id'].'" onchange="change_checkbox(this)" type="checkbox"';
if ($row['toon'] == true){
echo 'checked></td>';
}else
{
echo 'unchecked></td>';
}
echo '<td><img src="../xml/'.$row['cars_id'].'-1.JPG" width="120px"></td>';
echo "<td><h3> ", $row['brand']," " . $row['model'], " " . $row['type'], " € " . $row['price'], " </h3></td>";
echo '</tr>';
}
?>
</tbody>
</table>
</section>
<script type="text/javascript">
function change_checkbox(el){
var id = null;
if(el.checked){
alert("On");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { id: id } // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}else{
alert("Off");
$.ajax ({
method: "POST", // type:post or get
url: "test.php", // your php file
data: { name: "test"} // data that I want to send
}).done(function( msg ) {
alert( "Data Saved: " + msg ); // after success show msg
})
}
}

Problems accessing data from jQuery “serialize()” form to PHP backend

I’m trying to pass values from a dynamic form to PHP, using jQuery serialize(), but I am only receiving part of the string:
The form is created by a MySQL query:
echo '<form role="form" id="reserva_tour" action="shop_wopt.php" method="POST">';
$db->Consultar("SELECT * FROM tour_options WHERE tourID = '$tour_id' order by tourID");
while($row = $db->ObtenerArray()) {
$regis = $row['recid'];
$name = $row['name'];
$radl = $row['adl_rate'];
print "<a href='#' class='tit_tour btn btn-success'>$name - $$ratebase</a>";
print "<input type='text' name='open_adl[$regis]' id='adl$regis' class='adl' />";
}
print "Tour Calc ";
print "</form>";
The jQuery:
$(".calcTourOpt").click(function()
{
var adl = $('.adl').serialize().replace(/%5B/g, '[').replace(/%5D/g, ']');
console.log(adl);
$.ajax({
url: "calctour_opt.php",
data:"adl=" + adl + "",
type: "POST",
dataType: "json",
cache: false,
success: function(data){
console.log(data)
}
});
});
This is calctour_opt.php:
$adl = $_POST['adl'];
$values = array();
parse_str($adl);
$total = $open_adl[4];
echo json_encode($total);
This is happening:
After serializing the class "adl" (before the ajax call, in the console.log), the string looks like this: open_adl[4]=2&open_adl[5]=3 and is correct!
In my php file if I declare $total = $open_adl[4]; works fine, it shows me the result: 2.
But if I change to: $total = $open_adl[5]; does not work, it shows me NULL, instead of 3.
Can anybody tell me what is wrong?
You should change $.ajax data param from string to json string like this
// FROM
$.ajax({
url: "calctour_opt.php",
data:"adl=" + adl + "", //<- Wrong
type: "POST",
...
// TO
$.ajax({
url: "calctour_opt.php",
data: {adl: adl}, //<- Correct
check documentation here about data param for ajax - http://api.jquery.com/jquery.ajax/

Calling an Ajax function based on button class name click

I have created several image buttons in php. I have assigned a common class to all of them. When I call a jquery function based on button class name click. This works fine but when I try calling an ajax function it doesn't work. There is no error seen.
PHP to create a button
function printpic($name, $picpath, $category, $pic)
{
$style = " margin=0px; background-color=transparent; border=none;";
//$functionname= "selectedpic(this.id)";
$functionname= "myCall(this.id);";
$styleimage = "HEIGHT= 120 WIDTH= 120 BORDER=0";
$eventimage1= "zoomin(this)";
$eventimage2= "zoomout(this)";
$btnclass="btnclass";
$j=0;
$spa=0;
$i=0;
for($k=0; $k<4; $k++)
{
echo "<tr>";
for($j=0; $j<4; $j++)
{
echo"<td>";
$btn= "btn".$category[$i];
echo "<span id='" . $spa. "'>";
echo "<button name='" . $btn. "'
margin ='".$style."'
class='".$btnclass."'
onClick='".$functionname."'
>";
echo "<img src='". $picpath[$i]."/".$name[$i]."'
id ='".$pic[$i]."'
alt ='".$name[$i]."'
.$styleimage.
onMouseMove='".$eventimage1."'
onMouseOut='".$eventimage2."'
>";
echo "</button >";
$spa++;
echo"</span>";
echo"</td>";
$i++;
} // wfor
echo "</tr>";
}// for
} // end function
?>
Jquery + Ajax
$(document).ready(function(e) {
$('.btnclass').click(function() {
event = event || window.event;
var target = event.target || event.srcElement;
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
success: function(responseText) { // get the response
if(responseText == 1) { alert ("hi");}
else { alert (datastring); }
} // end success
}); // ajax end
});
});
indexverification.php
<?php
session_start();
$picno=$_SESSION['picno']; // picno from db
$answer=$_SESSION['answer']; // answer from db
$id=$_POST['id']; // id of picture clicked
$ans=$_SESSION['ans']; // answer type
if (($id==$picno) && ($answer==$ans))
{
echo '1';
}
else
{
echo '2';
}
?>
I think you use the wrong syntax. Try this:
//AJAX request
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
})
//Success action
.success(function( html ) {
if(responseText == 1) { alert ("hi");}
else { alert (datastring); };
})
//Error action
.fail(function() {
alert("Request failed.");
});

PHP and AJAX search results into a table

I am trying to make a webapp and I have used a php, ajax and mysql search function from another site.
It currently allows me to search the database and return what I want. The only problem I am having is that it returns the results in a simple text box. I want to be able to return the results in a table.
The search simply searches the database for forename, surname, address etc... This is the code I have.
php:
<?php
include('config.php');
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$sql=mysql_query("SELECT * FROM info WHERE CONCAT(Forename,' ',Surname) LIKE '%$search_word%'or Address1 LIKE '%$search_word%' or Address2 LIKE '%$search_word%' or Postcode LIKE '%$search_word%' or DOB LIKE '%$search_word%' ORDER BY ID DESC LIMIT 20 ");
$count=mysql_num_rows($sql);
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
}
?>
This is connecting into the database and pulling out the results. I then have my html etc...:
script:
$(function() {
//-------------- Update Button-----------------
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
// $("#MainTable").append(data);
if(html.length > 0)
{
$("#MainTable tr:not(:first-child)").remove();
}
for(var i = 0; i < html.length; i++)
{
var date = new Date(html[i]["Timestamp"]*1000);
html[i]["Timestamp"] = date.getHours()+":"+date.getMinutes();
$("#MainTable").append("<tr><td><a href='#' id='info"+data[i]["ID"]+"' data-role='button' data-theme='b' data-icon='check' data-iconpos='notext' class='id'></a></td><td>"+data[i]["Timestamp"]+"</td><td>"+data[i]["ID"]+"</td><td>"+data[i]["Forename"]+" "+data[i]["Surname"]+"</td><td class='hidden'>"+data[i]["ID"]+"</td><td>"+data[i]["DOB"]+"</td><td class='hidden'>"+data[i]["Address2"]+"</td><td class='hidden'>"+data[i]["Town"]+"</td><td class='hidden'>"+data[i]["City"]+"</td><td class='hidden'>"+data[i]["County"]+"</td><td>"+data[i]["Address1"]+"</td><td>"+data[i]["Postcode"]+"</td><td class='hidden'>"+data[i]["Phone2"]+"</td><td class='hidden'>"+data[i]["DOB"]+"</td></tr>");
if(data[i]["Completed"] == "1")
{
$("#MainTable tr:last-child td").addClass("lineThrough");
}
$("#MainTable tr:last td:first a, #MainTable tr:last td:last a").button();
}
}
});
}
return false;
});
//---------------- Delete Button----------------
});
I have tried a few different things such as changing the +Data+ in the table script to html or tried adding append(html) but I am having no luck and when I search I am instead getting undefined in my table or it is blank completely.
This is the HTML for my table:
<table data-role="table" id="MainTable" data-mode="columntoggle">
<tr><th> </th><th>ID Number</th><th>Name</th><th>DOB</th><th>Address</th><th>Postcode</th></tr>
<tr><td colspan='7'>No data currently available, connect to the internet to fetch the latest appointments.</td></tr>
</table>
Would appreciate any help with this. Hope this makes sense.
Instead of outputting this in your php page:
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<li><?php echo $final_msg; ?></li>
Loop through the results outputting them in the table format you need, e.g:
echo "<tr>";
echo "<td>".$row['Forename']."</td>";
echo "<td>".$row['Surname']."</td>";
//etc
echo "</tr>"
Then take that response and fill the containing table with (jquery AJAX) something like:
.done(function( response ) {
$('#MainTable').html(response);
}
Changes:
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$result = $row['Forename'].' '.$row['Surname'].' '.$row['DOB'].' '.$row['Address1'].' '.$row['Address2'].' '.$row['Postcode'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $result);
?>
<tr>
<td> </td>
<td><?=$row['id']?></td>
<td><?=$final_msg?></td>
<td><?=$row['address']?></td>
<td><?=$row['postcode']?></td>
</tr>
<?php
}
}
else
{
echo "<li>No Results</li>";
}
Changes in the JS
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
$("#MainTable").append(html); //<-- append the data from the ajax
}
});

how come i can't populate textarea with <br>, by the way im using ajax

this is the ajax im using,
$.ajax({
type: "POST",
url: "../../Ajax/<?php echo $exercise_num ?>",
data: "user_input=" + user_input,
success: function(resp){
//output
$("#message").text(resp);
}
});
}
and when i try to populate $("#message").text(resp) with
public function pb3()
{
$num1 = 10;
$num2 = 7;
echo "$num1 + $num2 = "; echo $num1 + $num2;echo "<br>hi";
}
my html code:
Message: <font id="message"></font>
the output:
Message: 10 + 7 = 17<br> hi;
or is there any way to use br in the textarea of font?
You can't have html inside a textarea. It won't be interpreted properly, and it should be escaped to prevent injection. You want to use a newline:
echo "\n\nhi";
Try this :
$("#message").text(resp.replace("<br>", "\n"));
ref : http://www.w3schools.com/jsref/jsref_replace.asp
you can replace <br> with \n ,
main thing is you cannot put html tags on textarea value
$.ajax({
type: "POST",
url: "../../Ajax/<?php echo $exercise_num ?>",
data: "user_input=" + user_input,
success: function(resp){
//output
$("#message").text(resp.split("<br>").join("\n"));
}
});
}

Categories