Using php response to populate front end Ajax - javascript

This should be a very easy question, but I cannot find the answer. I have a js file that is making an ajax request to a php file. i am then trying to use the response provided by php to update the front end, but the response is not in the correct format. I am getting back the whole echo statement when I look in the console. Pardon my ignorance here but I am quite new to php. I think there is an issue sending back an a href link and br in my php
$.ajax({
url: 'php.php',
}, function (data) {
console.log(data);
$('.container').html(data);
});
PHP
<?php
$output = 'This is<br>a<br>test<br><span>Test Here</span>';
echo $output;
?>
When all this has successfully worked I want to change my html to:
<div class="container">
This is<br>a<br>test<br><span>Test Here</span>
</div>

When using jQuery's $.ajax function you can use either of { success: function() {...} } or .done() promise:
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
});
Or
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
}).done(function( data) {
console.log(data);
$('.container').html(data);
});

Related

AJAX post to php not getting caught

Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});

I can't passing variable to PHP from JavaScript and jQuery load the response

I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>

Sending a javascript variable to a PHP script using jQuery Ajax

I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
dataType: "script",
data: { "selected_category" : v}
}).done(function() {
window.location.href = "http://mywebsite.com";
});
}
All help is appreciated
Here's the HTML
<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>
</ul>
This is the ajax php file
<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
You need to remove dataType: "script" since you are just sending data. Do it like this:
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
data: {"selected_category": v}
}).done(function(result) {
console.log(result);
//window.location.href = "http://mywebsite.com";
});
}
Hi this is what I do to call an ajax request
You can post data or load a file using following code:
$("#button click or any other event").click(function(){
try
{
$.post("my php page address",
{
'Status':'6',
'var one':$("#myid or .class").val().trim(),
'var 2':'var 2'
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax request you
//can send any type of data whether json or or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
I hope this help!
AJAX is easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#divID').click({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
Your example could be changed to look something like:
HTML:
<ul class="cat">
<li class="opt" value="TheFirstOption">option1</li>
<li class="opt" value="The Second Option">Option 2</li>
</ul>
javascript/jQuery:
$('.opt').click(function(){
var v = $(this).val();
$.ajax({
type: "POST",
url: "myurl.php",
dataType: "html",
data: { "selected_category" : v}
}).done(function(data) {
$('#div_to_insert_the_response').html(data);
});
});
PHP:
<?php
$val = $_POST['selected_category'];
echo 'You selected: ' . $val;
dataType: "script" has no sense here, I think you want json or leave it empty.
Your PHP script should work if you try to get the variable with $_GET['selected_category']
I suggest you this modification to help yourself for debugging
$.ajax({
type: "GET",
url: "myurl.php",
data: { "selected_category" : v},
success: function(data){
console.log(data);
// you can also do redirection here (or in complete below)
},
complete: function(data){
// when request is done, independent of success or error.
},
error: function(data){
// display things to the user
console.error(data);
}
})

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

Return and print value passed through php script from javascript object using jquery ajax

i have the following code:
Javascript object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
dataType: 'json',
success: function(data){
callback(data);
console.log(data)
},
error: function(){}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
return data;
});
}
}
})();
simple php script:
<?php
$tableName = $_REQUEST['table'];
echo $tableName;
?>
My js command for fetching(seperate script ofc):
var obj = getDBresults;
var data = obj.getAllVideoes();
console.log(data)
My issue is with the callback function. It wont output anything and it doesn't seem to be running at all.. Had this issue for quite som time now and i just cant figure it out.. Is there anything i'v been missing? All help is apriciated! Sorry for my spelling btw.
you ajax is expecting
`dataType: 'json',`
json output from your php script
you are returning html/plaintext data
`echo $tableName;`
try json_encode
echo json_encode(array($tableName));
result is not in JSON format, so when jQuery fails to parse it,
You can catch the error with ajax's error: callback function

Categories