Parsing URL jQuery AJAX form - php

Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.
There is a way of inputting a video url into this. I've got everything working except one thing.
If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM
it works fine.
but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu
doesn't.
I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.
This is the problem:
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
because its reading like
var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';
it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax
Any ideas how to solve this?
EDIT:
Here's the full code that's the problem:
var title = $('input#title').val();
var content = $('textarea#content').val();
var date = $('input#date').val();
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: dataString,
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})
return false;
if content equals:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid>
<br>Text 3<br>
the content variable gets put through the ajax call as:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI
with an extra variable that is
&feature=feedu</vid>
<br>Text 3<br>
So how do u stop the ajax reading &feature as a separate $_POST variable?

Did you encodeURI() before pass the your video url?
If you need it in PHP then URLEncode

I used this bit of code in the php file
if(isset($_POST['feature'])){
$content=htmlspecialchars_decode(stripslashes(nl2br("<br />".$_POST['content'].'&feature='.$_POST['feature']."<br />")));
}
But it's not very dynamic as it only applies to youtube URLs

In JS do (before ajaxing)
dataString = encodeURI(dataString);
And then decode it on PHP
$dataString = urldecode($_POST['data']);
Or do:
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: {
'title': $('input#title').val(),
'content': $('textarea#content').val(),
'date': $('input#date').val(),
'Submit': 'Yes'
}
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})

Related

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

correct JSON format from Jquery to PHP

I'm working on a project coding PHP-AJAX-Jquery and JSON and need to send the information of a form that has three input fields to a php file that will store the info of the three fields in the database.
my problem is that I need(I have because of project spec) to use Jquery-AJAX and JSON and I think I'm passing in a malformed JSON string to the PHP file, this is the js that is supposed to handle the call:
$(document).ready(function(){
$('#ID_formulario').on('submit',function(e) {
e.preventDefault();
var nombre = $('input#ID_nombre');
var email = $('input#ID_email');
if(validaForm(nombre, email)){
var url = $(this).attr('action');
var data = $(this).serializeArray();
var type = $(this).attr('method');
alert(data);
$.ajax({
url:url,
data:data,
type:type,
cache: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
beforeSend: function () {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="imagen.gif" align="absmiddle"> <span class="loading">Realizando peticion...</span>');
},
error: function(){
alert("error peticiĆ³n ajax");
},
success: function(datos){
$('#result').empty().html(respuesta). fadeIn('slow').delay(5000).fadeOut();
$('#ID_formulario')[0].reset();
$('input#ID_nombre').focus();
$("#flash").hide();
//$("#display").after(html);
//$("#result").append(data);
}
});
}
});
});
my questions are: how to send the info of the three fields in a valid JSON format to the php file? is there any jquery function that helps? or is serializeArray() enough?
It's okay to use success: function(datos) or should I replace it to .done(function)) ?
thanks in advance.
You dont need to send anything as JSON to PHP. Just send it with type: POST and read it in PHP. Then return it as JSON to read in Javascript. You just read the $_POST in PHP. I believe you've mistaken your project specs and you need to RETURN data from PHP as JSON.
This is one of my projects:
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "product"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
// Read returned JSON. Exammple
"<div class='data-row'><strong>TYPE</strong> " + data["title"]+ "</div>";
);
}
});
return false;
});
});
In PHP you take the POST and read data.
response.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "product": sendValues();
break;
}
}
}
// Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
// Do everything with $_POST's here
function sendValues(){
$return = $_POST;
$return["title"] = 'Something';
$return["json"] = json_encode($return);
echo json_encode($return); // Return JSON formatted data to Javascript.
}

jQuery Ajax(post), data not being received by PHP

The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}

PHP: Whois via AJAX

I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

Categories