jQuery send empty data - javascript

I have jQuery script to send data from one php to another one.
<script>
jQuery(function(){
jQuery(".button").click(function(){
$.ajax({
url : "content_articles.php",
type : 'POST',
data : {'mark': ButtonValue}
}).done(function(response){
alert(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
});
});
It should take button's value and send it. The value is right, checked with "some debug" alert. But all I have in the end is alert 'FAILED! ERROR: ' with no error message.
On the other side i use
$rowid=$_POST['mark'];
It is empty of course...
The rest of content_articles
<?php
$rowid=$_POST['mark'];
/*echo $_POST['mark'];
exit;*/
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$res = mysql_query("SELECT id FROM news ORDER BY id DESC LIMIT 1");
$last =mysql_fetch_assoc($res);
if($rowid==""){
$sql="SELECT * FROM news WHERE id = ".$last['id'];
}
else
{
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
}
$result = mysql_query($sql) or die(mysql_error());
?>

In you ajax replace alert('succesful'); by alert(response);.
Let's check if MARK is arriving ok, put next 3 lines at the top of your code :
$rowid=$_POST['mark'];
echo $_POST['mark'];
exit;
Let's shorten your code :
$rowid=$_POST['mark'];
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['SOME_COLUMN'];
You replace "SOME_COLUMN" by a column in table "news".
let's check if there are results from your query, replace the last line by this one:
echo mysql_num_rows( $result );

You can try to use next
var ButtonValue = $(this).attr('value');
// check here that your ButtonValue is not empty, you can call alert(Buttonvalue); to sure that this var is not empty and receive value from clicked element
$.post('content_articles.php', { mark:ButtonValue }, function(data){
alert(data); // to show what the resposne from script
});
Make sure in console of browser that your PHP script is available and server not return any error (like 404 or 500 and etc)

Related

Alert is showing but data is not updating and not able to click ok button of alert

My Alert is showing that updated successfully but data is not updating in database and not able to click ok button of alert. Here is my php code for upresult.php. Hope This will b helpful. Thank you in advance
my jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:formData,
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
You want to alert alert. Try with editing your flow control structure like this:
<?php
include("connection.php");
// you need to validate this data before sending it to update query
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
// this parameters should be binded to avoid SQL injection
$query = "
update stud
set
stud_name = '$name',
mobile = '$mob',
dob = '$dob',
address = '$add',
gender = '$gen',
country = '$cn',
state = '$st',
city = '$ct'
where stud_no = '$no';
";
/** This may be query for checking.
* Just execute it after first query and grab response from it.
* Depends of response you will return appropirate text message.
*/
$checkUpdateQuery = "
select if(count(*) = 1, true, false) as response
from stud
where stud_name = '$name',
and mobile = '$mob',
and dob = '$dob',
and address = '$add',
and gender = '$gen',
and country = '$cn',
and state = '$st',
and city = '$ct'
and stud_no = '$no';
";
/** mysqli_query will return false only if some error occurred.
* In other cases you will get true,
* so you need to check if data is updated by another query.
*/
$data = mysqli_query($conn, $query);
echo $data ? 'Updated Successfully' : 'Cannot update record';
Few things you should consider is do you have certain stud_no in database, mysqli_query returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
If you want we can change this query. Can you use PDO instead of mysqli?

Sending and processing an associative array from jquery to php

I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

ajax function not working fine

I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.

Error in $.ajax call

I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';
dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...
Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);

Categories

Resources