$.get() not working Jquery - php

I'm tryin to get a value in URL from php file via $.get(), here is the code:
PHP folder called 'jquery_con4.php':
echo (isset($_GET['req'])) ? 'found':'notfound';
JQuery called 'pass.js':
$.get('connection/jquery_con4.php', function(data){
alert(data);
});
the main folder called 'password_c.php' which include the javascript called 'pass.js' which has $.get but it shows me in note 'notfound', & if remove if echo, it shows be 'undefined index:req'
--- URL is: 'http://localhost/series/skyface/password_c.php?req=65yDq0zI39UcRSF'
Thanks!

http://localhost:8888/series/skyface/password_c.php?req=65yDq0zI39UcRSF
In order to pass the 'req' value from the URL querystring to the jquery_con4.php script, you need a JS function that will grab it for you and pass it into an ajax request.
Below is an example of how that might work.
/series/skyface/password_c.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="../../main.js"></script>
</body>
</html>
/main.js:
jQuery(document).ready(function($) {
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function success(data) {
console.log(data);
}
$.ajax({
url: '/connection/jquery_con4.php',
data: {req : getParameterByName('req')},
success: success
});
});
/connection/jquery_con4.php:
<?php echo(isset($_GET['req'])) ? 'found' : 'notfound'; ?>

Related

jQuery Json response printing html tags

When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.

how to change the url using php and ajax without reloading the page?

I want to make a web site that when login page redirected to a profile page the url changed to the user name as bellow( such as facebook) .
If the URL is :
localhost/profile.php
How to change it to :
localhost/username
that's my code : (my problem is commented within )
<?php
if(isset($_POST['changeUrl'])){
$url= "/newUrl";
echo $url;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-2.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
changeUrl(history.state);
function changeUrl(){
var currentState = history.state;
$.ajax({
url :currentState ,
data : {changeUrl : "changeUrl"} ,
type : 'post' ,
success : function(replacementState){
alert(replacementState);
//the return string from the alert function is "/newUrl<!DOCTYPE html><html><head>...all between....</html>"
window.history.pushState(currentState, "", replacementState);
},
});
}
});
</script>
</head>
<body>
</body>
</html>

ajax new record count notification in php

iam doing a page in php that if any new record is entered it will notify the users screen with the new record count. Following is the code i did for the same, but its not working fine. Can u pls suggest me as of what iam doing wrong...
alert.php
<?php
require("config.php");
$result = mysql_query("SELECT * FROM marketing_tend_corr");
$res = mysql_num_rows($result);
echo $res;
?>
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
define('BASEPATH', true);
require("config.php");
?>
<script>
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
if (count_cases != -1 && count_cases != response) echo $count_cases);
count_cases = response;
}
});
},1000);
</script>
The following line of code is not going to work in Javascript:
if (count_cases != -1 && count_cases != response) echo $count_cases);
This line of code contains php code (echo $count_cases) which is server side code.
I've changed the code a bit and replaced the number of records by returning a random value.
// alert.php
<?php
echo rand(1, 1000000);
//index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
$("body").html(response);
}
});
},1000);
</script>
</head>
<body>
</body>
</html>
You can check the index.php file in your browser to see the random numbers being returned. This random number should in your case become the result of your 'mysql_num_rows' function.

post php array to ajax using jquery

I have the following :
<script charset="UTF-8">
function deleter(theid) {
var namme = document.getElementById(theid).id;
$.post( "sql_machine.php", {
selection_name: select_namme
})
}
</script>
using jquery, would it be possible to post a php array too? may be encoding it as json?
like the following?
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine_tomskus.php", {
selection_name: select_namme,
{ array : dataToSend }
})
}
</script>
Just use JSON.stringify to send the array, and to decode it to array in php, use json_decode.
In JQ:
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine_tomskus.php", {
selection_name: select_namme,
array : JSON.stringify(yourArrayOrObject)
})
}
</script>
Then, in php just use json_decode($_POST["array"])
thanksGINCHER here it is my final solution :
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine.php", {
selection_name: select_namme,
array : <?echo json_encode($array);?>
})
}
</script>

How do I send data to my PHP script using AJAX?

I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.
Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>
For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.

Categories