javascript function passes only one specific parameter - javascript

I built this function in my html page:
<script type = "text/javascript">
function set() {
var type = 'test';
var status = 0;
var id = 2;
$.post("sys/class/buttonHandler.php"), { status: status};
}
</script>
that is triggered by this button:
<button type="button" onclick="set()" class="btn">Press here</button>
to reach this buttonHandler.php:
<?php
require 'class.global.php';
$type = 'test';
$status = $_POST['status'];
$id = 2;
set($type, $status, $id);
?>
that correctly executes this function in the class.global.php:
function set($type, $status, $id)
{
$result = mysql_query("UPDATE users SET $type = '$status' WHERE id = '$id'");
}
The problem is when I try to change the parameter that the javascript function passes or when I try to add the other two parameters, like this:
<script type = "text/javascript">
function set_profile() {
var type = 'test';
var status = 0;
var id = 2;
$.post("sys/class/admobButtonHandler.php"), { status: status, type: type, id: id};
}
</script>
<?php
require 'class.global.php';
$type = $_POST['type'];
$status = $_POST['status'];
$id = $_POST['id'];
setProfile($type, $status, $id);
?>
Nothing works anymore..
Is there any other way that I can make this work?
Thanks

Take a look at the jQuery docs for the post() function. http://api.jquery.com/jquery.post/. You've got your syntax all wrong... It should be:
$.post("/sys/class/admobButtonHandler.php", {status: status, type: type, id: id});

Related

I want to update value from DB. but my code won't work

Main
public function update_sample(){
$id3 = sanitize($this->input->post('id3'));
$sample3 = sanitize($this->input->post('sample3'));
if($this->session->userdata('position_id') != ""){
$username = $this->model->get_users($this->session->userdata('user_id'))->row()->username;
$query = $this->model->update_sample($data);
$data = array(
"success" => 1,
"message" => 'Note: You have successfully updated');
}else{
$this->logout();
}
generate_json($data);
}
model
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
return $this->db->query($sql, $data);
}
js
$("#table-grid").delegate(".btnUpdate", "click", function(){
var id = $(this).data('value');
$.ajax({
type: 'post',
url: base_url+'Main/view_details',
data: {'id3': id},
success: function(data){
var res1 = data.result1;
if(data.success==1){
document.getElementById("sample3").value = res1[0].samples;
$('#update').modal();
}
}
});
});
I want to update Data from database I've been stuck here for long.
I don't know how your class is created, but it looks like your function only returns true for query execution, you'll need to check for "affected_rows".
Try the code below, with a little luck it may work, otherwise you have to check the $result variable and modify the code corresponding to the result.
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
$result = $this->db->query($sql, $data);
return $result && $result->affected_rows > 0 ? true : false;
}

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

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.

How to send an array to a PHP file so the values can be added to mySQL using HTTP request?

Sending a javaScript array to a PHP file and then storing the elements in a mySQL database.
Currently I'm getting errors in for my "httpSend.responseText" alert. Saying Notice: Undefined index: name in .. line 8
Notice: Undefined index: address in .. on line 9
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in .. on line 12
I'm not sure if the array is sending correctly or being received correctly.
var name = "John";
var address = "UK";
var sendInfo = {
Name: name,
Address: address
};
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}
httpSend.send(sendInfo);
PHP
<?php
include("mysqlconnect.php");
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>
mysqlconnect looks like this
<?php
$connection = mysql_connect("localhost", "user", "pass");
if(!$connection){
die('Could not connect to server: ' . mysql_error());
}
mysql_select_db("database", $connection);
?>
Try this :
var name = "John";
var address = "UK";
var sendInfo = {
Name: name,
Address: address
};
var params = "sendInfo=" + JSON.stringify(sendInfo);
var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);
httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}
httpSend.send(params);
PHP code:
<?php
include("mysqlconnect.php");
$sendInfo = json_decode($_POST['sendInfo']);
$name = $sendInfo ['name'];
$address = $sendInfo ['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>
why are you using single quotes to wrap variables '$name' and '$address' change your code to this may be this will help you:
<?php
include("mysqlconnect.php");
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('".$name."', '".$address."')");
?>
Try this:
<?php
include("mysqlconnect.php");
$name = $_POST['Name']; // NOTE THE CASE CHANGE HERE AS THIS IS WHATS DEFINED IN YOUR JS
$address = $_POST['Address'];
mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('".$name."','".$address."')");
?>
Where is $connection being defined?

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Categories

Resources