Simple Jquery POST call not working - javascript

I got a simple POST call to a PHP file on my website. For some reason it's not working though. The console.log shows"undefined"
function check() {
var url = "../API/keychecker.php";
var spullen = $("keyval").val;
$.ajax({
type: "POST",
url: url,
data: {
key: spullen
},
success: function(data) {
console.log(data);
}
})
}
Here is the PHP file:
<?php
echo json_encode($_POST['key']);
?>

Your keyval call doesn't specify the type of element identifier. jQuery won't find the element you're looking for as you currently have it.
You must specify:
For classes:
$( ".keyval" ).val();
For ID
$( "#keyval" ).val();
For input name
$( "input[name=keyval]" ).val();
That should attach the value to the POST request.

var url = "API/keychecker.php";
var spullen = $( "keyval" ).val();

Related

Call PHP function with javascript with a javascript parameter

I have this simple javascript which calls a PHP function flawlessly:
var showFeedPHP = "<?php showFeed($link, $category, $siteVersion, $cookie_index, $myuserlevel, $perPage, $showFrom); ?>";
$( "#sectionPosts" ).append( ""+showFeedPHP+"" );
I would like the last paramter, $showFrom, to be a javascript variable.
However, this version doesn't work and will just set the last parameter to the text string "+showFromJS+" :
var showFromJS = 10;
var showFeedPHP = "<?php showFeed($link, $category, $siteVersion, $cookie_index, $myuserlevel, $perPage, "+showFromJS+"); ?>";
$( "#sectionPosts" ).append( ""+showFeedPHP+"" );
I would like to use a javascript variable for declaring one of the php function parameters, but how?
You have to use Ajax in this case here is a sample
var showdeed= function(id) {
$.ajax({
url: 'path/to/php/file/showFeed',
type: 'GET',
data: {link:link,
category:category,...},
success: function(data) {
$( "#sectionPosts" ).append( ""+data+"" );
}
});
};
You must use AJAX to achieve your objective
function loadData() {
$.ajax({
url: "path_to_showfeed.php?var1="+<?php echo json_encode($link);?>+"&var2="+<?php echo json_encode($category);?>+"&var3="....
}).done(function(data) {
$( "#sectionPosts" ).append( ""+data+"" );
});
}
Also add this line to your head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

JQuery Autocomplete and AJAX combination

I'm trying to implement auto-complete on a textbox in php. The data from autocomplete is retrieved using a GET ajax call (which calls a certain api and returns json output).
The code for my ajax was as follows:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
console.log("1. " + obj[0]);
console.log("2. " + obj[1]);
}
});
});
});
</script>
This code was working perfectly find, and the output was shown in the console correctly. Next I tried adding this ajax call as "source" to my autcomplete call as follows:
<script type="text/javascript">
$(function() {
var query = document.getElementsByName('newartist')[0].value;
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var outp = [];
outp.push(obj.sections[0].data[0].name);
outp.push(obj.sections[0].data[1].name);
console.log(obj.sections[0].data[0].name);
console.log(obj.sections[0].data[1].name);
response(outp);
}
});
}
});
});
</script>
Here, the code stopped working for some reasons, and any console.log commands I had stopped outputting the results.
One other method I found as answer to a similar question was to implement the following code:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var artists = [];
artists.push(obj[0]);
artists.push(obj[1]);
test(obj);
}
});
});
});
function test(data){
console.log(data);
$("#tags").autocomplete({
source: data
});
}
</script>
This was a bit better as autocomplete was indeed suggesting results, but it was inconsistent as it sometimes outputted 1 result instead of 2 (my ajax call ALWAYS returns 2 results, and I made sure that it's always the case by using console.log), and sometimes the suggestions proposed by autocomplete were those of the previous AJAX call and not the current one (again, console showed new results but autocomplete suggested previous ones.
If you could point to the errors in both of these methods, it would be great.
Thanks!!
Code looking fine. Please mention the JSON output format.

live search bootstrap with ajax and query

Me and some mates have been trying to make a live search script on our search bar. Now this isn't going that well so now we are asking for ur help!
our external file to get the results is this :
$con = mysqli_connect('localhost', '*', '*', '*');
$key=$_POST['search'];
$query = ("select name, url from search where name LIKE '%{$key}%'");
$sql = $con->query($query);
while($row = $sql->fetch_array()){
echo json_encode($row);
}
and our script code looks like this :
<script>
$(document).ready(function(){
$( "#formGroupInputLarge" ).keyup(function() {
console.log( "Handler for .keyup() called." )
var string = $('#formGroupInputLarge').val();
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {'search': string},
success: function(data){
var text= JSON.parse(data);
$("#suggesstion-box").show();
$("#suggesstion-box").html("<a href='#'>"+ text +"</a>");
$("#search-box").css("background","#FFF");
}
}
);
});
});
</script>
we've tried with multiple things like the next ones :
<script>
$(document).ready(function () {
$("#formGroupInputLarge").keyup(function () {
console.log("Handler for .keyup() called.");
var string = $('#formGroupInputLarge').val();
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {'search': string},
success: function (data) {
var obj = eval('('+ data +')' );
console.log(obj['name']);
//var text = JSON.parse(data);
//$("#suggesstion-box").show();
//$("#suggesstion-box").html(text);
//$("#search-box").css("background", "#FFF");
}
}
);
});
});
</script>
but none of it seems to work. Please help us!
So many things could be wrong in your code !
You need to give more info on how each part behaves (error messages, etc).
Check this to get a good look at how everything work with AJAX, and nice and simple examples http://www.w3schools.com/php/php_ajax_intro.asp

parsing value from a text field to the data base with jquery

I created a simple text field form and a button on a webpage:
<input type="text" value="name"><button>click me</button>
and I created a short script in jquery:
<script>
$( "button" ).click(function() {
var text = $( "input" ).text();
$( "input" ).val( text );
});
</script>
What I want to achieve is to take the value written by user in the text field and after hitting the button - inserting taken value from text field to the database. I have database ready, but I've never connected with that through jquery, I only used php for that. Right now when I press the button, I get the "name" string inside the text field (instead of string typed before). How should I change the code to make it work?
Thanks!
You need to continue to use php to talk to the database and use
jQuery.ajax(), or the .post() or .get() shorthand, to send the data to php. So:
$("button").click(function() {
$.post('myphpfile.php', { mytext: $('input').val() });
});
then in your php file:
<?php
if( $_REQUEST["mytext"] )
{
$mytext = $_REQUEST['mytext'];
// insert $mytext into database
}
?>
$( "button" ).click(function() {
$.ajax({
method: "POST",
url: "save.php",
data: $("input").val()
})
.done(function( msg ) {
alert( "Data Saved" );
});
});
Use AJAX call to call you service and pass you value parameter along with that.
var val=$('#text').val();
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "value="+val,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
<input type="text" value="name" id="name">
<input type="button" id="button" value="Click Me"/>
<script>
$( "#button" ).click(function() {
var text = $("#name").val();
$.ajax({
url: 'location.php',
type: "POST",
data: {
text: text
},
success: function(response)
{
alert("inserted");
}
});
});
</script>
it will just get the input value than you have to post it using ajax and using mysql you can insert the value to database

AJAX: Can't pass javascript variable to SQL query in PHP script

I have a PHP page with 2 sections side by side. The left pane has a MySQL query that runs and produces a list of categories as links. The right pane should have subcategories that appear when links in the left pane are clicked.
I have some AJAX in an attached JS file that should pass the ID in the links from the left pane, into a query in the right pane. The query should run. It runs if I take out a variable.
The PHP/SQL Queries work fine. JS does not.
I think this is the appropriate way of doing this.
ajax.js
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: "ajax="+a,
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
})
});
});
I am being told everything works, but I cannot call $_POST['ajax'] in PHP. Perhaps my page is not being refreshed. There is no form on the page.
Lastly, my file hierarchy has categories.php comprised of a list of includes, which are in a folder that is not public.
I think your ajax syntax is wrong. Try this if your argument is a and your post identifier is ajax:
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: {ajax : a},
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
});
});
});
Try setting async: false on your $.ajax call. Also, how is the data being return from php? Are you using JSON_ENCODE for the data?

Categories