I cant see data from the jquery post - javascript

I wanted to perform jquery post to php and get the data and post to the console log. But however i cant find data on the console.log after performing post the data. my code is found below...........please help me...
student html page
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post("student.php",
{
PostLastName: "Abdullah",
PostLastReligion: "Muslim"
},
function(data)
{
console.log(data);
});
});
</script>
</body>
</html>
student.php script
<?php
if ((empty($_POST["PostLastName"])) && (empty($_POST["PostLastReligion"])))
{
//Return "Posted Values are empty" if the values is empty
$post_string = 'Posted Values Are Empty';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
else
{
//Return the Post Data
$post_string= 'Post Last Name = '.$_POST["PostLastName"]."\n".' Post Last Religion = '.$_POST["PostLastReligion"].'';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
?>

I have test your code. i think check first check your loaded jquery included in header.
After change some code like below mention and test your browser console.
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post( "student.php", { PostLastName: "Abdullah", PostLastReligion: "Muslim" })
.done(function( data ) {
console.log(data);
});
};
</script>
</body>
</html>
I hope u resolve u r issue.

Related

send login request to server using jquery POST method

I want to log into this website: https://kintai.jinjer.biz/sign_in
I sent log in credentials to the website form using POST method and request login as a response.
However it does not work. I get redirected to login page when i click button.
Is there something wrong with the code?
<html>
<head>
<title> Approach to Login</title>
<script type="text/javascript" src="https://jinji.jinjer.biz/assets/templates/hr/js/jquery.min.js"></script>
<script async="" src="//wap.wovn.io/1.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$.post("https://kintai.jinjer.biz/sign_in",{
company_code:"5709",
email:"1234",
password:"1234"
},function (data) {
    window.open("https://kintai.jinjer.biz/staffs/top");
});
});
});
</script>
</head>
<body>
<button type= "submit"> Login </button>
</body>
</html>
Try adding prevent default.
$("button").click(function (e) {
e.preventDefault();
$.post("https://kintai.jinjer.biz/sign_in",{
company_code:"5709",
email:"1234",
password:"1234"
},function (data) {
    window.open("https://kintai.jinjer.biz/staffs/top");
});
});

How to use a .click function in jQuery

The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>

Why is the js and html code not running the search query?

I am trying to use Youtube's api, and run a search query to retrieve the videos found. When I run the js or the html, nothing is printing. The authentication key is correct. When I run the js file all it says is [Finished in 0.4s]. When I run the html file nothing shows up.
js file
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad() {
gapi.client.setApiKey('hidden');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'dog'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response) {
showResponse(response);
}
search html code
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
By default the return value for the video link is the video ID inside the json response format.
"id": {
"kind": "youtube#video",
"videoId": "dgVKzvO5zNc"
}
you can filter the json response and create a work around like a link, here is an example:
request.execute(function(response) {
var items = response.result.items;
for(i in items){
var vidID = items[i].id.videoId;
var link = '' + "link"+[i] + '<br>';
document.getElementById('search-container').innerHTML += link;
}
});
html file
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<div id="buttons"><input id="query" value='cats' type="text"/><button id="search-button" onclick="search()" >Search</button></label>
</div>
<div id="search-container">
</div>
</body>
</html>

Send info from javascript dialog to php

I get info in javascript dialog like this:
<!DOCTYPE html>
<html>
<body>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
//Here is my info
}
</script>
</body>
</html>
How can I send this "myInfo" to PHP file (in the same server of javascript file) via GET, POST or by other method?
This is fairly easy with ajax,
PHP Code:
<?php
$data=$_GET['data'];
//Do something with it
echo 'Response';
die();
?>
HTML Code:
<!DOCTYPE html>
<html>
<body>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
//Do someting with it
}
}
xmlhttp.open("GET","/file.php?data="+myInfo,true);
xmlhttp.send();
}
</script>
</body>
</html>
Instead of using native ajax you can use jquery and ajax to send data like below
<!DOCTYPE html>
<html>
<body>
<script src="jquery-1.11.3.min.js"></script>
<script>
var myInfo = prompt("Please enter info", "");
if (myInfo != null) {
$.ajax({
url: "php_page.php",
data: {
info: myInfo
},
success: function( data ) {
alert( "data sent" );
}
});
}
</script>
</body>
</html>
You will have to use jquery.js inorder to use this ajax functionality. On your php page you can directly refer the variable using $_REQUEST method as below
<?php
$data= $_REQUEST['info'];
?>
for more info on how jquery works you can refer to jquery.com

Get results from database using AJAX

In line 10, I have insert getSuggestion(q); for me to get results from my database but it does not work.
What should I put there in order for me to retrieve results from database while other codes remain the same?
This is my current code:
<html>
<script type="text/javascript" src="javascript/hogan-2.0.0.js"></script>
<script type="text/javascript" src="javascript/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="javascript/typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
<script type="text/javascript">
//document.getElementById("suggestion")
function getSuggestion(q) {
var ajax;
if(window.XMLHttpRequest)//for ie7+, FF, Chrome
ajax = new XMLHttpRequest();//ajax object
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
ajax.onreadystatechange = function() {
if(ajax.status === 200 && ajax.readyState === 4) {
//if result are not there then don't display them
if(ajax.responseText === "")
document.getElementById("suggestion").style.visibility = "hidden";
else {
document.getElementById("suggestion").style.visibility = "visible";
document.getElementById("suggestion").innerHTML = ajax.responseText;
}
}
};
ajax.open("GET", "suggestion.php?q=" + q, false);
ajax.send();
}
</script>
</html>
Thanks in advance.
Replace
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
with this:
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
And that's all you need. Typeahead does the rest.
Query is in $_GET['q']
You can find my example here
My index.php looks like this:
<html>
<head>
<link rel="stylesheet" href="http://twitter.github.io/typeahead.js/css/main.css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/typeahead/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
</head>
<body>
<input type="text" class="q typeahead tt-query" />
</body>
You dont need css file or classes to input. Only class "q" is needed.
<input type="text" class="q" />
And suggestion.php source:
<?php
$q = $_GET['q'];
echo json_encode(array($q));
?>
As you can see, whetever you currently search, it answers with the same result as you typed. You have to make database query and echo array with json_encode
Remember to add correct url to remote parameter.
EDIT: My example now gets data from itunes and searches for music videos. Edited source available in example.

Categories