I'm making a web application and I'm trying to make it so when you enter the ID of a provider it automatically outputs them into a span, this is my AJAX/JS call
<script>
function showHint(str)
{
if (str.length == 0)
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../include/proveedores.php?q=" + str, true);
xmlhttp.send();
console.log(telfValor);
}
}
</script>
<span id="txtHint"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
And this is the .php it calls to make the search
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = $_REQUEST["q"];
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
// Output "no suggestion" if no hint was found or output correct values
echo $descrip === "" ? "no suggestion" : $descrip;
?>
Is there any way to accomplish this?
EDIT: This is to make an AJAX calls to return various values into spans with just 1 AJAX call
<script src="../js/jquery.js" type="text/javascript"></script>
<script>
function showHint(str)
{
// If there is nothing on the textbox, there is nothing in the spans
if (str.length === 0)
{
$('#Span Name').html("");
$('#Telephone').html("");
return;
}
$.ajax
({
//Here goes the file which contains the SQL call
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
// Here goes the data that goes into the spans
success: function (data, status, jqXhr)
{
$("#Span Name").html(data["Array Name"]);
$("#Telephone").html(data["Telephone"]);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
}
</script>
// This is the text input that will be sent to your query file
<input type="text" onkeyup="showHint(this.value)">
<span id="Span Name"></span>
<span id="Telephone"></span>
proveedores.php:
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL, this is what you have posted
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
if (isset($q) && $q !== "")
{
// THIS IS PRONE TO SQL INJECTION! USE INTERNALLY!
$sql = "SELECT * FROM PROVIDERS WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$Variable = $row['Column Name'];
$Telf = $row['Telef'];
$Direc = $row['Direc1'];
}
// This is the array to be encoded to AJAX
$values = array();
// Output "no suggestion" if no hint was found or output correct values
$values["ArrayName"] = ($Variable === "") ? "no suggestion" : $Variable;
$values["Telephone"] = ($Telf === "") ? "" : $Telf;
// Output the json data
print_r(json_encode($values));
?>
To start, you should use a javascript library like jQuery to handle all the tough AJAX lifting. It will make your life sooo much easier. If you want to use regular javascript, you can return a comma-separated string and then parse each value separated by a comma but that can get messy. With that being said, you can use jQuery AJAX and return your data in a JSON encoded data object.
.php
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
$values = array();
// Output "no suggestion" if no hint was found or output correct values
// NOTE: we're using the same "txtHint" here for the key as we do in the javascript function
$values["txtHint"] = ($descrip === "") ? "no suggestion" : $descrip;
// Set these to something useful
$values["txtPhone"] = "";
$values["txtAddress"] = "";
// Output the json data
print_r(json_encode($values));
?>
Now, for the jQuery implementation. The first thing you'll have to do is download the jQuery library from jQuery's website. I would recommend getting the most recent version (currently jQuery 2.x).
.html
<script src="/script/jquery.js" type="text/javascript"></script>
<script>
function showHint(str) {
if (str.length === 0) {
$('#txtHint').html("");
return;
}
$.ajax({
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr) {
$("#txtHint").html(data["txtHint"]);
// You can do this same thing for the other data returned
$("#txtPhone").html(data["txtPhone"]);
$("#txtAddress").html(data["txtAddress"]);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}
});
// Not sure where this is defined. It might throw an error
console.log(telfValor);
}
</script>
<span id="txtHint"></span>
<span id="txtPhone"></span>
<span id="txtAddress"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
The obvious change is the call to $.ajax() instead of using the XmlHttpRequest() object. It is in and of itself fairly self-explanatory. One thing I would like to mention is that since we set the "type" to "GET", the key-value pairs in "data" will be appended to the url as a querystring in the form: "url?key1=value1&key2=value2&etc...". So the resulting url, in our case, would be "../include/proveedores.php?q=[VALUE_OF_STR]" where [VALUE_OF_STR] is the value of the str variable.
The other change worth noting is that jQuery has a very helpful way of selecting elements. If you want to get an element by an ID you can just use the syntax: $('#txtHint').
Where the '#' symbol denotes that we're looking for an element based on the ID and 'txtHint' is the ID of the element you're looking for. You can read more about jQuery selectors in the docs.
Related
I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",
I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}
So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})
I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.
I'm trying to create a small chat application but for the sake of minifying the bytes being transferred is there any other way on writing this javascript that is less heavy than this code?
Here is my javascript:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
Can this also be done on a JSON format too? because I think some says that json is lighter.. not sure though
here is my php code
$con = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt=$con->prepare($sql);
$stmt->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$text=$_POST['message'];
$sql4 = "INSERT INTO $tblname2(msgid,username,message_content,message_time,recipient)VALUES(:aid,:a,:b,NOW(),:c) ";
$stmt5 = $con2->prepare($sql4);
$stmt5->bindParam(':aid',$tblpre,PDO::PARAM_STR);
$stmt5->bindParam(':a',$_POST['name'],PDO::PARAM_STR);
$stmt5->bindParam(':b',$text,PDO::PARAM_STR);
$stmt5->bindParam(':c',$usern,PDO::PARAM_STR);
$stmt5->execute();
As user2401175 saies. Why not use a framework, thats what they are here for.
jQuery is really simple and easy to understand.
You could try adding this, just before your "" tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Under this include of jQuery, you may now use the jQuery Post method to do your ajax request.
In html Use
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
then Create javascript object like this
var changePacket = {
date1:value1,
data2:value2
}
And send Ajax request
$.ajax({
url: "phpFile.php",
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(changePacket)},
success: function(response) {
alert('hip hip hurray');
},
error: function(response) {
alert('some thing wrong happend');
}
});
In php
$json = $_POST['json'];
$data = json_decode($json);
now user your variable like this $date->data1 and $date->data2
i have a simple ajax script that sends 3 variables to an external php script, it then adds them into an array and sends the array back, and i want it to output it in the javascript console, so that i can check that the variables are being passed back successfully, however when i run the script nothing appears in the console, only that
XHR finished loading: "http://localhost/blank/scripts/ajax/profile_password_submit.php".
Here is the ajax
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=data;
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the external php script
session_start();
include '../../connect.php';
$user_id = "";
$user_id = $_SESSION['userId'];
echo $user_id;
if(empty($_SESSION['userId'])){
echo "user id session not set";
exit;
}
$old_password = $_POST['pro_content_password_old'];
$new_password = $_POST['pro_content_password_new'];
$new_password1 = $_POST['pro_content_password_verify'];
$password_array = array("old"=>$old_password,"new"=>$new_password, "new1"=>$new_password1);
echo json_encode($password_array);
Any ideas? Also i am using Google Chrome console
It looks like you're not outputting a proper JSON object. I don't know for a fact, since you haven't shared what your PHP script is outputting, but I have a feeling that this line in that is what's causing your problem:
echo $user_id;
You're not just outputting a JSON encoded PHP array, you're also outputting the $user_id variable.
jQuery's ajax success callback only fires if it receives a properly formatted JSON object, which yours is not. It probably looks something more like this:
1234{"old": "oldpass", "new": "newpass", "new1": "newpass1"}
You need JSON.stringify :
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=JSON.stringify(data);
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the final working version now, its a lot different to my original but it works a lot better
<script type="text/javascript">
function submit_profile_password(){
//var results = document.getElementById("results");
var result_error = document.getElementById("pro_content_error_password");
var old_error = document.getElementById("pro_password_old_comment");
var new_error = document.getElementById("pro_password_new_comment");
var new1_error = document.getElementById("pro_password_new1_comment");
var oldPass = document.getElementsByName("pro_content_password_old")[0].value;
var newPass = document.getElementsByName("pro_content_password_new")[0].value;
var new1Pass = document.getElementsByName("pro_content_password_verify")[0].value;
var vars = "oldPass="+oldPass+"&newPass="+newPass+"&new1Pass="+new1Pass;
var hr = new XMLHttpRequest();
hr.open("POST", "scripts/ajax/profile_password_submit.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
//results.innerHTML = "";
for(var obj in data){
if(obj == "old"){
old_error.innerHTML = "";
old_error.innerHTML = data[obj];
}else if(obj == "new"){
new_error.innerHTML = "";
new_error.innerHTML = data[obj];
}else if(obj == "new1"){
new1_error.innerHTML = "";
new1_error.innerHTML = data[obj];
}else if(obj == "result"){
result_error.innerHTML = "";
result_error.innerHTML = data[obj];
}
//alert("Key = "+obj+"value = "+data[obj]+"");
}
}
}
hr.send(vars);
//results.innerHTML = "requesting...";
return false;
}
</script>
Thanks all for the help