ajax multiple data sent parameters php - php

whats wrong with this?
EDIT:
$check = $row['publish'] == 1 ? 'true' : 'false';
It works when I want to unpublished, but if the checkbox is empty I cannot publised.
OnClick="doAction(<?php echo $check;?>, <?php echo $id;?>);"
function doAction(check,id){
$.ajax({
type: "GET",
url: "test.php",
data: "check=" + check + "&id=" + id,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
and the file test.php:
$id = $_GET['id'];
$check = $_GET['check'];
if ($check == "false"){
$query = mysql_query("update article set publish = 1 where id =" . $id);
echo "Published";
}
else {
$query = mysql_query("update article set publish = 0 where id =" . $id);
echo "Unpublished";
}
I cannot display the id in the test.php file.it gives me nothing. But in the doAction parameters are(.., id) so it's been sent but I don t receive it in the ajax call and then in file. Why?

Try change:
data: "check=" + check + "&id = " + id,
To:
data: "check=" + check + "&id=" + id,
And you should define what will be response HTML , JSON etc. use for this example:
dataType: "JSON"

If you are passing the value in arguments use below code.
OnClick="doAction('<?php echo $check;?>', '<?php echo $id;?>');"

Related

Passing json to php and getting response

I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");

Add to database with mysql, ajax and php

I have a file cart.html which displayes a list of items fetched from database and each item has a button 'AddToCart' which when clicked call the function addDB() and add the product to the table product_add.
My problem is that when the button 'AddToCart' is clicked only nulll values are inserted in the table product_add .
//This function is found in the cart.html and get the items from the database
$(document).ready(function() {
$("#product").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "allProducts.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
//the above function is called when a button 'View All Products' is clicked
<input type="button" id="cart" value="View Cart"/>
The above code works fine and displayes the result
//These lines of codes are in the allProducts.php
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td><img src=".$row['image']." width='120' height='100'/></td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['price']."</td>";
echo "<td>";
echo "<input type='button' value='Add to Cart' onclick='addDB()'/>";
echo "</td>";
echo "</tr>";
Here is the function addDB()
function addDB() {
var request = $.ajax({
url: "add.php",
type: "GET",
dataType: "html"
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
};
This is the add.php
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id', '$name','$price')";
$insertQuery=mysql_query($insert);
?>
My problem is that when the button 'AddToCart is clicked' null or 0 are being inserted in the database.Can somebody please help me ?
You are not sending any data to the php-page. A simple approach would be to pass them via GET-Parameters in the url of you AJAX-Call:
function addDB(id, name ,price) {
var request = $.ajax({
url: "add.php?id=" + id + "&name=" + name + "&price=" + price,
type: "GET"
});
request.done(function() {
alert("Ajax call done.");
});
}
Also, your code is vulnerable to sql-injections. Please do ALWAYS use prepared statements
You modified add.php would then look like this:
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$query = $mysqli->prepare("INSERT INTO product_add(id, name, price) VALUES (?, ?, ?)");
$query->bind_param("isi", $id, $name, $price);
$query->execute();
$query->close();
?>
You would of course have to initialize the object "$mysqli" somehow in your file dbConnect.php in order to use it.

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

Sending ajax request gets an error

The following abstract of my code given:
JS
$(function() {
$(".submit").click(function() {
var dataString = 'user=' + user + '&size=' + size + '&q_1=' + q_1 + '&q_2=' + q_2 + '&q_3=' + q_3 + '&q_4=' + q_4 + '&q_5=' + q_5;
$.ajax({
type: "POST",
url: "form_send.php",
data: dataString,
success: function() {
//success
},
error: function() {
//error
}
});
return false;
});
});
PHP
if ($_POST) {
$user = $_POST['user'];
$size = $_POST['size'];
$q1 = $_POST['q_1'];
$q2 = $_POST['q_2'];
$q3 = $_POST['q_3'];
$q4 = $_POST['q_4'];
$q5 = $_POST['q_5'];
//insert data
$insert = mysql_query("INSERT INTO table (username, size, q_1, q_2, q_3, q_4, q_5) VALUES ('$user', '$size', '$q1', '$q2', '$q3', '$q4', '$q5')");
if(!$insert){ die("There's little problem: ".mysql_error());}
}
The other code is checked and working all right, so there has to be a mistake in this abstract; also I cannot find one.
Its always going into the "error" of the ajax request. Thanks in advance for the help!
your data in ajax should like this
data:{'user' : user, 'size':size,'q_1' : q_1 , 'q_2':q_2, 'q_3': q_3 , 'q_4':q_4, 'q_5' :q_5}

Categories