Write non form data to xml using php - php

I am coding a video platform. When anyone sees the video and hit the like button the like should be incremented by one and should be written to xml file - I want to do this with php. And when the like symbol is clicked, the php should not be loaded but it should be executed.
Here is my code:
HTML:
<a href='#' onclick='doLike(id)'><i class='material-icons' style='float:bottom'>thumb_up</i></a>
JavaScript:
function doLike(id){
$.ajax({
type: "POST",
async: true,
url: "likup.php",
cache: false,
contentType: false,
processData: false,
error: function(){alert('Cannot reach file');},
success:
function(){
alert("Saved Successfully");
}
});}
PHP:
error_reporting(E_ALL);
$file = 'xml/shortfilm/filmname.xml';
$xml = simplexml_load_file($file);
$xml->Shortfilm[0]->like= 2;
But I am still unable to achieve what I want.

onclick='doLike(id)'
On click doList(id) will be called. What is id? Is it defined? You need to make sure that this parameter has the correct value. Your doLike does not send the id to the server. You need to send it, otherwise your server will not receive it. Your server, in turn should process the request and save the like into the xml.

Related

Upload image via Ajax

Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.

PHP script not echoing data when called via AJAX

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

Sending multiple variables in ajax

I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.

why is jqXHR.responseText returning my PHP file and not executing the script?

I'm trying to simply execute an ajax request to my server. The request passes my form data to signUp.php where the information is then process. Then php will echo back a responseText to my jqXHR object and I print the alert. The problem is that my php file is being executed, rather the jqXHR.responseText is instead returning the my php file itself as if it were a text file. A sample php responseTest would look like ...
"<?php
php code ...
?>"
Instead I want the responseText to return my echoes. The code is written bellow.
var formData = new FormData(document.getElementById("signUpForm"));
$.ajax({
url: "./cgi-script/signUp.php",
type: "POST",
xhr: function giveXmlHTTP(){
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function(data,statusText,jqXHR){
alert(jqXHR.responseText);
},
data:formData,
cache: false,
contentType: false,
processData: false
});
}
These generally happens when PHP does not gets parsed. So make sure you are running on the SERVER which is capable and configured to run PHP and are not double clicking the HTML page.
The two most common causes for this problem are that you are missing the initial <?php and that your server has not been set up for PHP. My guess is that when you just visit signUp.php you'll find the same problem.

Passing the ID to url string via jquery and then picking it by PHP without page refresh?

I want to pass the ID to the urlstring via jQuery without refreshing jQuery and # tag so that I could get the ID via php $_get['ID'] function.
But the problem is that
If I use #, page did not get refreshed, however PHP did pick the ID from url.
If I don't use #, then php do picks the ID but Page get refreshed.
I want to pass an id to php without refreshing the page.
//javascript
function com(id) {
location.href = '#?ID=id'; //by this way way,page doesn't refresh, ID appears in the url string but ID is not picked by PHP as # is there
// location.href = '?ID=id'; this way way, ID appears in the url string , ID is also picked by PHP as # is there.But page get refreshed.
$.ajax({
type: "Post",
url: "getdata.php",
async: true,
cache: false,
success: function(data) {},
});
}​
//php for getdata.php
<?php echo $_GET['ID']; ?>
You need to educate yourself about server-side vs. client-side operations. Javascript is client side. The server (running PHP in your case) knows nothing about what javascript is doing unless you send some information back. This can be accomplished via a page refresh or via ajax (put simplistically).
What you want is ajax which is an asynchronous request that goes back to the server. The server can then handle it and choose to pass information back to the page. Look into jQuery's ajax.
Update based on your updated comment:
function com(id) {
//forget about appending the id. This isn't doing anything.
//You can use it for informational purposes or so that if someone cuts and pastes
//the link you can handle it server side appropriately.
location.href = '#?ID=id';
//instead focus on this call. append your query string to the url
$.ajax({
type: "POST",
url: "getdata.php?ID=12345",
async: true,
cache: false,
success: function(data) {
alert(data); //should alert the id processed by php
},
});
}​

Categories